{"code": " public function testSmtpConnect()\n {\n $this->Mail->SMTPDebug = 4; //Show connection-level errors\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP single connect failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = \"ssl://localhost:12345;tls://localhost:587;10.10.10.10:54321;localhost:12345;10.10.10.10\";\n $this->assertFalse($this->Mail->smtpConnect(), 'SMTP bad multi-connect succeeded');\n $this->Mail->smtpClose();\n $this->Mail->Host = \"localhost:12345;10.10.10.10:54321;\" . $_REQUEST['mail_host'];\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP multi-connect failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = \" localhost:12345 ; \" . $_REQUEST['mail_host'] . ' ';\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP hosts with stray spaces failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = $_REQUEST['mail_host'];\n //Need to pick a harmless option so as not cause problems of its own! socket:bind doesn't work with Travis-CI\n $this->assertTrue(\n $this->Mail->smtpConnect(array('ssl' => array('verify_depth' => 10))),\n 'SMTP connect with options failed'\n );\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "function PMA_getErrorReportForm()\n{\n $html = \"\";\n $html .= '
'\n . '
';\n\n $html .= '

' . __(\n 'phpMyAdmin has encountered an error. We have collected data about'\n . ' this error as well as information about relevant configuration'\n . ' settings to send to the phpMyAdmin team to help us in'\n . ' debugging the problem.'\n ) . '

';\n\n $html .= '
'\n . '
'\n            . htmlspecialchars(PMA_getReportData())\n            . '
';\n\n $html .= '
'\n . '';\n\n $html .= ''\n . '';\n\n $html .= '
';\n\n $html .= PMA_URL_getHiddenInputs();\n\n $reportData = PMA_getReportData(false);\n if (! empty($reportData)) {\n $html .= PMA_getHiddenFields($reportData);\n }\n\n $html .= '
';\n\n return $html;\n}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "function PMA_Process_formset(FormDisplay $form_display)\n{\n if (isset($_GET['mode']) && $_GET['mode'] == 'revert') {\n // revert erroneous fields to their default values\n $form_display->fixErrors();\n PMA_generateHeader303();\n }\n\n if (!$form_display->process(false)) {\n // handle form view and failed POST\n $form_display->display(true, true);\n return;\n }\n\n // check for form errors\n if (!$form_display->hasErrors()) {\n PMA_generateHeader303();\n return;\n }\n\n // form has errors, show warning\n $separator = PMA_URL_getArgSeparator('html');\n $page = isset($_GET['page']) ? $_GET['page'] : null;\n $formset = isset($_GET['formset']) ? $_GET['formset'] : null;\n $formset = $formset ? \"{$separator}formset=$formset\" : '';\n $formId = PMA_isValid($_GET['id'], 'numeric') ? $_GET['id'] : null;\n if ($formId === null && $page == 'servers') {\n // we've just added a new server, get its id\n $formId = $form_display->getConfigFile()->getServerCount();\n }\n $formId = $formId ? \"{$separator}id=$formId\" : '';\n ?>\n
\n

\n
\n \n page=mode=revert\">\n \n \n
\n displayErrors() ?>\n \">\n \n  \n \n page=mode=edit\">\n explicit_key_length) {\n $this->setKeyLength(strlen($key) << 3);\n $this->explicit_key_length = false;\n }\n\n $this->key = $key;\n $this->changed = true;\n $this->_setEngine();\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " public function testCheckHTTP()\n {\n if (! function_exists('curl_init')) {\n $this->markTestSkipped('Missing curl extension!');\n }\n $this->assertTrue(\n $this->object->checkHTTP(\"https://www.phpmyadmin.net/test/data\")\n );\n $this->assertContains(\n \"TEST DATA\",\n $this->object->checkHTTP(\"https://www.phpmyadmin.net/test/data\", true)\n );\n $this->assertFalse(\n $this->object->checkHTTP(\"https://www.phpmyadmin.net/test/nothing\")\n );\n // Use rate limit API as it's not subject to rate limiting\n $this->assertContains(\n '\"resources\"',\n $this->object->checkHTTP(\"https://api.github.com/rate_limit\", true)\n );\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " public static function validateNumber(\n $path,\n $values,\n $allow_neg,\n $allow_zero,\n $max_value,\n $error_string\n ) {\n if (empty($values[$path])) {\n return '';\n }\n\n $value = Util::requestString($values[$path]);\n\n if (intval($value) != $value\n || (! $allow_neg && $value < 0)\n || (! $allow_zero && $value == 0)\n || $value > $max_value\n ) {\n return $error_string;\n }\n\n return '';\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " public function testCheckLoginPassEntity()\n {\n $login=checkLoginPassEntity('loginbidon', 'passwordbidon', 1, array('dolibarr'));\n print __METHOD__.\" login=\".$login.\"\\n\";\n $this->assertEquals($login, '');\n\n $login=checkLoginPassEntity('admin', 'passwordbidon', 1, array('dolibarr'));\n print __METHOD__.\" login=\".$login.\"\\n\";\n $this->assertEquals($login, '');\n\n $login=checkLoginPassEntity('admin', 'admin', 1, array('dolibarr')); // Should works because admin/admin exists\n print __METHOD__.\" login=\".$login.\"\\n\";\n $this->assertEquals($login, 'admin', 'The test to check if pass of user \"admin\" is \"admin\" has failed');\n\n $login=checkLoginPassEntity('admin', 'admin', 1, array('http','dolibarr')); // Should work because of second authetntication method\n print __METHOD__.\" login=\".$login.\"\\n\";\n $this->assertEquals($login, 'admin');\n\n $login=checkLoginPassEntity('admin', 'admin', 1, array('forceuser'));\n print __METHOD__.\" login=\".$login.\"\\n\";\n $this->assertEquals($login, ''); // Expected '' because should failed because login 'auto' does not exists\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-88", "cwe_name": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", "description": "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", "url": "https://cwe.mitre.org/data/definitions/88.html", "label_name": "safe"} {"code": "function barcode_print($code, $encoding=\"ANY\", $scale = 2 ,$mode = \"png\")\n{\n // DOLCHANGE LDR Add log\n dol_syslog(\"barcode.lib.php::barcode_print $code $encoding $scale $mode\");\n\n $bars=barcode_encode($code,$encoding);\n if (! $bars || ! empty($bars['error']))\n {\n // DOLCHANGE LDR Return error message instead of array\n if (empty($bars['error'])) $error='Bad Value '.$code.' for encoding '.$encoding;\n else $error=$bars['error'];\n dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR);\n return $error;\n }\n if (! $mode) $mode=\"png\";\n //if (preg_match(\"/^(text|txt|plain)$/i\",$mode)) print barcode_outtext($bars['text'],$bars['bars']);\n //elseif (preg_match(\"/^(html|htm)$/i\",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0);\n //else\n barcode_outimage($bars['text'], $bars['bars'], $scale, $mode);\n return $bars;\n}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "\tpublic function execute()\n\t{\n\t\tparent::execute();\n\n\t\t// get parameters\n\t\t$searchTerm = SpoonFilter::getPostValue('term', null, '');\n\t\t$term = (SPOON_CHARSET == 'utf-8') ? SpoonFilter::htmlspecialchars($searchTerm) : SpoonFilter::htmlentities($searchTerm);\n\n\t\t// validate\n\t\tif($term == '') $this->output(self::BAD_REQUEST, null, 'term-parameter is missing.');\n\n\t\t// previous search result\n\t\t$previousTerm = SpoonSession::exists('searchTerm') ? SpoonSession::get('searchTerm') : '';\n\t\tSpoonSession::set('searchTerm', '');\n\n\t\t// save this term?\n\t\tif($previousTerm != $term)\n\t\t{\n\t\t\t// format data\n\t\t\t$this->statistics = array();\n\t\t\t$this->statistics['term'] = $term;\n\t\t\t$this->statistics['language'] = FRONTEND_LANGUAGE;\n\t\t\t$this->statistics['time'] = FrontendModel::getUTCDate();\n\t\t\t$this->statistics['data'] = serialize(array('server' => $_SERVER));\n\t\t\t$this->statistics['num_results'] = FrontendSearchModel::getTotal($term);\n\n\t\t\t// save data\n\t\t\tFrontendSearchModel::save($this->statistics);\n\t\t}\n\n\t\t// save current search term in cookie\n\t\tSpoonSession::set('searchTerm', $term);\n\n\t\t// output\n\t\t$this->output(self::OK);\n\t}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\tpublic function check_forgot_password_token($token)\n\t{\n\t\t$salt = substr($token, 0, 32);\n\t\treturn $this->_forgot_password_token($salt) == $token;\n\t}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-640", "cwe_name": "Weak Password Recovery Mechanism for Forgotten Password", "description": "The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.", "url": "https://cwe.mitre.org/data/definitions/640.html", "label_name": "safe"} {"code": "\tpublic function get() {\n\t\t$r = '
'.htmlentities($this->stack_name).'
';\n\t\tfor ($i = 0; $i < count($this->tiles_array); $i++) {\n\t\t\t$top = rand(-5, 5);\n\t\t\t$left = rand(-5, 5);\n\t\t\t$img_w = $this->tiles_array[$i]->getWidth();\n\t\t\t$extra = '';\n\t\t\tif ($img_w < IMAGE_WIDTH) {\n\t\t\t\t$extra = 'width:'.$img_w.'px;';\n\t\t\t}\n\t\t\t$r .= '
tiles_array[$i]->getMiniatureSrc().'\\');margin-top:'.$top.'px; margin-left:'.$left.'px;'.$extra.'\">
';\n\t\t}\n\t\treturn $r;\n\t}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\tpublic function getOnClickAction() {\n\t\treturn 'javascript:openNewGal(\\''.htmlentities($this->stack_name).'\\');';\n\t}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\tfunction insertCommandCategorieInDB(){\n\t\tglobal $pearDB;\n\t\t\n\t\tif (testCommandCategorieExistence($_POST[\"category_name\"])){\n\t\t\t$DBRESULT = $pearDB->query(\"INSERT INTO `command_categories` (`category_name` , `category_alias`, `category_order`) VALUES ('\".$pearDB->escape($_POST[\"category_name\"]).\"', '\".$pearDB->escape($_POST[\"category_alias\"]).\"', '1')\");\n\t\t}\n\t}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "safe"} {"code": "function getTypes($subtype=\"both\") {\n\t$types = array(\"users\" => array(),\n\t \"resources\" => array());\n\tif($subtype == \"users\" || $subtype == \"both\") {\n\t\t$query = \"SELECT id, name FROM userprivtype\";\n\t\t$qh = doQuery($query, 365);\n\t\twhile($row = mysql_fetch_assoc($qh)) {\n\t\t\tif($row[\"name\"] == \"block\" || $row[\"name\"] == \"cascade\")\n\t\t\t\tcontinue;\n\t\t\t$types[\"users\"][$row[\"id\"]] = $row[\"name\"];\n\t\t}\n\t}\n\tif($subtype == \"resources\" || $subtype == \"both\") {\n\t\t$query = \"SELECT id, name FROM resourcetype\";\n\t\t$qh = doQuery($query, 366);\n\t\twhile($row = mysql_fetch_assoc($qh))\n\t\t\t$types[\"resources\"][$row[\"id\"]] = $row[\"name\"];\n\t}\n\treturn $types;\n}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "function XMLRPCaddNode($nodeName, $parentNode) {\n\trequire_once(\".ht-inc/privileges.php\");\n\tglobal $user;\n\tif(! is_numeric($parentNode)) {\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 78,\n\t\t 'errormsg' => 'Invalid nodeid specified');\n\t}\n\tif(in_array(\"nodeAdmin\", $user['privileges'])) {\n\t\t$nodeInfo = getNodeInfo($parentNode);\n\t\tif(is_null($tmp)) {\n\t\t\treturn array('status' => 'error',\n\t\t\t 'errorcode' => 78,\n\t\t\t 'errormsg' => 'Invalid nodeid specified');\n\t\t}\n\n\t\tif(! validateNodeName($nodeName, $tmp)) {\n\t\t\treturn array('status' => 'error',\n\t\t\t 'errorcode' => 81,\n\t\t\t 'errormsg' => 'Invalid node name');\n\t\t}\n\n\t\tif(checkUserHasPriv(\"nodeAdmin\", $user['id'], $parentNode)) {\n\t\t\t$query = \"SELECT id \"\n\t\t\t . \"FROM privnode \"\n\t\t\t . \"WHERE name = '$nodeName' AND parent = $parentNode\";\n\t\t\t$qh = doQuery($query);\n\t\t\tif(mysql_num_rows($qh)) {\n\t\t\t\treturn array('status' => 'error',\n\t\t\t\t 'errorcode' => 82,\n\t\t\t\t 'errormsg' => 'A node of that name already exists under ' . $nodeInfo['name']);\n\t\t\t}\n\t\t\t$query = \"INSERT IGNORE INTO privnode \"\n\t\t\t . \"(parent, name) \"\n\t\t\t . \"VALUES \"\n\t\t\t . \"($parentNode, '$nodeName')\";\n\t\t\tdoQuery($query);\n\t\t\t$qh = doQuery(\"SELECT LAST_INSERT_ID() FROM privnode\", 101);\n\t\t\tif(! $row = mysql_fetch_row($qh)) {\n\t\t\t\treturn array('status' => 'error',\n\t\t\t\t 'errorcode' => 85,\n\t\t\t\t 'errormsg' => 'Could not add node to database');\n\t\t\t}\n\t\t\t$nodeid = $row[0];\n\t\t\treturn array('status' => 'success',\n\t\t\t 'nodeid' => $nodeid);\n\t\t}\n\t\telse {\n\t\t\treturn array('status' => 'error',\n\t\t\t 'errorcode' => 49,\n\t\t\t 'errormsg' => 'Unable to add node at this location');\n\t\t}\n\t}\n\telse {\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 70,\n\t\t 'errormsg' => 'User cannot access node content');\n\t}\n}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "\t\t\t\tarray_push($images, array('id' => $imageid, 'name' => $image));\n\t\t}\n\t\treturn array('status' => 'success',\n\t\t 'images' => $images);\n\n\t}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "\t\t\t$privs = array_unique($allprivs);\n\t\t}\n\t\telseif(array_key_exists($key, $cnp['resources']))\n\t\t\t$privs = $cnp['resources'][$key];\n\t\telse\n\t\t\t$privs = array();\n\t\treturn array('status' => 'success',\n\t\t 'privileges' => $privs);\n\t}\n\telse {\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 71,\n\t\t 'errormsg' => 'Invalid resource type');\n\t}\n}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "function XMLRPCgetResourceGroups($type) {\n\tglobal $user;\n\t$resources = getUserResources(array(\"groupAdmin\"), array(\"manageGroup\"), 1);\n\tif(array_key_exists($type, $resources)) {\n\t\treturn array('status' => 'success',\n\t\t 'groups' => $resources[$type]);\n\t}\n\telse {\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 73,\n\t\t 'errormsg' => 'invalid resource group type');\n\t}\n}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "function HTMLPurifier($html, $config = null) {\n static $purifier = false;\n if (!$purifier) {\n $purifier = new HTMLPurifier();\n }\n return $purifier->purify($html, $config);\n}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " foreach ($attributes as $attribute => $x) {\n $allowed_attributes[\"$element.$attribute\"] = true;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function mungeRgb($string) {\n return preg_replace('/rgb\\((\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\)/', 'rgb(\\1,\\2,\\3)', $string);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $value = trim($value);\n $ok = false;\n do {\n if (isset($definition->info[$property])) {\n $ok = true;\n break;\n }\n if (ctype_lower($property)) break;\n $property = strtolower($property);\n if (isset($definition->info[$property])) {\n $ok = true;\n break;\n }\n } while(0);\n if (!$ok) continue;\n // inefficient call, since the validator will do this again\n if (strtolower(trim($value)) !== 'inherit') {\n // inherit works for everything (but only on the base property)\n $result = $definition->info[$property]->validate(\n $value, $config, $context );\n } else {\n $result = 'inherit';\n }\n if ($result === false) continue;\n $propvalues[$property] = $result;\n }\n\n $context->destroy('CurrentCSSProperty');\n\n // procedure does not write the new CSS simultaneously, so it's\n // slightly inefficient, but it's the only way of getting rid of\n // duplicates. Perhaps config to optimize it, but not now.\n\n $new_declarations = '';\n foreach ($propvalues as $prop => $value) {\n $new_declarations .= \"$prop:$value;\";\n }\n\n return $new_declarations ? $new_declarations : false;\n\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $r = $this->percentage->validate($bit, $config, $context);\n if ($r !== false) {\n $measures[] = $r;\n $i++;\n }\n\n }\n\n if (!$i) return false; // no valid values were caught\n\n $ret = array();\n\n // first keyword\n if ($keywords['h']) $ret[] = $keywords['h'];\n elseif ($keywords['ch']) {\n $ret[] = $keywords['ch'];\n $keywords['cv'] = false; // prevent re-use: center = center center\n }\n elseif (count($measures)) $ret[] = array_shift($measures);\n\n if ($keywords['v']) $ret[] = $keywords['v'];\n elseif ($keywords['cv']) $ret[] = $keywords['cv'];\n elseif (count($measures)) $ret[] = array_shift($measures);\n\n if (empty($ret)) return false;\n return implode(' ', $ret);\n\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function __construct() {\n $this->mask = '_- ';\n for ($c = 'a'; $c <= 'z'; $c++) $this->mask .= $c;\n for ($c = 'A'; $c <= 'Z'; $c++) $this->mask .= $c;\n for ($c = '0'; $c <= '9'; $c++) $this->mask .= $c; // cast-y, but should be fine\n // special bytes used by UTF-8\n for ($i = 0x80; $i <= 0xFF; $i++) {\n // We don't bother excluding invalid bytes in this range,\n // because the our restriction of well-formed UTF-8 will\n // prevent these from ever occurring.\n $this->mask .= chr($i);\n }\n\n /*\n PHP's internal strcspn implementation is\n O(length of string * length of mask), making it inefficient\n for large masks. However, it's still faster than\n preg_match 8)\n for (p = s1;;) {\n spanp = s2;\n do {\n if (*spanp == c || p == s1_end) {\n return p - s1;\n }\n } while (spanp++ < (s2_end - 1));\n c = *++p;\n }\n */\n // possible optimization: invert the mask.\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function __construct($min = null, $max = null) {\n $this->min = $min !== null ? HTMLPurifier_Length::make($min) : null;\n $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " foreach ($caught as $key => $status) {\n if ($status !== false) continue;\n $r = $this->info['list-style-' . $key]->validate($bit, $config, $context);\n if ($r === false) continue;\n if ($r === 'none') {\n if ($none) continue;\n else $none = true;\n if ($key == 'image') continue;\n }\n $caught[$key] = $r;\n $i++;\n break;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function __construct($max = null) {\n $this->max = $max;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " array_splice($first, 8 - count($second), 8, $second);\n $aIP = $first;\n unset($first,$second);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function __construct() {\n $this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels();\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function __construct($name, $css_name = null) {\n $this->name = $name;\n $this->cssName = $css_name ? $css_name : $name;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function set($type, $impl) {\n $this->info[$type] = $impl;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function doSetupTricky($config) {\n $this->info['display'] = new HTMLPurifier_AttrDef_Enum(array(\n 'inline', 'block', 'list-item', 'run-in', 'compact',\n 'marker', 'table', 'inline-block', 'inline-table', 'table-row-group',\n 'table-header-group', 'table-footer-group', 'table-row',\n 'table-column-group', 'table-column', 'table-cell', 'table-caption', 'none'\n ));\n $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum(array(\n 'visible', 'hidden', 'collapse'\n ));\n $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll'));\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " } elseif ($token instanceof HTMLPurifier_Token_End) {\n $nesting--;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function _compileRegex() {\n $raw = str_replace(' ', '', $this->dtd_regex);\n if ($raw{0} != '(') {\n $raw = \"($raw)\";\n }\n $el = '[#a-zA-Z0-9_.-]+';\n $reg = $raw;\n\n // COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M\n // DOING! Seriously: if there's problems, please report them.\n\n // collect all elements into the $elements array\n preg_match_all(\"/$el/\", $reg, $matches);\n foreach ($matches[0] as $match) {\n $this->elements[$match] = true;\n }\n\n // setup all elements as parentheticals with leading commas\n $reg = preg_replace(\"/$el/\", '(,\\\\0)', $reg);\n\n // remove commas when they were not solicited\n $reg = preg_replace(\"/([^,(|]\\(+),/\", '\\\\1', $reg);\n\n // remove all non-paranthetical commas: they are handled by first regex\n $reg = preg_replace(\"/,\\(/\", '(', $reg);\n\n $this->_pcre_regex = $reg;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $result[] = new HTMLPurifier_Token_Start('li', $t->attr, $t->line, $t->col, $t->armor);\n break;\n } else {\n if (!$t->is_whitespace) {\n trigger_error(\"Only whitespace present invariant violated in List ChildDef\", E_USER_ERROR);\n return false;\n }\n }\n }\n }\n } else {\n // start wrapping (this doesn't precisely mimic\n // browser behavior, but what browsers do is kind of\n // hard to mimic in a standards compliant way\n // XXX Actually, this has no impact in practice,\n // because this gets handled earlier. Arguably,\n // we should rip out all of that processing\n $result[] = new HTMLPurifier_Token_Start('li');\n $nesting++;\n $seen_li = true;\n $need_close_li = true;\n }\n }\n $result[] = $token;\n }\n if ($need_close_li) {\n $result[] = new HTMLPurifier_Token_End('li');\n }\n if (empty($result)) return false;\n if ($all_whitespace) {\n return false;\n }\n if ($tokens_of_children == $result) return true;\n return $result;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " if (empty($i)) unset($elements[$i]); // remove blank\n }\n }\n $this->elements = $elements;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $ret = array_merge($ret, $token_array);\n }\n }\n\n if (!empty($collection) && $is_collecting == false){\n // grab the trailing space\n $ret = array_merge($ret, $collection);\n }\n\n array_pop($tokens_of_children); // remove phantom token\n\n return ($ret === $tokens_of_children) ? true : $ret;\n\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function __construct($definition, $parent = null) {\n $parent = $parent ? $parent : $definition->defaultPlist;\n $this->plist = new HTMLPurifier_PropertyList($parent);\n $this->def = $definition; // keep a copy around for checking\n $this->parser = new HTMLPurifier_VarParser_Flexible();\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function getBatchSerial($namespace) {\n if (empty($this->serials[$namespace])) {\n $batch = $this->getBatch($namespace);\n unset($batch['DefinitionRev']);\n $this->serials[$namespace] = sha1(serialize($batch));\n }\n return $this->serials[$namespace];\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $this->set($namespace .'.'. $directive, $value);\n }\n }\n }\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " private function _listify($lookup) {\n $list = array();\n foreach ($lookup as $name => $b) $list[] = $name;\n return implode(', ', $list);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function _findUnused($hash) {\n $accessed = $hash->getAccessed();\n foreach ($hash as $k => $v) {\n if (!isset($accessed[$k])) {\n trigger_error(\"String hash key '$k' not used by builder\", E_USER_NOTICE);\n }\n }\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function evalArray($contents) {\n return eval('return array('. $contents .');');\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function error($target, $msg) {\n if ($target !== false) $prefix = ucfirst($target) . ' in ' . $this->getFormattedContext();\n else $prefix = ucfirst($this->getFormattedContext());\n throw new HTMLPurifier_ConfigSchema_Exception(trim($prefix . ' ' . $msg));\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function assertIsString() {\n if (!is_string($this->contents)) $this->error('must be a string');\n return $this;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function error($msg) {\n throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function getChildDef($def, $module) {\n $value = $def->content_model;\n if (is_object($value)) {\n trigger_error(\n 'Literal object child definitions should be stored in '.\n 'ElementDef->child not ElementDef->content_model',\n E_USER_NOTICE\n );\n return $value;\n }\n switch ($def->content_model_type) {\n case 'required':\n return new HTMLPurifier_ChildDef_Required($value);\n case 'optional':\n return new HTMLPurifier_ChildDef_Optional($value);\n case 'empty':\n return new HTMLPurifier_ChildDef_Empty();\n case 'custom':\n return new HTMLPurifier_ChildDef_Custom($value);\n }\n // defer to its module\n $return = false;\n if ($module->defines_child_def) { // save a func call\n $return = $module->getChildDef($def);\n }\n if ($return !== false) return $return;\n // error-out\n trigger_error(\n 'Could not determine which ChildDef class to instantiate',\n E_USER_ERROR\n );\n return false;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function register($name, &$ref) {\n if (isset($this->_storage[$name])) {\n trigger_error(\"Name $name produces collision, cannot re-register\",\n E_USER_ERROR);\n return;\n }\n $this->_storage[$name] =& $ref;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function __construct($type) {\n $this->type = $type;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function get($config) {\n return $this->cache->get($config);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function cleanup($config) {\n return $this->cache->cleanup($config);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function set($def, $config) {\n $status = parent::set($def, $config);\n if ($status) $this->definitions[$this->generateKey($config)] = $def;\n return $status;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function replace($def, $config) {\n $status = parent::replace($def, $config);\n if ($status) $this->definitions[$this->generateKey($config)] = $def;\n return $status;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function generateFilePath($config) {\n $key = $this->generateKey($config);\n return $this->generateDirectoryPath($config) . '/' . $key . '.ser';\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " private function _prepareDir($config) {\n $directory = $this->generateDirectoryPath($config);\n $chmod = $config->get('Cache.SerializerPermissions');\n if (!$chmod) {\n $chmod = 0755; // invalid config or simpletest\n }\n if (!is_dir($directory)) {\n $base = $this->generateBaseDirectoryPath($config);\n if (!is_dir($base)) {\n trigger_error('Base directory '.$base.' does not exist,\n please create or change using %Cache.SerializerPath',\n E_USER_WARNING);\n return false;\n } elseif (!$this->_testPermissions($base, $chmod)) {\n return false;\n }\n $old = umask(0000);\n mkdir($directory, $chmod);\n umask($old);\n } elseif (!$this->_testPermissions($directory, $chmod)) {\n return false;\n }\n return true;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " foreach ($doctype->aliases as $alias) {\n if (isset($this->doctypes[$alias])) continue;\n $this->aliases[$alias] = $name;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public static function create($content_model, $content_model_type, $attr) {\n $def = new HTMLPurifier_ElementDef();\n $def->content_model = $content_model;\n $def->content_model_type = $content_model_type;\n $def->attr = $attr;\n return $def;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function substituteNonSpecialEntities($string) {\n // it will try to detect missing semicolons, but don't rely on it\n return preg_replace_callback(\n $this->_substituteEntitiesRegex,\n array($this, 'nonSpecialEntityCallback'),\n $string\n );\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function substituteSpecialEntities($string) {\n return preg_replace_callback(\n $this->_substituteEntitiesRegex,\n array($this, 'specialEntityCallback'),\n $string);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function __construct($context) {\n $this->locale =& $context->get('Locale');\n $this->context = $context;\n $this->_current =& $this->_stacks[0];\n $this->errors =& $this->_stacks[0];\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function postFilterCallback($matches) {\n $url = $this->armorUrl($matches[1]);\n return ''.\n ''.\n ''.\n '';\n\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function preFilter($html, $config, $context) {\n $pre_regex = '#]+>.+?'.\n 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\\-_=]+).+?#s';\n $pre_replace = '\\1';\n return preg_replace($pre_regex, $pre_replace, $html);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $attr = $this->generateAttributes($token->attr, $token->name);\n if ($this->_flashCompat) {\n if ($token->name == \"object\") {\n $flash = new stdclass();\n $flash->attr = $token->attr;\n $flash->param = array();\n $this->_flashStack[] = $flash;\n }\n }\n return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';\n\n } elseif ($token instanceof HTMLPurifier_Token_End) {", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function generateScriptFromToken($token) {\n if (!$token instanceof HTMLPurifier_Token_Text) return $this->generateFromToken($token);\n // Thanks \n $data = preg_replace('#//\\s*$#', '', $token->data);\n return '';\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected function processModules($config) {\n\n if ($this->_anonModule) {\n // for user specific changes\n // this is late-loaded so we don't have to deal with PHP4\n // reference wonky-ness\n $this->manager->addModule($this->_anonModule);\n unset($this->_anonModule);\n }\n\n $this->manager->setup($config);\n $this->doctype = $this->manager->doctype;\n\n foreach ($this->manager->modules as $module) {\n foreach($module->info_tag_transform as $k => $v) {\n if ($v === false) unset($this->info_tag_transform[$k]);\n else $this->info_tag_transform[$k] = $v;\n }\n foreach($module->info_attr_transform_pre as $k => $v) {\n if ($v === false) unset($this->info_attr_transform_pre[$k]);\n else $this->info_attr_transform_pre[$k] = $v;\n }\n foreach($module->info_attr_transform_post as $k => $v) {\n if ($v === false) unset($this->info_attr_transform_post[$k]);\n else $this->info_attr_transform_post[$k] = $v;\n }\n foreach ($module->info_injector as $k => $v) {\n if ($v === false) unset($this->info_injector[$k]);\n else $this->info_injector[$k] = $v;\n }\n }\n\n $this->info = $this->manager->getElements();\n $this->info_content_sets = $this->manager->contentSets->lookup;\n\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function setup($config) {}", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function setup($config) {\n\n $this->addElement('marquee', 'Inline', 'Flow', 'Common',\n array(\n 'direction' => 'Enum#left,right,up,down',\n 'behavior' => 'Enum#alternate',\n 'width' => 'Length',\n 'height' => 'Length',\n 'scrolldelay' => 'Number',\n 'scrollamount' => 'Number',\n 'loop' => 'Number',\n 'bgcolor' => 'Color',\n 'hspace' => 'Pixels',\n 'vspace' => 'Pixels',\n )\n );\n\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function setup($config) {\n $this->addElement('ruby', 'Inline',\n 'Custom: ((rb, (rt | (rp, rt, rp))) | (rbc, rtc, rtc?))',\n 'Common');\n $this->addElement('rbc', false, 'Required: rb', 'Common');\n $this->addElement('rtc', false, 'Required: rt', 'Common');\n $rb = $this->addElement('rb', false, 'Inline', 'Common');\n $rb->excludes = array('ruby' => true);\n $rt = $this->addElement('rt', false, 'Inline', 'Common', array('rbspan' => 'Number'));\n $rt->excludes = array('ruby' => true);\n $this->addElement('rp', false, 'Optional: #PCDATA', 'Common');\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function setup($config) {\n\n // create fixes, initialize fixesForLevel\n $fixes = $this->makeFixes();\n $this->makeFixesForLevel($fixes);\n\n // figure out which fixes to use\n $level = $config->get('HTML.TidyLevel');\n $fixes_lookup = $this->getFixesForLevel($level);\n\n // get custom fix declarations: these need namespace processing\n $add_fixes = $config->get('HTML.TidyAdd');\n $remove_fixes = $config->get('HTML.TidyRemove');\n\n foreach ($fixes as $name => $fix) {\n // needs to be refactored a little to implement globbing\n if (\n isset($remove_fixes[$name]) ||\n (!isset($add_fixes[$name]) && !isset($fixes_lookup[$name]))\n ) {\n unset($fixes[$name]);\n }\n }\n\n // populate this module with necessary fixes\n $this->populate($fixes);\n\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function makeFixes() {\n $r = array();\n $r['@lang'] = new HTMLPurifier_AttrTransform_Lang();\n return $r;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " foreach ($module->info as $name => $def) {\n if (!isset($this->elementLookup[$name])) {\n $this->elementLookup[$name] = array();\n }\n $this->elementLookup[$name][] = $module->name;\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function handleText(&$token) {\n if (!$this->allowsElement('a')) return;\n if (strpos($token->data, '%') === false) return;\n\n $bits = preg_split('#%([a-z0-9]+\\.[a-z0-9]+)#Si', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);\n $token = array();\n\n // $i = index\n // $c = count\n // $l = is link\n for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {\n if (!$l) {\n if ($bits[$i] === '') continue;\n $token[] = new HTMLPurifier_Token_Text($bits[$i]);\n } else {\n $token[] = new HTMLPurifier_Token_Start('a',\n array('href' => str_replace('%s', $bits[$i], $this->docURL)));\n $token[] = new HTMLPurifier_Token_Text('%' . $bits[$i]);\n $token[] = new HTMLPurifier_Token_End('a');\n }\n }\n\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function prepare($config, $context) {\n $this->attrValidator = new HTMLPurifier_AttrValidator();\n $this->config = $config;\n $this->context = $context;\n return parent::prepare($config, $context);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function handleEnd(&$token) {\n if ($token->markForDeletion) {\n $token = false;\n }\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function tokenizeHTML($string, $config, $context) {\n trigger_error('Call to abstract class', E_USER_ERROR);\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " protected static function CDATACallback($matches) {\n // not exactly sure why the character set is needed, but whatever\n return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');\n }", "label": 1, "programming_language": "PHP", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public function callbackArmorCommentEntities($matches) {\n return '\",e[0];)return b>4?b:a},doubleTapToGo:function(a) {var b=this.element;return a.hasClass(\"doubleTapToGo\")?(a.removeClass(\"doubleTapToGo\"),!0):a.parent().children(\"ul\").length?(b.find(\".doubleTapToGo\").removeClass(\"doubleTapToGo\"),a.addClass(\"doubleTapToGo\"),!1):void 0},remove:function() {this.element.off(\".\"+e),this.element.removeData(e)}},a.fn[e]=function(b) {return this.each(function() {var c=a(this);c.data(e)&&c.data(e).remove(),c.data(e,new d(this,b))}),this}}(jQuery,window,document);", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " convertChangesToXML: function(changes) {\n var ret = [];\n for ( var i = 0; i < changes.length; i++) {\n var change = changes[i];\n if (change.added) {\n ret.push('');\n } else if (change.removed) {\n ret.push('');\n }\n\n ret.push(escapeHTML(change.value));\n\n if (change.added) {\n ret.push('');\n } else if (change.removed) {\n ret.push('');\n }\n }\n return ret.join('');\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "Mocha.prototype.timeout = function(timeout) {\n this.suite.timeout(timeout);\n return this;\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "Runner.prototype.runSuite = function(suite, fn) {\n var total = this.grepTotal(suite)\n , self = this\n , i = 0;\n\n debug('run suite %s', suite.fullTitle());\n\n if (!total) return fn();\n\n this.emit('suite', this.suite = suite);\n\n function next(errSuite) {\n if (errSuite) {\n // current suite failed on a hook from errSuite\n if (errSuite == suite) {\n // if errSuite is current suite\n // continue to the next sibling suite\n return done();\n } else {\n // errSuite is among the parents of current suite\n // stop execution of errSuite and all sub-suites\n return done(errSuite);\n }\n }\n\n if (self._abort) return done();\n\n var curr = suite.suites[i++];\n if (!curr) return done();\n self.runSuite(curr, next);\n }\n\n function done(errSuite) {\n self.suite = suite;\n self.hook('afterAll', function() {\n self.emit('suite end', suite);\n fn(errSuite);\n });\n }\n\n this.hook('beforeAll', function(err) {\n if (err) return done();\n self.runTests(suite, next);\n });\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "function Context() {}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " function uncaught(err) {\n self.uncaught(err);\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " beginningOfLine: function() {\n isatty && process.stdout.write('\\u001b[0G');\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "module.exports = function(type) {\n return function() {\n }\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "module.exports = function(val, options) {\n options = options || {};\n if ('string' == typeof val) return parse(val);\n return options.long ? longFormat(val) : shortFormat(val);\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "Suite.prototype.afterAll = function(fn) {\n if (this.pending) return this;\n var hook = new Hook('\"after all\" hook', fn);\n hook.parent = this;\n hook.timeout(this.timeout());\n hook.slow(this.slow());\n hook.ctx = this.ctx;\n this._afterAll.push(hook);\n this.emit('afterAll', hook);\n return this;\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "Runner.prototype.runTest = function(fn) {\n var test = this.test\n , self = this;\n\n if (this.asyncOnly) test.asyncOnly = true;\n\n try {\n test.on('error', function(err) {\n self.fail(test, err);\n });\n test.run(fn);\n } catch (err) {\n fn(err);\n }\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " , fn = fn || function() {};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " context.test.only = function(title, fn) {\n var test = context.test(title, fn);\n var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';\n mocha.grep(new RegExp(reString));\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "NyanCat.prototype.face = function() {\n var stats = this.stats;\n if (stats.failures) {\n return '( x .x)';\n } else if (stats.pending) {\n return '( o .o)';\n } else if (stats.passes) {\n return '( ^ .^)';\n } else {\n return '( - .-)';\n }\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "NyanCat.prototype.rainbowify = function(str) {\n var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];\n this.colorIndex += 1;\n return '\\u001b[38;5;' + color + 'm' + str + '\\u001b[0m';\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "Context.prototype.slow = function(ms) {\n this.runnable().slow(ms);\n return this;\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "function fragment(html) {\n var args = arguments\n , div = document.createElement('div')\n , i = 1;\n\n div.innerHTML = html.replace(/%([se])/g, function(_, type) {\n switch (type) {\n case 's': return String(args[i++]);\n case 'e': return escape(args[i++]);\n }\n });\n\n return div.firstChild;\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "function List(runner) {\n Base.call(this, runner);\n\n var self = this\n , stats = this.stats\n , total = runner.total;\n\n runner.on('start', function() {\n console.log(JSON.stringify(['start', { total: total }]));\n });\n\n runner.on('pass', function(test) {\n console.log(JSON.stringify(['pass', clean(test)]));\n });\n\n runner.on('fail', function(test, err) {\n console.log(JSON.stringify(['fail', clean(test)]));\n });\n\n runner.on('end', function() {\n process.stdout.write(JSON.stringify(['end', self.stats]));\n });\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "process.on = function(e, fn) {\n if ('uncaughtException' == e) {\n global.onerror = function(err, url, line) {\n fn(new Error(err + ' (' + url + ':' + line + ')'));\n return true;\n };\n uncaughtExceptionHandlers.push(fn);\n }\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " Area.prototype.drawSeries = function() {\n var i, range, _i, _j, _k, _len, _ref, _ref1, _results, _results1, _results2;\n this.seriesPoints = [];\n if (this.options.behaveLikeLine) {\n range = (function() {\n _results = [];\n for (var _i = 0, _ref = this.options.ykeys.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; 0 <= _ref ? _i++ : _i--) { _results.push(_i); }\n return _results;\n }).apply(this);\n } else {\n range = (function() {\n _results1 = [];\n for (var _j = _ref1 = this.options.ykeys.length - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; _ref1 <= 0 ? _j++ : _j--) { _results1.push(_j); }\n return _results1;\n }).apply(this);\n }\n _results2 = [];\n for (_k = 0, _len = range.length; _k < _len; _k++) {\n i = range[_k];\n this._drawFillFor(i);\n this._drawLineFor(i);\n _results2.push(this._drawPointFor(i));\n }\n return _results2;\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\tthis.path2array = function(hash, i18) {\n\t\tvar file, \n\t\t\tpath = [];\n\t\t\t\n\t\twhile (hash && (file = files[hash]) && file.hash) {\n\t\t\tpath.unshift(i18 && file.i18 ? file.i18 : file.name);\n\t\t\thash = file.phash;\n\t\t}\n\t\t\t\n\t\treturn path;\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\t\thelper : function(e) {\n\t\t\t\t\tvar dir = $(e.target).parent();\n\t\t\t\t\t\t\n\t\t\t\t\tdir.children().removeClass('ui-state-hover');\n\t\t\t\t\t\n\t\t\t\t\treturn $('
')\n\t\t\t\t\t\t\t.append($('
').show().append(dir.clone()));\n\n\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\t\t\t\t\tdata : {cmd : 'netmount', protocol: 'googledrive', host: 'google.com', user: 'init', options: {id: fm.id, offline: oline.prop('checked')? 1:0, pass: f.host[1].value}},\n\t\t\t\t\t\t\tpreventDefault : true\n\t\t\t\t\t\t}).done(function(data) {\n\t\t\t\t\t\t\t$(f.host[0]).removeClass(\"elfinder-info-spinner\").html(data.body.replace(/\\{msg:([^}]+)\\}/g, function(whole,s1) {return fm.i18n(s1,'Google.com');}));\n\t\t\t\t\t\t}).fail(function() {});\n\t\t\t\t\t} else {\n\t\t\t\t\t\toline.parent().parent()[f.user.val()? 'hide':'show']();\n\t\t\t\t\t}\n\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\tcompare = function(dir1, dir2) {\n\t\t\t\treturn fm.naturalCompare(dir1.i18 || dir1.name, dir2.i18 || dir2.name);\n\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\tthis.returnBytes = function(val) {\n\t\tvar last;\n\t\tif (isNaN(val)) {\n\t\t\tif (! val) {\n\t\t\t\tval = '';\n\t\t\t}\n\t\t\t// for ex. 1mb, 1KB\n\t\t\tval = val.replace(/b$/i, '');\n\t\t\tlast = val.charAt(val.length - 1).toLowerCase();\n\t\t\tval = val.replace(/[tgmk]$/i, '');\n\t\t\tif (last == 't') {\n\t\t\t\tval = val * 1024 * 1024 * 1024 * 1024;\n\t\t\t} else if (last == 'g') {\n\t\t\t\tval = val * 1024 * 1024 * 1024;\n\t\t\t} else if (last == 'm') {\n\t\t\t\tval = val * 1024 * 1024;\n\t\t\t} else if (last == 'k') {\n\t\t\t\tval = val * 1024;\n\t\t\t}\n\t\t\tval = isNaN(val)? 0 : parseInt(val);\n\t\t} else {\n\t\t\tval = parseInt(val);\n\t\t\tif (val < 1) val = 0;\n\t\t}\n\t\treturn val;\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\t\t\tnavbarUp : function() {\n\t\t\t\t\t\tnavbar.scrollTop(Math.max(0, navbar.scrollTop() - helper.data('autoScrVal')));\n\t\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\tthis.cwd = function() {\n\t\treturn files[cwd] || {};\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "G.prototype.B=function() {var e,c=this.a;u?this.z?(e=new Uint8Array(c),e.set(this.b.subarray(0,c))):e=this.b.subarray(0,c):(this.b.length>c&&(this.b.length=c),e=this.b);return this.buffer=e};function $(e) {this.input=e;this.c=0;this.m=[];this.s=!1}$.prototype.G=function() {this.s||this.g();return this.m.slice()};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\tsetcheck = function(perm) {\n\t\t\tvar _perm;\n\t\t\tfor (var i = 0; i < 3; i++) {\n\t\t\t\t_perm = parseInt(perm.slice(i, i+1), 8);\n\t\t\t\t$(\"#\"+id+\"-read-\"+level[i]+'-perm').prop(\"checked\", false);\n\t\t\t\t$(\"#\"+id+\"-write-\"+level[i]+'-perm').prop(\"checked\", false);\n\t\t\t\t$(\"#\"+id+\"-execute-\"+level[i]+'-perm').prop(\"checked\", false);\n\t\t\t\tif ((_perm & 4) == 4) {\n\t\t\t\t\t$(\"#\"+id+\"-read-\"+level[i]+'-perm').prop(\"checked\", true);\n\t\t\t\t}\n\t\t\t\tif ((_perm & 2) == 2) {\n\t\t\t\t\t$(\"#\"+id+\"-write-\"+level[i]+'-perm').prop(\"checked\", true);\n\t\t\t\t}\n\t\t\t\tif ((_perm & 1) == 1) {\n\t\t\t\t\t$(\"#\"+id+\"-execute-\"+level[i]+'-perm').prop(\"checked\", true);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsetperm();\n\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "elFinder.prototype.commands.home = function() {\n\tthis.title = 'Home';\n\tthis.alwaysEnabled = true;\n\tthis.updateOnSelect = false;\n\tthis.shortcuts = [{\n\t\tpattern : 'ctrl+home ctrl+shift+up',\n\t\tdescription : 'Home'\n\t}];\n\t\n\tthis.getstate = function() {\n\t\tvar root = this.fm.root(),\n\t\t\tcwd = this.fm.cwd().hash;\n\t\t\t\n\t\treturn root && cwd && root != cwd ? 0: -1;\n\t}\n\t\n\tthis.exec = function() {\n\t\treturn this.fm.exec('open', this.fm.root());\n\t}\n\t\n\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "936918E3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],z=u?new Uint32Array(A):A;function B() {}B.prototype.getName=function() {return this.name};B.prototype.getData=function() {return this.data};B.prototype.H=function() {return this.I};r(\"Zlib.GunzipMember\",B);r(\"Zlib.GunzipMember.prototype.getName\",B.prototype.getName);r(\"Zlib.GunzipMember.prototype.getData\",B.prototype.getData);r(\"Zlib.GunzipMember.prototype.getMtime\",B.prototype.H);function D(e) {var c=e.length,d=0,b=Number.POSITIVE_INFINITY,a,f,g,k,m,p,t,h,l,y;for(h=0;hd&&(d=e[h]),e[h]>=1;y=g<<16|h;for(l=p;lF;F++)switch(!0) {case 143>=F:E.push([F+48,8]);break;case 255>=F:E.push([F-144+400,9]);break;case 279>=F:E.push([F-256+0,7]);break;case 287>=F:E.push([F-280+192,8]);break;default:n(\"invalid literal: \"+F)}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\t\t\topen : function() {\n\t\t\t\t\t\tfm.bind('resize', dinit);\n\t\t\t\t\t\timg.attr('src', src + (src.indexOf('?') === -1 ? '?' : '&')+'_='+Math.random());\n\t\t\t\t\t\timgc.attr('src', img.attr('src'));\n\t\t\t\t\t\timgr.attr('src', img.attr('src'));\n\t\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\t\t\tnavbarDown : function() {\n\t\t\t\t\t\tnavbar.scrollTop(navbar.scrollTop() + helper.data('autoScrVal'));\n\t\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\tmoveup = function(hash) {\n\t\t\t\tvar self = $('#'+hash2id(hash)),\n\t\t\t\t\ttgt = self.parent(),\n\t\t\t\t\tprev = tgt.prev('div'),\n\t\t\t\t\tcls = 'ui-state-hover',\n\t\t\t\t\tctm = fm.getUI('contextmenu');\n\t\t\t\t\n\t\t\t\tmenuTimer && clearTimeout(menuTimer);\n\t\t\t\t\n\t\t\t\tif (prev.length) {\n\t\t\t\t\tctm.find(':first').data('placesHash', hash);\n\t\t\t\t\tself.addClass(cls);\n\t\t\t\t\ttgt.insertBefore(prev);\n\t\t\t\t\tprev = tgt.prev('div');\n\t\t\t\t\tmenuTimer = setTimeout(function() {\n\t\t\t\t\t\tself.removeClass(cls);\n\t\t\t\t\t\tif (ctm.find(':first').data('placesHash') === hash) {\n\t\t\t\t\t\t\tctm.hide().empty();\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 1500);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!prev.length) {\n\t\t\t\t\tself.removeClass(cls);\n\t\t\t\t\tctm.hide().empty();\n\t\t\t\t}\n\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\t\tbuttons : (fm.command('zipdl') && fm.isCommandEnabled('zipdl', fm.cwd().hash))? [\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel : 'cmddownload',\n\t\t\t\t\t\tcallback : function() {\n\t\t\t\t\t\t\tfm.exec('download', hashes);\n\t\t\t\t\t\t\tdfrd.reject();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t] : []\n\t\t\t});\n\t\t} else {", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "u.S=function() {var a,b=this.a;w?this.L?(a=new Uint8Array(b),a.set(this.b.subarray(0,b))):a=this.b.subarray(0,b):(this.b.length>b&&(this.b.length=b),a=this.b);return this.buffer=a};function V(a) {a=a||{};this.files=[];this.v=a.comment}V.prototype.M=function(a) {this.j=a};V.prototype.s=function(a) {var b=a[2]&65535|2;return b*(b^1)>>8&255};V.prototype.k=function(a,b) {a[0]=(B[(a[0]^b)&255]^a[0]>>>8)>>>0;a[1]=(6681*(20173*(a[1]+(a[0]&255))>>>0)>>>0)+1>>>0;a[2]=(B[(a[2]^a[1]>>>24)&255]^a[2]>>>8)>>>0};V.prototype.U=function(a) {var b=[305419896,591751049,878082192],c,d;w&&(b=new Uint32Array(b));c=0;for(d=a.length;c 1)) {\n\t\t\t\t\td.options.disabled = isOutView(d.element);\n\t\t\t\t\td.options.autoDisable = d.options.disabled? 2 : 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// call origin function\n\t\treturn origin( t, event );\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "oa.prototype.parse=function() {var a=this.input,b=this.offset;(a[b++]!==X[0]||a[b++]!==X[1]||a[b++]!==X[2]||a[b++]!==X[3])&&m(Error(\"invalid file header signature\"));this.version=a[b++];this.ja=a[b++];this.$=a[b++]|a[b++]<<8;this.I=a[b++]|a[b++]<<8;this.A=a[b++]|a[b++]<<8;this.time=a[b++]|a[b++]<<8;this.V=a[b++]|a[b++]<<8;this.p=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.z=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.J=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.h=a[b++]|a[b++]<<\n8;this.g=a[b++]|a[b++]<<8;this.F=a[b++]|a[b++]<<8;this.fa=a[b++]|a[b++]<<8;this.ha=a[b++]|a[b++]<<8;this.ga=a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24;this.aa=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.filename=String.fromCharCode.apply(null,w?a.subarray(b,b+=this.h):a.slice(b,b+=this.h));this.Y=w?a.subarray(b,b+=this.g):a.slice(b,b+=this.g);this.v=w?a.subarray(b,b+this.F):a.slice(b,b+this.F);this.length=b-this.offset};function pa(a,b) {this.input=a;this.offset=b}var qa={O:1,da:8,ea:2048};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\tstop : function(e, ui) {\n\t\t\tvar helper = ui.helper,\n\t\t\t\tfiles;\n\t\t\t\n\t\t\t$(this).elfUiWidgetInstance('draggable') && $(this).draggable('option', { refreshPositions : false });\n\t\t\tself.draggingUiHelper = null;\n\t\t\tself.trigger('focus').trigger('dragstop');\n\t\t\tif (! helper.data('droped')) {\n\t\t\t\tfiles = $.map(helper.data('files')||[], function(h) { return h || null ;});\n\t\t\t\tself.trigger('unlockfiles', {files : files});\n\t\t\t\tself.trigger('selectfiles', {files : files});\n\t\t\t}\n\t\t\tself.enable();\n\t\t\t\n\t\t\thelper.data('autoScrTm') && clearInterval(helper.data('autoScrTm'));\n\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\tthis.exec = function(hashes, sortopt) {\n\t\tvar fm = this.fm,\n\t\t\tsort = $.extend({\n\t\t\t\ttype : fm.sortType,\n\t\t\t\torder : fm.sortOrder,\n\t\t\t\tstick : fm.sortStickFolders\n\t\t\t}, sortopt);\n\n\t\treturn fm.lazy(function() {\n\t\t\tfm.setSort(sort.type, sort.order, sort.stick);\n\t\t\tthis.resolve();\n\t\t});\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\t\t\t\t\tcallback:function (all) {\n\t\t\t\t\t\t\t\tdecision = all ? 'overwrite_all' : 'overwrite';\n\t\t\t\t\t\t\t\tdecide(decision);\n\t\t\t\t\t\t\t\tif (!overwriteAll && !omitAll) {\n\t\t\t\t\t\t\t\t\tif ('overwrite' == decision) {\n\t\t\t\t\t\t\t\t\t\tunpack(file);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif ((index+1) < cnt) {\n\t\t\t\t\t\t\t\t\t\tconfirm(files, index+1);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tdfrd.resolve();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (overwriteAll) {\n\t\t\t\t\t\t\t\t\tfor (i = index; i < cnt; i++) {\n\t\t\t\t\t\t\t\t\t\tunpack(files[i]);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdfrd.resolve();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " mouseProto._touchEnd = function (event) {\n\n\t// Ignore event if not handled\n\tif (!touchHandled) {\n\t return;\n\t}\n\n\t// Simulate the mouseup event\n\tsimulateMouseEvent(event, 'mouseup');\n\n\t// Simulate the mouseout event\n\tsimulateMouseEvent(event, 'mouseout');\n\n\t// If the touch interaction did not move, it should trigger a click\n\tif (!this._touchMoved) {\n\n\t // Simulate the click event\n\t simulateMouseEvent(event, 'click');\n\t}\n\n\t// Unset the flag to allow other widgets to inherit the touch event\n\ttouchHandled = false;\n\tthis._touchMoved = false;\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\tthis.validResponse = function(cmd, data) {\n\t\treturn data.error || this.rules[this.rules[cmd] ? cmd : 'defaults'](data);\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "k.p.toString(16)+\", data=0x\"+p.toString(16)))}return l};u.M=function(a) {this.j=a};function ra(a,b,c) {c^=a.s(b);a.k(b,c);return c}u.k=V.prototype.k;u.T=V.prototype.U;u.s=V.prototype.s;v(\"Zlib.Unzip\",W);v(\"Zlib.Unzip.prototype.decompress\",W.prototype.r);v(\"Zlib.Unzip.prototype.getFilenames\",W.prototype.Z);v(\"Zlib.Unzip.prototype.setPassword\",W.prototype.M);}).call(this);", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\tthis.url = function(hash) {\n\t\tvar file = files[hash];\n\t\t\n\t\tif (!file || !file.read) {\n\t\t\treturn '';\n\t\t}\n\t\t\n\t\tif (file.url == '1') {\n\t\t\tthis.request({\n\t\t\t\tdata : {cmd : 'url', target : hash},\n\t\t\t\tpreventFail : true,\n\t\t\t\toptions: {async: false}\n\t\t\t})\n\t\t\t.done(function(data) {\n\t\t\t\tfile.url = data.url || '';\n\t\t\t})\n\t\t\t.fail(function() {\n\t\t\t\tfile.url = '';\n\t\t\t});\n\t\t}\n\t\t\n\t\tif (file.url) {\n\t\t\treturn file.url;\n\t\t}\n\t\t\n\t\tif (cwdOptions.url && file.hash.indexOf(self.cwd().volumeid) === 0) {\n\t\t\treturn cwdOptions.url + $.map(this.path2array(hash), function(n) { return encodeURIComponent(n); }).slice(1).join('/')\n\t\t}\n\n\t\tvar params = $.extend({}, this.customData, {\n\t\t\tcmd: 'file',\n\t\t\ttarget: file.hash\n\t\t});\n\t\tif (this.oldAPI) {\n\t\t\tparams.cmd = 'open';\n\t\t\tparams.current = file.phash;\n\t\t}\n\t\treturn this.options.url + (this.options.url.indexOf('?') === -1 ? '?' : '&') + $.param(params, true);\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\tthis.diff = function(incoming, onlydir, excludeProps) {\n\t\tvar raw = {},\n\t\t\tadded = [],\n\t\t\tremoved = [],\n\t\t\tchanged = [],\n\t\t\tisChanged = function(hash) {\n\t\t\t\tvar l = changed.length;\n\n\t\t\t\twhile (l--) {\n\t\t\t\t\tif (changed[l].hash == hash) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t$.each(incoming, function(i, f) {\n\t\t\traw[f.hash] = f;\n\t\t});\n\t\t\t\n\t\t// find removed\n\t\t$.each(files, function(hash, f) {\n\t\t\tif (!onlydir || f.phash === onlydir) {\n\t\t\t\t!raw[hash] && removed.push(hash);\n\t\t\t}\n\t\t});\n\t\t\n\t\t// compare files\n\t\t$.each(raw, function(hash, file) {\n\t\t\tvar origin = files[hash];\n\n\t\t\tif (!origin) {\n\t\t\t\tadded.push(file);\n\t\t\t} else {\n\t\t\t\t$.each(file, function(prop) {\n\t\t\t\t\tif (! excludeProps || $.inArray(prop, excludeProps) === -1) {\n\t\t\t\t\t\tif (file[prop] != origin[prop]) {\n\t\t\t\t\t\t\tchanged.push(file)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\t\n\t\t// parents of removed dirs mark as changed (required for tree correct work)\n\t\t$.each(removed, function(i, hash) {\n\t\t\tvar file = files[hash], \n\t\t\t\tphash = file.phash;\n\n\t\t\tif (phash \n\t\t\t&& file.mime == 'directory' \n\t\t\t&& $.inArray(phash, removed) === -1 \n\t\t\t&& raw[phash] \n\t\t\t&& !isChanged(phash)) {\n\t\t\t\tchanged.push(raw[phash]);\n\t\t\t}\n\t\t});\n\t\t\n\t\treturn {\n\t\t\tadded : added,\n\t\t\tremoved : removed,\n\t\t\tchanged : changed\n\t\t};\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "u.B=function() {var a=0,b=this.b,c=this.l,d,f=new (w?Uint8Array:Array)(this.t+(this.a-32768)),h,k,e,g;if (0===c.length)return w?this.b.subarray(32768,this.a):this.b.slice(32768,this.a);h=0;for(k=c.length;h]*>/gi, ' ');\n\t\t\t\t\tvar type = src.match(/<[^>]+>/)? 'html' : 'text';\n\t\t\t\t\tmy.innerHTML = '';\n\t\t\t\t\tupload({files : [ src ], type : type});\n\t\t\t\t}\n\t\t\t}, 1);\n\t\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\t\t\t\t\t\tupdate: function(e, ui) {\n\t\t\t\t\t\t\t\tvar target = $(ui.item[0]).attr('class').split(' ')[0].replace('elfinder-cwd-view-th-', ''),\n\t\t\t\t\t\t\t\t\tprev, done;\n\t\t\t\t\t\t\t\tcustomCols = $.map($(this).children(), function(n) {\n\t\t\t\t\t\t\t\t\tvar name = $(n).attr('class').split(' ')[0].replace('elfinder-cwd-view-th-', '');\n\t\t\t\t\t\t\t\t\tif (! done) {\n\t\t\t\t\t\t\t\t\t\tif (target === name) {\n\t\t\t\t\t\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tprev = name;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn (name === 'name')? null : name;\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\ttemplates.row = makeTemplateRow();\n\t\t\t\t\t\t\t\tfm.storage('cwdCols', customCols);\n\t\t\t\t\t\t\t\tprev = '.elfinder-col-'+prev+':first';\n\t\t\t\t\t\t\t\ttarget = '.elfinder-col-'+target+':first';\n\t\t\t\t\t\t\t\tfm.lazy(function() {\n\t\t\t\t\t\t\t\t\tcwd.find('tbody tr').each(function() {\n\t\t\t\t\t\t\t\t\t\tvar $this = $(this);\n\t\t\t\t\t\t\t\t\t\t$this.children(prev).after($this.children(target));\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "u.S=function() {var a,b=this.a;w?this.L?(a=new Uint8Array(b),a.set(this.b.subarray(0,b))):a=this.b.subarray(0,b):(this.b.length>b&&(this.b.length=b),a=this.b);return this.buffer=a};function V(a) {a=a||{};this.files=[];this.v=a.comment}V.prototype.M=function(a) {this.j=a};V.prototype.s=function(a) {var b=a[2]&65535|2;return b*(b^1)>>8&255};V.prototype.k=function(a,b) {a[0]=(B[(a[0]^b)&255]^a[0]>>>8)>>>0;a[1]=(6681*(20173*(a[1]+(a[0]&255))>>>0)>>>0)+1>>>0;a[2]=(B[(a[2]^a[1]>>>24)&255]^a[2]>>>8)>>>0};V.prototype.U=function(a) {var b=[305419896,591751049,878082192],c,d;w&&(b=new Uint32Array(b));c=0;for(d=a.length;c -1) {\n var ext = url.pathname.slice(pos) + '.';\n if ('.eot.ttf.otf.svg.woff.woff2.'.indexOf(ext) !== -1) {\n return 'font';\n }\n // Still need this because often behind-the-scene requests are wrongly\n // categorized as 'other'\n if ('.ico.png.gif.jpg.jpeg.webp.'.indexOf(ext) !== -1) {\n return 'image';\n }\n }\n }\n // see crbug.com/410382\n return 'object';\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-284", "cwe_name": "Improper Access Control", "description": "The software does not restrict or incorrectly restricts access to a resource from an unauthorized actor.", "url": "https://cwe.mitre.org/data/definitions/284.html", "label_name": "safe"} {"code": "\t\t\t\tbeforeSend: function() {\n\t\t\t\t\tif (fn_beforeSend==undefined) {\n\t\t\t\t\t\tD.body.html('
');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfn_beforeSend(D, $this);\n\t\t\t\t\t}\n\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": "\t\t\t\tsuccess: function(responce) {\n\n\t\t\t\t\t// \u0421\u043e\u0431\u044b\u0442\u0438\u0435 \u043f\u043e\u0441\u043b\u0435 \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438 \u0434\u043e \u043f\u043e\u043a\u0430\u0437\u0430 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u043c\u043e\u0433\u043e\n\t\t\t\t\t$this.trigger('afterLoading');\n\t\t\t\t\tD.afterLoading(D, $this, responce);\n\n\t\t\t\t\tif (fn_success==undefined) {\n\t\t\t\t\t\tD.body.html(responce);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfn_success(D, $this, responce);\n\t\t\t\t\t}\n\t\t\t\t\tmodal.prepare_body(D, $this);\n\n\t\t\t\t\t// \u0421\u043e\u0431\u044b\u0442\u0438\u0435 \u043f\u043e\u0441\u043b\u0435 \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438 \u043f\u043e\u0441\u043b\u0435 \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u043c\u043e\u0433\u043e\n\t\t\t\t\t$this.trigger('afterLoadingOnShow');\n\t\t\t\t\tD.afterLoadingOnShow(D, $this, responce);\n\n\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": "App.Helpers.isUnlimitedValue = function(value) {\n var value = value.trim();\n if (value == App.Constants.UNLIM_VALUE || value == App.Constants.UNLIM_TRANSLATED_VALUE) {\n return true;\n }\n\n return false;\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": "App.Helpers.isUnlimitedValue = function(value) {\n var value = value.trim();\n if (value == App.Constants.UNLIM_VALUE || value == App.Constants.UNLIM_TRANSLATED_VALUE) {\n return true;\n }\n\n return false;\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " description: Ext.util.Format.htmlDecode(record.data.description)\n }\n var panel = new pimcore.object.classificationstore.storeConfiguration(data, this.applyConfig.bind(this));\n panel.show();\n }.bind(this)", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " afterrender: function () {\n Ext.get(this.getIframe()).on('load', function () {\n this.iFrameLoaded();\n }.bind(this));\n }.bind(this)", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " renderer: function (text) {\n return replace_html_event_attributes(strip_tags(text, 'div,span,b,strong,em,i,small,sup,sub,p'));\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "TagCreationContainer.prototype._resizeTag = function(textfield) {\n var that = this; \n\n x2.DEBUG && console.log ('_resizeTag');\n $(textfield).each(function() {\n that.textsize.text ($(this).val());\n x2.DEBUG && console.log ('that.textsize.width = ' + that.textsize.width ());\n $(this).css('width', (that.textsize.width() + 10) + 'px');\n });\n\n return $(textfield);\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "$.fn.addConfigMenu = function(options, callback) {\n var dropdown = $(this).find('#widget-dropdown');\n\n var target = $('')\n .height(18).width(18);\n target.appendTo(dropdown);\n var ul = $('
    ').appendTo(dropdown);\n\n for (var key in options){\n $('
    '+options[key]+'
    ').\n appendTo(ul).\n click( function(element) {\n return callback(element);\n });\n }\n\n\n // Handle opening and closing of the menu\n target.on('click', function(){\n if( ul.hasClass('open') ){\n ul.addClass('closed');\n ul.removeClass('open');\n } else {\n ul.removeClass('closed');\n ul.addClass('open');\n }\n \n });\n\n return dropdown;\n\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "froalaOptions.requestHeaders={'X-CSRF-TOKEN':$('meta[name=\"csrf-token\"]').attr('content'),'X-Requested-With':'XMLHttpRequest'}\nvar $form=this.$el.closest('form')\nvar formData={};if($form.length>0){$.each($form.serializeArray(),function(index,field){formData[field.name]=field.value;})}\nfroalaOptions.imageUploadURL=froalaOptions.fileUploadURL=window.location\nfroalaOptions.imageUploadParam=froalaOptions.fileUploadParam='file_data'\nfroalaOptions.imageUploadParams=froalaOptions.fileUploadParams=$.extend(formData,{_handler:froalaOptions.uploadHandler,})\nvar placeholder=this.$textarea.attr('placeholder')\nfroalaOptions.placeholderText=placeholder?placeholder:''\nfroalaOptions.height=this.$el.hasClass('stretch')?Infinity:$('.height-indicator',this.$el).height()\nif(!this.options.useMediaManager){delete $.FroalaEditor.PLUGINS.mediaManager}\n$.FroalaEditor.ICON_TEMPLATES={font_awesome:'',text:'[NAME]',image:'[ALT]'}\nthis.$textarea.on('froalaEditor.initialized',this.proxy(this.build))\nthis.$textarea.on('froalaEditor.contentChanged',this.proxy(this.onChange))\nthis.$textarea.on('froalaEditor.html.get',this.proxy(this.onSyncContent))\nthis.$textarea.on('froalaEditor.html.set',this.proxy(this.onSetContent))\nthis.$textarea.on('froalaEditor.paste.beforeCleanup',this.proxy(this.beforeCleanupPaste))\nthis.$form.on('oc.beforeRequest',this.proxy(this.onFormBeforeRequest))\nthis.$textarea.froalaEditor(froalaOptions)\nthis.editor=this.$textarea.data('froala.editor')\nif(this.options.readOnly){this.editor.edit.off()}\nthis.$el.on('keydown','.fr-view figure',this.proxy(this.onFigureKeydown))}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "window.ocSanitize=function(html){return sanitize(html)};}(window);+function($){\"use strict\";if($.oc===undefined)", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\t\t\t\t\t\tplugin: $itemRow.data( 'plugin' ),\n\t\t\t\t\t\tslug: $itemRow.data( 'slug' )\n\t\t\t\t\t}\n\t\t\t\t} );\n\t\t\t} );\n\n\t\t\t// Display bulk notification for updates of any kind.\n\t\t\t$document.on( 'wp-plugin-update-success wp-plugin-update-error wp-theme-update-success wp-theme-update-error', function( event, response ) {\n\t\t\t\tvar $bulkActionNotice, itemName;\n\n\t\t\t\tif ( 'wp-' + response.update + '-update-success' === event.type ) {\n\t\t\t\t\tsuccess++;\n\t\t\t\t} else {\n\t\t\t\t\titemName = response.pluginName ? response.pluginName : $( '[data-slug=\"' + response.slug + '\"]' ).find( '.theme-title strong' ).text();\n\n\t\t\t\t\terror++;\n\t\t\t\t\terrorMessages.push( itemName + ': ' + response.errorMessage );\n\t\t\t\t}\n\n\t\t\t\twp.updates.adminNotice = wp.template( 'wp-bulk-updates-admin-notice' );\n\n\t\t\t\twp.updates.addAdminNotice( {\n\t\t\t\t\tid: 'bulk-action-notice',\n\t\t\t\t\tsuccesses: success,\n\t\t\t\t\terrors: error,\n\t\t\t\t\terrorMessages: errorMessages,\n\t\t\t\t\ttype: response.update\n\t\t\t\t} );\n\n\t\t\t\t$bulkActionNotice = $( '#bulk-action-notice' ).on( 'click', 'button', function() {\n\t\t\t\t\t$bulkActionNotice.find( 'ul' ).toggleClass( 'hidden' );\n\t\t\t\t} );\n\n\t\t\t\tif ( error > 0 && ! wp.updates.queue.length ) {\n\t\t\t\t\t$( 'html, body' ).animate( { scrollTop: 0 } );\n\t\t\t\t}\n\t\t\t} );\n\n\t\t\t// Reset admin notice template after #bulk-action-notice was added.\n\t\t\t$document.on( 'wp-updates-notice-added', function() {\n\t\t\t\twp.updates.adminNotice = wp.template( 'wp-updates-admin-notice' );\n\t\t\t} );\n\n\t\t\t// Check the queue, now that the event handlers have been added.\n\t\t\twp.updates.queueChecker();\n\t\t} );", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " data: $('#UserSettingSetHomePageForm').serialize(),\n success:function (data, textStatus) {\n showMessage('success', 'Homepage set.');\n $('#setHomePage').addClass('orange');\n },\n });\n\n }\n });\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " get_DOM_row(row_pos) {\n var row_id = this.tr_id_mapping[row_pos];\n var tr = document.getElementById(row_id);\n return tr;\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " var sanitize_html = function (html, allow_css) {\n /**\n * sanitize HTML\n * if allow_css is true (default: false), CSS is sanitized as well.\n * otherwise, CSS elements and attributes are simply removed.\n */\n const options = {};\n if (!allow_css) {\n options.allowedStyles = {};\n }\n return defaultSanitizer.sanitize(html, options);\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " function getCookie(name) {\r\n var value = \"; \" + document.cookie;\r\n var parts = value.split(\"; \" + name + \"=\");\r\n if (parts.length === 2) return parts.pop().split(\";\").shift();\r\n }\r", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " jsonPathExtractionQuery(column, path) {\n let paths = _.toPath(path);\n let pathStr;\n const quotedColumn = this.isIdentifierQuoted(column)\n ? column\n : this.quoteIdentifier(column);\n\n switch (this.dialect) {\n case 'mysql':\n case 'mariadb':\n case 'sqlite':\n /**\n * Non digit sub paths need to be quoted as ECMAScript identifiers\n * https://bugs.mysql.com/bug.php?id=81896\n */\n if (this.dialect === 'mysql') {\n paths = paths.map(subPath => {\n return /\\D/.test(subPath)\n ? Utils.addTicks(subPath, '\"')\n : subPath;\n });\n }\n\n pathStr = this.escape(['$']\n .concat(paths)\n .join('.')\n .replace(/\\.(\\d+)(?:(?=\\.)|$)/g, (__, digit) => `[${digit}]`));\n\n if (this.dialect === 'sqlite') {\n return `json_extract(${quotedColumn},${pathStr})`;\n }\n\n return `json_unquote(json_extract(${quotedColumn},${pathStr}))`;\n\n case 'postgres':\n pathStr = this.escape(`{${paths.join(',')}}`);\n return `(${quotedColumn}#>>${pathStr})`;\n\n default:\n throw new Error(`Unsupported ${this.dialect} for JSON operations`);\n }\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\t\tshowEmptyFolder: function (albumPath, errorMessage) {\n\t\t\tvar message = '
    ';\n\t\t\tvar uploadAllowed = true;\n\n\t\t\tthis.element.children().detach();\n\t\t\tthis.removeLoading();\n\n\t\t\tif (!_.isUndefined(errorMessage) && errorMessage !== null) {\n\t\t\t\tmessage += '

    ' + t('gallery',\n\t\t\t\t\t\t'Album cannot be shown') + '

    ';\n\t\t\t\tmessage += '

    ' + escapeHTML(errorMessage) + '

    ';\n\t\t\t\tuploadAllowed = false;\n\t\t\t} else {\n\t\t\t\tmessage += '

    ' + t('gallery',\n\t\t\t\t\t\t'No media files found') + '

    ';\n\t\t\t\t// We can't upload yet on the public side\n\t\t\t\tif (Gallery.token) {\n\t\t\t\t\tmessage += '

    ' + t('gallery',\n\t\t\t\t\t\t\t'Upload pictures in the files app to display them here') + '

    ';\n\t\t\t\t} else {\n\t\t\t\t\tmessage += '

    ' + t('gallery',\n\t\t\t\t\t\t\t'Upload new files via drag and drop or by using the [+] button above') +\n\t\t\t\t\t\t'

    ';\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.emptyContentElement.html(message);\n\t\t\tthis.emptyContentElement.removeClass('hidden');\n\n\t\t\tthis._hideButtons(uploadAllowed);\n\t\t\tGallery.currentAlbum = albumPath;\n\t\t\tvar availableWidth = $(window).width() - Gallery.buttonsWidth;\n\t\t\tthis.breadcrumb.init(albumPath, availableWidth);\n\t\t\tGallery.config.albumDesign = null;\n\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " var a = function jnvgfg(sfgnmj = function ccunlk() { jnvgfg(undefined, 1); }, b) {", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": " function _typed(name, signatures) {\n var refs = new Refs();\n\n // parse signatures, expand them\n var _signatures = parseSignatures(signatures);\n if (_signatures.length == 0) {\n throw new Error('No signatures provided');\n }\n\n // filter all any type signatures\n var anys = filterAnyTypeSignatures(_signatures);\n\n // parse signatures into a node tree\n var node = parseTree(_signatures, [], anys);\n\n //var util = require('util');\n //console.log('ROOT');\n //console.log(util.inspect(node, { depth: null }));\n\n // generate code for the typed function\n // safeName is a conservative replacement of characters \n // to prevend being able to inject JS code at the place of the function name \n // the name is useful for stack trackes therefore we want have it there\n var code = [];\n var safeName = (name || '').replace(/[^a-zA-Z0-9_$]/g, '_')\n var args = getArgs(maxParams(_signatures));\n code.push('function ' + safeName + '(' + args.join(', ') + ') {');\n code.push(' \"use strict\";');\n code.push(' var name = ' + JSON.stringify(name || '') + ';');\n code.push(node.toCode(refs, ' ', false));\n code.push('}');\n\n // generate body for the factory function\n var body = [\n refs.toCode(),\n 'return ' + code.join('\\n')\n ].join('\\n');\n\n // evaluate the JavaScript code and attach function references\n var factory = (new Function(refs.name, 'createError', body));\n var fn = factory(refs, createError);\n\n //console.log('FN\\n' + fn.toString()); // TODO: cleanup\n\n // attach the signatures with sub-functions to the constructed function\n fn.signatures = mapSignatures(_signatures);\n\n return fn;\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " function nextTickWork () {\n process.nextTick(work)\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-674", "cwe_name": "Uncontrolled Recursion", "description": "The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.", "url": "https://cwe.mitre.org/data/definitions/674.html", "label_name": "safe"} {"code": " payload: Buffer.from('world'),\n retain: false,\n dup: false,\n messageId: i + 1,\n qos: 1\n }))\n }\n\n duplex.push(Buffer.concat(packets))\n }\n })", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-674", "cwe_name": "Uncontrolled Recursion", "description": "The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.", "url": "https://cwe.mitre.org/data/definitions/674.html", "label_name": "safe"} {"code": " lheading: /^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)/,", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "function marked(src, opt, callback) {\n if (callback || typeof opt === 'function') {\n if (!callback) {\n callback = opt;\n opt = null;\n }\n\n opt = merge({}, marked.defaults, opt || {});\n\n var highlight = opt.highlight\n , tokens\n , pending\n , i = 0;\n\n try {\n tokens = Lexer.lex(src, opt)\n } catch (e) {\n return callback(e);\n }\n\n pending = tokens.length;\n\n var done = function(err) {\n if (err) {\n opt.highlight = highlight;\n return callback(err);\n }\n\n var out;\n\n try {\n out = Parser.parse(tokens, opt);\n } catch (e) {\n err = e;\n }\n\n opt.highlight = highlight;\n\n return err\n ? callback(err)\n : callback(null, out);\n };\n\n if (!highlight || highlight.length < 3) {\n return done();\n }\n\n delete opt.highlight;\n\n if (!pending) return done();\n\n for (; i < tokens.length; i++) {\n (function(token) {\n if (token.type !== 'code') {\n return --pending || done();\n }\n return highlight(token.text, token.lang, function(err, code) {\n if (err) return done(err);\n if (code == null || code === token.text) {\n return --pending || done();\n }\n token.text = code;\n token.escaped = true;\n --pending || done();\n });\n })(tokens[i]);\n }\n\n return;\n }\n try {\n if (opt) opt = merge({}, marked.defaults, opt);\n return Parser.parse(Lexer.lex(src, opt), opt);\n } catch (e) {\n e.message += '\\nPlease report this to https://github.com/chjj/marked.';\n if ((opt || marked.defaults).silent) {\n return '

    An error occured:

    '\n        + escape(e.message + '', true)\n        + '
    ';\n }\n throw e;\n }\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "Renderer.prototype.code = function(code, lang, escaped) {\n if (this.options.highlight) {\n var out = this.options.highlight(code, lang);\n if (out != null && out !== code) {\n escaped = true;\n code = out;\n }\n }\n\n if (!lang) {\n return '
    '\n      + (escaped ? code : escape(code, true))\n      + '\\n
    ';\n }\n\n return '
    '\n    + (escaped ? code : escape(code, true))\n    + '\\n
    \\n';\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\tfunction prepare(_html, _isHtml)\n\t{\n\t\t// Free and null the old tooltip_div\n\t\thide();\n\n\t\t//Generate the tooltip div, set it's text and append it to the body tag\n\t\ttooltip_div = jQuery(_wnd.document.createElement('div'));\n\t\ttooltip_div.hide();\n\t\tif (_isHtml)\n\t\t{\n\t\t\ttooltip_div.append(_html);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttooltip_div.text(_html)\n\t\t}\n\t\ttooltip_div.addClass(\"egw_tooltip\");\n\t\tjQuery(_wnd.document.body).append(tooltip_div);\n\n\t\t//The tooltip should automatically hide when the mouse comes over it\n\t\ttooltip_div.mouseenter(function() {\n\t\t\t\thide();\n\t\t});\n\t}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\t_UID_callback: function _UID_callback(event) {\n\t\t// Copy to avoid changes, which may cause nm problems\n\t\tvar value = event === null ? null : jQuery.extend({},event);\n\n\t\t// Make sure id is a string, check values\n\t\tif(value)\n\t\t{\n\t\t\tthis._values_check(value);\n\t\t}\n\n\t\t// Check for changing days in the grid view\n\t\tif(!this._sameday_check(value))\n\t\t{\n\t\t\t// May need to update parent to remove out-of-view events\n\t\t\tvar parent = this._parent;\n\t\t\tthis._parent.removeChild(this);\n\t\t\tif(event === null && parent && parent._out_of_view)\n\t\t\t{\n\t\t\t\tparent._out_of_view();\n\t\t\t}\n\n\t\t\t// This should now cease to exist, as new events have been created\n\t\t\tthis.free();\n\t\t\treturn;\n\t\t}\n\n\t\t// Copy to avoid changes, which may cause nm problems\n\t\tthis.options.value = jQuery.extend({},value);\n\n\t\tif(this._parent.options.date)\n\t\t{\n\t\t\tthis.options.value.date = this._parent.options.date;\n\t\t}\n\n\t\t// Let parent position\n\t\tthis._parent.position_event(this);\n\n\t\t// Parent may remove this if the date isn't the same\n\t\tif(this._parent)\n\t\t{\n\t\t\tthis._update();\n\t\t}\n\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "Tine.Addressbook.ContactGridPanel.displayNameRenderer = function(data) {\n var i18n = Tine.Tinebase.appMgr.get('Addressbook').i18n;\n return data ? Ext.util.Format.htmlEncode(data) : ('
    ' + i18n._('No name') + '
    ');\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " text: Ext.util.Format.htmlEncode(nodeName),\n path: nodeData.path,\n name: nodeData.name,\n nodeRecord: newNodeRecord,\n account_grants: nodeData.account_grants,\n id: nodeData.id\n });\n \n newNode.attributes.nodeRecord.beginEdit();\n newNode.attributes.nodeRecord.set('path', nodeData.path);\n newNode.attributes.nodeRecord.endEdit();\n \n newNode.parentNode = target;\n return newNode;\n \n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " text: Ext.util.Format.htmlEncode(nodeName),\n path: nodeData.path,\n name: nodeData.name,\n nodeRecord: newNodeRecord,\n account_grants: nodeData.account_grants,\n id: nodeData.id\n });\n \n newNode.attributes.nodeRecord.beginEdit();\n newNode.attributes.nodeRecord.set('path', nodeData.path);\n newNode.attributes.nodeRecord.endEdit();\n \n newNode.parentNode = target;\n return newNode;\n \n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " onNodeTextChange: function(node, text, oldText) {\n if (node.attributes && node.attributes.filterPanel) {\n node.attributes.filterPanel.setTitle(Ext.util.Format.htmlEncode(text));\n }\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " render: function(relations) {\n if ((! relations) || (relations.length == 0)) {\n return '';\n }\n \n if (! this.recordClass) {\n if (! Tine[this.foreignApp]) {\n Tine.log.warn('Tine.widgets.relation.GridRenderer::render - ForeignApp not found: ' + this.foreignApp);\n return '';\n }\n \n this.recordClass = Tine[this.foreignApp].Model[this.foreignModel];\n }\n \n for (var index = 0; index < relations.length; index++) {\n var el = relations[index];\n if (el.type == this.type && el.related_model == this.relModel) {\n var record = new this.recordClass(el.related_record);\n return Ext.util.Format.htmlEncode(record.getTitle());\n }\n }\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "Manager.prototype.handleHandshake = function (data, req, res) {\n var self = this\n , origin = req.headers.origin\n , headers = {\n 'Content-Type': 'text/plain'\n };\n\n function writeErr (status, message) {\n if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {\n res.writeHead(200, { 'Content-Type': 'application/javascript' });\n res.end('io.j[' + data.query.jsonp + '](new Error(\"' + message + '\"));');\n } else {\n res.writeHead(status, headers);\n res.end(message);\n }\n };\n\n function error (err) {\n writeErr(500, 'handshake error');\n self.log.warn('handshake error ' + err);\n };\n\n if (!this.verifyOrigin(req)) {\n writeErr(403, 'handshake bad origin');\n return;\n }\n\n var handshakeData = this.handshakeData(data);\n\n if (origin) {\n // https://developer.mozilla.org/En/HTTP_Access_Control\n headers['Access-Control-Allow-Origin'] = origin;\n headers['Access-Control-Allow-Credentials'] = 'true';\n }\n\n this.authorize(handshakeData, function (err, authorized, newData) {\n if (err) return error(err);\n\n if (authorized) {\n var id = self.generateId(newData || handshakeData)\n , hs = [\n id\n , self.enabled('heartbeats') ? self.get('heartbeat timeout') || '' : ''\n , self.get('close timeout') || ''\n , self.transports(data).join(',')\n ].join(':');\n\n if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {\n hs = 'io.j[' + data.query.jsonp + '](' + JSON.stringify(hs) + ');';\n res.writeHead(200, { 'Content-Type': 'application/javascript' });\n } else {\n res.writeHead(200, headers);\n }\n\n res.end(hs);\n\n self.onHandshake(id, newData || handshakeData);\n self.store.publish('handshake', id, newData || handshakeData);\n\n self.log.info('handshake authorized', id);\n } else {\n writeErr(403, 'handshake unauthorized');\n self.log.info('handshake unauthorized');\n }\n })\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-330", "cwe_name": "Use of Insufficiently Random Values", "description": "The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.", "url": "https://cwe.mitre.org/data/definitions/330.html", "label_name": "safe"} {"code": " updateState: function(rfb, state, oldstate) {\n var msg;\n\n document.documentElement.classList.remove(\"noVNC_connecting\");\n document.documentElement.classList.remove(\"noVNC_connected\");\n document.documentElement.classList.remove(\"noVNC_disconnecting\");\n\n switch (state) {\n case 'connecting':\n document.getElementById(\"noVNC_transition_text\").textContent = _(\"Connecting...\");\n document.documentElement.classList.add(\"noVNC_connecting\");\n break;\n case 'connected':\n UI.connected = true;\n document.documentElement.classList.add(\"noVNC_connected\");\n if (rfb && rfb.get_encrypt()) {\n msg = _(\"Connected (encrypted) to \") + UI.desktopName;\n } else {\n msg = _(\"Connected (unencrypted) to \") + UI.desktopName;\n }\n UI.showStatus(msg);\n break;\n case 'disconnecting':\n UI.connected = false;\n document.getElementById(\"noVNC_transition_text\").textContent = _(\"Disconnecting...\");\n document.documentElement.classList.add(\"noVNC_disconnecting\");\n break;\n case 'disconnected':\n UI.showStatus(_(\"Disconnected\"));\n break;\n default:\n msg = \"Invalid UI state\";\n Util.Error(msg);\n UI.showStatus(msg, 'error');\n break;\n }\n\n UI.updateVisualState();\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.reset = function() {\n bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then(\n function() { // success\n growl.success('The foreign source definition for ' + _.escape($scope.foreignSource) + 'has been reseted.');\n $scope.initialize();\n },\n $scope.errorHandler\n );\n }\n });\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.initialize = function() {\n growl.success('Retrieving definition for requisition ' + _.escape($scope.foreignSource) + '...');\n RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(\n function(foreignSourceDef) { // success\n $scope.foreignSourceDef = foreignSourceDef;\n // Updating pagination variables for detectors.\n $scope.filteredDetectors = $scope.foreignSourceDef.detectors;\n $scope.updateFilteredDetectors();\n // Updating pagination variables for policies.\n $scope.filteredPolicies = $scope.foreignSourceDef.policies;\n $scope.updateFilteredPolicies();\n },\n $scope.errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.initialize = function() {\n growl.success('Retrieving definition for requisition ' + _.escape($scope.foreignSource) + '...');\n RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(\n function(foreignSourceDef) { // success\n $scope.foreignSourceDef = foreignSourceDef;\n // Updating pagination variables for detectors.\n $scope.filteredDetectors = $scope.foreignSourceDef.detectors;\n $scope.updateFilteredDetectors();\n // Updating pagination variables for policies.\n $scope.filteredPolicies = $scope.foreignSourceDef.policies;\n $scope.updateFilteredPolicies();\n },\n $scope.errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.refresh = function() {\n growl.success('Retrieving node ' + _.escape($scope.foreignId) + ' from requisition ' + _.escape($scope.foreignSource) + '...');\n RequisitionsService.getNode($scope.foreignSource, $scope.foreignId).then(\n function(node) { // success\n $scope.node = node;\n },\n $scope.errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.initialize = function(customHandler) {\n var value = $cookies.get('requisitions_page_size');\n if (value) {\n $scope.pageSize = value;\n }\n growl.success('Retrieving requisition ' + _.escape($scope.foreignSource) + '...');\n RequisitionsService.getRequisition($scope.foreignSource).then(\n function(requisition) { // success\n $scope.requisition = requisition;\n $scope.filteredNodes = requisition.nodes;\n $scope.updateFilteredNodes();\n if (customHandler) {\n customHandler();\n }\n },\n $scope.errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.refresh = function(requisition) {\n RequisitionsService.startTiming();\n RequisitionsService.updateDeployedStatsForRequisition(requisition).then(\n function() { // success\n growl.success('The deployed statistics for ' + _.escape(requisition.foreignSource) + ' has been updated.');\n },\n $scope.errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.initialize = function() {\n growl.success('Retrieving definition for requisition ' + _.escape($scope.foreignSource) + '...');\n RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(\n function(foreignSourceDef) { // success\n $scope.foreignSourceDef = foreignSourceDef;\n // Updating pagination variables for detectors.\n $scope.filteredDetectors = $scope.foreignSourceDef.detectors;\n $scope.updateFilteredDetectors();\n // Updating pagination variables for policies.\n $scope.filteredPolicies = $scope.foreignSourceDef.policies;\n $scope.updateFilteredPolicies();\n },\n $scope.errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.initialize = function() {\n growl.success('Retrieving definition for requisition ' + _.escape($scope.foreignSource) + '...');\n RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(\n function(foreignSourceDef) { // success\n $scope.foreignSourceDef = foreignSourceDef;\n // Updating pagination variables for detectors.\n $scope.filteredDetectors = $scope.foreignSourceDef.detectors;\n $scope.updateFilteredDetectors();\n // Updating pagination variables for policies.\n $scope.filteredPolicies = $scope.foreignSourceDef.policies;\n $scope.updateFilteredPolicies();\n },\n $scope.errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.addRequisition = function() {\n bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {\n if (foreignSource) {\n RequisitionsService.addRequisition(foreignSource).then(\n function() { // success\n RequisitionsService.synchronizeRequisition(foreignSource, false).then(\n function() {\n growl.success('The requisition ' + _.escape(foreignSource) + ' has been created and synchronized.');\n $scope.foreignSources.push(foreignSource);\n },\n $scope.errorHandler\n );\n },\n $scope.errorHandler\n );\n } else {\n window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?\n }\n });\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.initialize = function(customHandler) {\n var value = $cookies.get('requisitions_page_size');\n if (value) {\n $scope.pageSize = value;\n }\n growl.success('Retrieving requisition ' + _.escape($scope.foreignSource) + '...');\n RequisitionsService.getRequisition($scope.foreignSource).then(\n function(requisition) { // success\n $scope.requisition = requisition;\n $scope.filteredNodes = requisition.nodes;\n $scope.updateFilteredNodes();\n if (customHandler) {\n customHandler();\n }\n },\n $scope.errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " $scope.add = function() {\n bootbox.prompt('Please enter the name for the new requisition', function(foreignSource) {\n if (foreignSource) {\n // Validate Requisition\n if (foreignSource.match(/[/\\\\?:&*'\"]/)) {\n bootbox.alert('Cannot add the requisition ' + _.escape(foreignSource) + ' because the following characters are invalid:
    :, /, \\\\, ?, &, *, \\', \"');\n return;\n }\n var r = $scope.requisitionsData.getRequisition(foreignSource);\n if (r) {\n bootbox.alert('Cannot add the requisition ' + _.escape(foreignSource) + ' because there is already a requisition with that name');\n return;\n }\n // Create Requisition\n RequisitionsService.addRequisition(foreignSource).then(\n function(r) { // success\n growl.success('The requisition ' + _.escape(r.foreignSource) + ' has been created.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " $scope.delete = function(foreignSource) {\n bootbox.confirm('Are you sure you want to remove the requisition ' + _.escape(foreignSource) + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteRequisition(foreignSource).then(\n function() { // success\n growl.success('The requisition ' + _.escape(foreignSource) + ' has been deleted.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " var doSynchronize = function(requisition, rescanExisting) {\n RequisitionsService.startTiming();\n RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(\n function() { // success\n growl.success('The import operation has been started for ' + _.escape(requisition.foreignSource) + ' (rescanExisting? ' + rescanExisting + ')
    Use refresh to update the deployed statistics');\n requisition.setDeployed(true);\n },\n errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " var doSynchronize = function(requisition, rescanExisting) {\n RequisitionsService.startTiming();\n RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(\n function() { // success\n growl.success('The import operation has been started for ' + _.escape(requisition.foreignSource) + ' (rescanExisting? ' + rescanExisting + ')
    Use refresh to update the deployed statistics');\n requisition.setDeployed(true);\n },\n errorHandler\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " title: 'Synchronize Requisition ' + _.escape(requisition.foreignSource),\n buttons: {\n fullSync: {\n label: 'Yes',\n className: 'btn-primary',\n callback: function() {\n doSynchronize(requisition, 'true');\n }\n },\n dbOnlySync: {\n label: 'DB Only',\n className: 'btn-secondary',\n callback: function() {\n doSynchronize(requisition, 'dbonly');\n }\n },\n ignoreExistingSync: {\n label: 'No',\n className: 'btn-secondary',\n callback: function() {\n doSynchronize(requisition, 'false');\n }\n },\n main: {\n label: 'Cancel',\n className: 'btn-secondary'\n }\n }\n });\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "function alphanumeric(inputtxt) { \n\tvar letters = /^[0-9a-zA-Z]+$/;\n\t\tif (letters.test(inputtxt)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "function(){e.find('input[type=\"reset\"]').click();e.dialog(\"close\")},d=\"reset\"):(c=function(){e.submit()},d=\"submit\");buttonsOpts.push({text:b.val(),click:c,\"class\":d})}),e.find(\".fc_confirm_bar\").hide());e.dialog({create:function(b,c){a(\".ui-widget-header\").removeClass(\"ui-corner-all\").addClass(\"ui-corner-top\")},open:function(a,b){\"undefined\"!=typeof functionOpen&&!1!==functionOpen&&functionOpen.call(this)},modal:!0,closeOnEscape:!0,title:b,minWidth:600,minHeight:400,buttons:buttonsOpts})})})}})(jQuery);function toTimeString(a){return(new Date(1E3*a)).toUTCString().match(/(\\d\\d:\\d\\d:\\d\\d)/)[0]}function TimeStringToSecs(a){a=a.split(\":\");return 3600*+a[0]+60*+a[1]+ +a[2]}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\"#fc_showFooter_info\",function(){$(this).toggleClass(\"fc_active\").parent(\"#fc_footer_info\").children(\"ul\").slideToggle(300)});$('[title!=\"\"]').qtip({content:{attr:\"title\"},style:{classes:\"qtip-light qtip-shadow qtip-rounded\"}})});(function(a){a.fn.page_tree=function(b){b=a.extend({beforeSend:function(){},afterSend:function(){}},b);return this.each(function(){var b=a(this);1 1);\n var tag = this.type, attr = this.toMathMLattributes();\n var data = [], SPACE = space + (annotation ? \" \" + (nested ? \" \" : \"\") : \"\") + \" \";\n for (var i = 0, m = this.data.length; i < m; i++) {\n if (this.data[i]) {data.push(this.data[i].toMathML(SPACE))}\n else {data.push(SPACE+\"\")}\n }\n if (data.length === 0 || (data.length === 1 && data[0] === \"\")) {\n if (!annotation) {return \"<\"+tag+attr+\" />\"}\n data.push(SPACE+\"\");\n }\n if (annotation) {\n if (nested) {data.unshift(space+\" \"); data.push(space+\" \")}\n data.unshift(space+\" \");\n var xmlEscapedTex = jax.originalText.replace(/[&<>]/g, function(item) {\n return { '>': '>', '<': '<','&': '&' }[item]\n });\n data.push(space+' '+xmlEscapedTex+\"\");\n data.push(space+\" \");\n }\n return space+\"<\"+tag+attr+\">\\n\"+data.join(\"\\n\")+\"\\n\"+space+\"\";\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " constructor (p, opt) {\n opt = opt || {}\n super(opt)\n if (typeof p !== 'string')\n throw new TypeError('path is required')\n this.path = p\n // suppress atime, ctime, uid, gid, uname, gname\n this.portable = !!opt.portable\n // until node has builtin pwnam functions, this'll have to do\n this.myuid = process.getuid && process.getuid()\n this.myuser = process.env.USER || ''\n this.maxReadSize = opt.maxReadSize || maxReadSize\n this.linkCache = opt.linkCache || new Map()\n this.statCache = opt.statCache || new Map()\n this.preservePaths = !!opt.preservePaths\n this.cwd = opt.cwd || process.cwd()\n this.strict = !!opt.strict\n this.noPax = !!opt.noPax\n this.noMtime = !!opt.noMtime\n this.mtime = opt.mtime || null\n\n if (typeof opt.onwarn === 'function')\n this.on('warn', opt.onwarn)\n\n let pathWarn = false\n if (!this.preservePaths) {\n const [root, stripped] = stripAbsolutePath(this.path)\n if (root) {\n this.path = stripped\n pathWarn = root\n }\n }\n\n this.win32 = !!opt.win32 || process.platform === 'win32'\n if (this.win32) {\n this.path = winchars.decode(this.path.replace(/\\\\/g, '/'))\n p = p.replace(/\\\\/g, '/')\n }\n\n this.absolute = opt.absolute || path.resolve(this.cwd, p)\n\n if (this.path === '')\n this.path = './'\n\n if (pathWarn) {\n this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {\n entry: this,\n path: pathWarn + this.path,\n })\n }\n\n if (this.statCache.has(this.absolute))\n this[ONLSTAT](this.statCache.get(this.absolute))\n else\n this[LSTAT]()\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " const check = t => {\n for (let f in checks) {\n t.equal(fs.readFileSync(basedir + '/' + f, 'utf8'), checks[f], f)\n t.equal(fs.statSync(basedir + '/' + f).nlink, 1, f)\n }\n t.end()\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-59", "cwe_name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.", "url": "https://cwe.mitre.org/data/definitions/59.html", "label_name": "safe"} {"code": "function merge(target, obj) {\n for (var key in obj) {\n if (!isValidKey(key) || !hasOwn(obj, key)) {\n continue;\n }\n\n var oldVal = obj[key];\n var newVal = target[key];\n\n if (isObject(newVal) && isObject(oldVal)) {\n target[key] = merge(newVal, oldVal);\n } else if (Array.isArray(newVal)) {\n target[key] = union([], newVal, oldVal);\n } else {\n target[key] = clone(oldVal);\n }\n }\n return target;\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "safe"} {"code": "function isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "safe"} {"code": "\t(function setupCallSite() {\n\t\tfor (let i=0; i= 1024 && u < units.length - 1);\n return bytes.toFixed(1) + ' ' + units[u];\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " main.subscribeStates = function (patterns) {\n if (!patterns) return;\n if (typeof patterns === 'object') {\n for (let s = 0; s < patterns.length; s++) {\n main.subscribesStates[patterns[s]] = main.subscribesStates[patterns[s]] || 0;\n main.subscribesStates[patterns[s]]++;\n if (main.subscribesStates[patterns[s]] === 1) {\n console.debug('Subscribe: ' + patterns[s]);\n main.socket.emit('subscribe', patterns[s]);\n }\n }\n } else {\n main.subscribesStates[patterns] = main.subscribesStates[patterns] || 0;\n main.subscribesStates[patterns]++;\n if (main.subscribesStates[patterns] === 1) {\n console.debug('Subscribe: ' + patterns);\n main.socket.emit('subscribe', patterns);\n }\n }\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": "module.exports = function(path, opts, cb) {\n if (!cb) {\n cb = opts;\n opts = {};\n }\n\n if(/;|&|`|\\$|\\(|\\)|\\|\\||\\||!|>|<|\\?|\\${/g.test(JSON.stringify(path))) {\n console.log('Input Validation failed, Suspicious Characters found');\n } else {\n var cmd = module.exports.cmd(path, opts);\n opts.timeout = opts.timeout || 5000;\n exec(cmd, opts, function(e, stdout, stderr) {\n if (e) { return cb(e); }\n if (stderr) { return cb(new Error(stderr)); }\n\n return cb(null, module.exports.parse(path, stdout, opts));\n });\n}\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "DotObject.prototype.transform = function (recipe, obj, tgt) {\n obj = obj || {}\n tgt = tgt || {}\n Object.keys(recipe).forEach(\n function (key) {\n this.set(recipe[key], this.pick(key, obj), tgt)\n }.bind(this)\n )\n return tgt\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "const isLegalKey = key => key !== '__proto__';", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-915", "cwe_name": "Improperly Controlled Modification of Dynamically-Determined Object Attributes", "description": "The software receives input from an upstream component that specifies multiple attributes, properties, or fields that are to be initialized or updated in an object, but it does not properly control which attributes can be modified.", "url": "https://cwe.mitre.org/data/definitions/915.html", "label_name": "safe"} {"code": " getDetailAddressHtml: function (address) {\n if (!address) {\n return '';\n }\n var name = this.nameHash[address] || null;\n var entityType = this.typeHash[address] || null;\n var id = this.idHash[address] || null;\n\n var addressHtml = '' + address + '';\n\n if (name) {\n name = this.getHelper().escapeString(name);\n }\n\n var lineHtml;\n if (id) {\n lineHtml = '
    ' + '' + name + ' » ' + addressHtml + '
    ';\n } else {\n if (name) {\n lineHtml = '' + name + ' » ' + addressHtml + '';\n } else {\n lineHtml = addressHtml;\n }\n }\n if (!id) {\n if (this.getAcl().check('Contact', 'edit')) {\n lineHtml += From.prototype.getCreateHtml.call(this, address);\n }\n }\n lineHtml = '
    ' + lineHtml + '
    ';\n return lineHtml;\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " addAddress: function (address, name, type, id) {\n if (name) {\n name = this.getHelper().escapeString(name);\n }\n\n if (this.justAddedAddress) {\n this.deleteAddress(this.justAddedAddress);\n }\n this.justAddedAddress = address;\n setTimeout(function () {\n this.justAddedAddress = null;\n }.bind(this), 100);\n\n address = address.trim();\n\n if (!type) {\n var arr = address.match(this.emailAddressRegExp);\n if (!arr || !arr.length) return;\n address = arr[0];\n }\n\n if (!~this.addressList.indexOf(address)) {\n this.addressList.push(address);\n this.nameHash[address] = name;\n\n if (type) {\n this.typeHash[address] = type;\n }\n if (id) {\n this.idHash[address] = id;\n }\n\n this.addAddressHtml(address, name);\n this.trigger('change');\n }\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " getCreateHtml: function (address) {\n address = this.getHelper().escapeString(address);\n\n var html = '' +\n '' +\n '' +\n '';\n\n return html;\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " html: avatarHtml + this.getHelper().escapeString(this.getUser().get('name')),\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " 'entityType': this.getHelper().escapeString(this.translateEntityType(this.model.get('parentType'))),", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''\n }, Dep.prototype.data.call(this));\n },\n\n setup: function () {\n var data = this.model.get('data') || {};\n\n this.emailId = data.emailId;\n this.emailName = data.emailName;\n\n if (\n this.parentModel\n &&\n (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)\n ) {\n if (this.model.get('post')) {\n this.createField('post', null, null, 'views/stream/fields/post');\n this.hasPost = true;\n }\n if ((this.model.get('attachmentsIds') || []).length) {\n this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');\n this.hasAttachments = true;\n }\n }\n\n this.messageData['email'] = '' + this.getHelper().escapeString(data.emailName) + '';\n\n this.messageName = 'emailSent';\n\n this.messageData['by'] = '' + this.getHelper().escapeString(data.personEntityName) + '';\n\n\n if (this.isThis) {\n this.messageName += 'This';\n }\n\n this.createMessage();\n },\n\n });\n});", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''\n }, Dep.prototype.data.call(this));\n },\n\n setup: function () {\n var data = this.model.get('data') || {};\n\n this.emailId = data.emailId;\n this.emailName = data.emailName;\n\n if (\n this.parentModel\n &&\n (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)\n ) {\n if (this.model.get('post')) {\n this.createField('post', null, null, 'views/stream/fields/post');\n this.hasPost = true;\n }\n if ((this.model.get('attachmentsIds') || []).length) {\n this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');\n this.hasAttachments = true;\n }\n }\n\n this.messageData['email'] = '' + this.getHelper().escapeString(data.emailName) + '';\n\n this.messageName = 'emailSent';\n\n this.messageData['by'] = '' + this.getHelper().escapeString(data.personEntityName) + '';\n\n\n if (this.isThis) {\n this.messageName += 'This';\n }\n\n this.createMessage();\n },\n\n });\n});", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " setup: function () {\n var data = this.model.get('data') || {};\n\n this.entityType = this.model.get('relatedType') || data.entityType || null;\n this.entityId = this.model.get('relatedId') || data.entityId || null;\n this.entityName = this.model.get('relatedName') || data.entityName || null;\n\n this.messageData['relatedEntityType'] = this.translateEntityType(this.entityType);\n this.messageData['relatedEntity'] = '' + this.getHelper().escapeString(this.entityName) +'';\n\n this.createMessage();\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " setup: function () {\n var data = this.model.get('data');\n\n var field = data.field;\n var value = data.value;\n\n this.style = data.style || 'default';\n\n this.statusText = this.getHelper().escapeString(this.getLanguage().translateOption(value, field, this.model.get('parentType')));\n\n this.messageData['field'] = this.translate(field, 'fields', this.model.get('parentType')).toLowerCase();\n\n this.createMessage();\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " setup: function () {\n var data = this.model.get('data');\n\n var field = data.field;\n var value = data.value;\n\n this.style = data.style || 'default';\n\n this.statusText = this.getHelper().escapeString(this.getLanguage().translateOption(value, field, this.model.get('parentType')));\n\n this.messageData['field'] = this.translate(field, 'fields', this.model.get('parentType')).toLowerCase();\n\n this.createMessage();\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " value = value.replace(/href=\" *javascript\\:(.*?)\"/gi, function(m, $1) {\n return 'removed=\"\"';\n });", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " moderateSanitizeHtml: function (value) {\n value = value || '';\n value = value.replace(/<[\\/]{0,1}(base)[^><]*>/gi, '');\n value = value.replace(/<[\\/]{0,1}(object)[^><]*>/gi, '');\n value = value.replace(/<[\\/]{0,1}(embed)[^><]*>/gi, '');\n value = value.replace(/<[\\/]{0,1}(applet)[^><]*>/gi, '');\n value = value.replace(/<[\\/]{0,1}(iframe)[^><]*>/gi, '');\n value = value.replace(/<[\\/]{0,1}(script)[^><]*>/gi, '');\n value = value.replace(/<[^><]*([^a-z]{1}on[a-z]+)=[^><]*>/gi, function (match) {\n return match.replace(/[^a-z]{1}on[a-z]+=/gi, ' data-handler-stripped=');\n });\n\n value = this.stripEventHandlersInHtml(value);\n\n value = value.replace(/href=\" *javascript\\:(.*?)\"/gi, function(m, $1) {\n return 'removed=\"\"';\n });\n value = value.replace(/href=' *javascript\\:(.*?)'/gi, function(m, $1) {\n return 'removed=\"\"';\n });\n value = value.replace(/src=\" *javascript\\:(.*?)\"/gi, function(m, $1) {\n return 'removed=\"\"';\n });\n value = value.replace(/src=' *javascript\\:(.*?)'/gi, function(m, $1) {\n return 'removed=\"\"';\n });\n\n return value;\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " value = value.replace(/src=\" *javascript\\:(.*?)\"/gi, function(m, $1) {\n return 'removed=\"\"';\n });", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " sanitizeHtmlLight: function (value) {\n return this.getHelper().moderateSanitizeHtml(value);\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " getItemHtml: function (value) {\n value = value.toString();\n var valueSanitized = this.escapeValue(value);\n var translatedValue = this.escapeValue(this.translatedOptions[value] || value);\n\n var html = '' +\n '
    ' +\n '
    ' +\n '' +\n '
    ' +\n '
    ' +\n '' +\n '

    ' +\n '
    ';\n\n return html;\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "function moveRuleGroup(e) {\n let box = $(e.currentTarget);\n var direction = box.data('direction');\n var groupId = box.data('id');\n\n $.post(moveRuleGroupUrl, {_token: token, direction: direction, id: groupId}).then(function () {\n location.reload();\n }).fail(function() {\n alert('I failed :(');\n });\n\n return false;\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " depthedLookup: function(name) {\n return [\n this.aliasable('container.lookup'),\n '(depths, ',\n JSON.stringify(name),\n ')'\n ];\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1321", "cwe_name": "Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')", "description": "The software receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype.", "url": "https://cwe.mitre.org/data/definitions/1321.html", "label_name": "safe"} {"code": "function usercheck_init(i) {\r\n var obj = document.getElementById('ajax_output');\r\n obj.innerHTML = '';\r\n\r\n if (i.value.length < 1)\r\n return;\r\n\r\n var err = new Array();\r\n if (i.value.match(/[^A-Za-z0-9_@.]/))\r\n err[err.length] = 'Username can only contain letters, numbers, underscores, at the rate and dots';\r\n if (i.value.length < 3)\r\n err[err.length] = 'Username too short';\r\n if (err != '') {\r\n obj.style.color = '#ff0000';\r\n obj.innerHTML = err.join('
    ');\r\n\r\n if(i.value.length > 1)\r\n {\r\n window.$(\"#staff_username_flag\").val(\"0\");\r\n window.$(\"#mod_staff_btn\").attr(\"disabled\", true);\r\n }\r\n\r\n return;\r\n }\r\n\r\n window.$(\"#staff_username_flag\").val(\"1\");\r\n window.$(\"#mod_staff_btn\").attr(\"disabled\", false);\r\n\r\n var pqr = i.value;\r\n\r\n\r\n ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback, usercheck_error);\r\n}\r", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "function usercheck_init_mod(i, opt) {\r\n var obj = document.getElementById('ajax_output_' + opt);\r\n obj.innerHTML = '';\r\n\r\n if (i.value.length < 1)\r\n return;\r\n\r\n var err = new Array();\r\n if (i.value.match(/[^A-Za-z0-9_@.]/))\r\n err[err.length] = 'Username can only contain letters, numbers, underscores, at the rate and dots';\r\n if (i.value.length < 3)\r\n err[err.length] = 'Username Too Short';\r\n if (err != '') {\r\n obj.style.color = '#ff0000';\r\n obj.innerHTML = err.join('
    ');\r\n\r\n if(i.value.length > 1)\r\n {\r\n window.$(\"#staff_username_flag\").val(\"0\");\r\n window.$(\"#mod_staff_btn\").attr(\"disabled\", true);\r\n }\r\n\r\n return;\r\n }\r\n\r\n window.$(\"#staff_username_flag\").val(\"1\");\r\n window.$(\"#mod_staff_btn\").attr(\"disabled\", false);\r\n\r\n var pqr = i.value;\r\n\r\n if (opt == '1')\r\n ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_p, usercheck_error);\r\n\r\n if (opt == '2')\r\n ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_s, usercheck_error);\r\n}\r", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "function addClient() {\n var ip = utils.escapeHtml($(\"#select\").val().trim());\n var comment = utils.escapeHtml($(\"#new_comment\").val());\n\n utils.disableAll();\n utils.showAlert(\"info\", \"\", \"Adding client...\", ip);\n\n if (ip.length === 0) {\n utils.enableAll();\n utils.showAlert(\"warning\", \"\", \"Warning\", \"Please specify a client IP or MAC address\");\n return;\n }\n\n // Validate input, can be:\n // - IPv4 address (with and without CIDR)\n // - IPv6 address (with and without CIDR)\n // - MAC address (in the form AA:BB:CC:DD:EE:FF)\n // - host name (arbitrary form, we're only checking against some reserved characters)\n if (utils.validateIPv4CIDR(ip) || utils.validateIPv6CIDR(ip) || utils.validateMAC(ip)) {\n // Convert input to upper case (important for MAC addresses)\n ip = ip.toUpperCase();\n } else if (!utils.validateHostname(ip)) {\n utils.enableAll();\n utils.showAlert(\n \"warning\",\n \"\",\n \"Warning\",\n \"Input is neither a valid IP or MAC address nor a valid host name!\"\n );\n return;\n }\n\n $.ajax({\n url: \"scripts/pi-hole/php/groups.php\",\n method: \"post\",\n dataType: \"json\",\n data: { action: \"add_client\", ip: ip, comment: comment, token: token },\n success: function (response) {\n utils.enableAll();\n if (response.success) {\n utils.showAlert(\"success\", \"fas fa-plus\", \"Successfully added client\", ip);\n reloadClientSuggestions();\n table.ajax.reload(null, false);\n } else {\n utils.showAlert(\"error\", \"\", \"Error while adding new client\", response.message);\n }\n },\n error: function (jqXHR, exception) {\n utils.enableAll();\n utils.showAlert(\"error\", \"\", \"Error while adding new client\", jqXHR.responseText);\n console.log(exception); // eslint-disable-line no-console\n },\n });\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "function deleteClient() {\n var tr = $(this).closest(\"tr\");\n var id = tr.attr(\"data-id\");\n var ip = utils.escapeHtml(tr.find(\"#ip_\" + id).text());\n var name = utils.escapeHtml(tr.find(\"#name_\" + id).text());\n\n if (name.length > 0) {\n ip += \" (\" + name + \")\";\n }\n\n utils.disableAll();\n utils.showAlert(\"info\", \"\", \"Deleting client...\", ip);\n $.ajax({\n url: \"scripts/pi-hole/php/groups.php\",\n method: \"post\",\n dataType: \"json\",\n data: { action: \"delete_client\", id: id, token: token },\n success: function (response) {\n utils.enableAll();\n if (response.success) {\n utils.showAlert(\"success\", \"far fa-trash-alt\", \"Successfully deleted client \", ip);\n table.row(tr).remove().draw(false).ajax.reload(null, false);\n reloadClientSuggestions();\n } else {\n utils.showAlert(\"error\", \"\", \"Error while deleting client with ID \" + id, response.message);\n }\n },\n error: function (jqXHR, exception) {\n utils.enableAll();\n utils.showAlert(\"error\", \"\", \"Error while deleting client with ID \" + id, jqXHR.responseText);\n console.log(exception); // eslint-disable-line no-console\n },\n });\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " '@npmcli/run-script': ({ event }) => {},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-345", "cwe_name": "Insufficient Verification of Data Authenticity", "description": "The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.", "url": "https://cwe.mitre.org/data/definitions/345.html", "label_name": "safe"} {"code": " click: context.createInvokeHandler('editor.resize', '0.5'),\n }).render();\n });", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " function addActiveClass($target) {\n if (!$target) {\n return;\n }\n $target.find('button').addClass('active');\n $selectedNode = $target;\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\tfunction ReadableStreamStreamer(config)\n\t{\n\t\tconfig = config || {};\n\n\t\tChunkStreamer.call(this, config);\n\n\t\tvar queue = [];\n\t\tvar parseOnData = true;\n\t\tvar streamHasEnded = false;\n\n\t\tthis.pause = function()\n\t\t{\n\t\t\tChunkStreamer.prototype.pause.apply(this, arguments);\n\t\t\tthis._input.pause();\n\t\t};\n\n\t\tthis.resume = function()\n\t\t{\n\t\t\tChunkStreamer.prototype.resume.apply(this, arguments);\n\t\t\tthis._input.resume();\n\t\t};\n\n\t\tthis.stream = function(stream)\n\t\t{\n\t\t\tthis._input = stream;\n\n\t\t\tthis._input.on('data', this._streamData);\n\t\t\tthis._input.on('end', this._streamEnd);\n\t\t\tthis._input.on('error', this._streamError);\n\t\t};\n\n\t\tthis._checkIsFinished = function()\n\t\t{\n\t\t\tif (streamHasEnded && queue.length === 1) {\n\t\t\t\tthis._finished = true;\n\t\t\t}\n\t\t};\n\n\t\tthis._nextChunk = function()\n\t\t{\n\t\t\tthis._checkIsFinished();\n\t\t\tif (queue.length)\n\t\t\t{\n\t\t\t\tthis.parseChunk(queue.shift());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tparseOnData = true;\n\t\t\t}\n\t\t};\n\n\t\tthis._streamData = bindFunction(function(chunk)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tqueue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding));\n\n\t\t\t\tif (parseOnData)\n\t\t\t\t{\n\t\t\t\t\tparseOnData = false;\n\t\t\t\t\tthis._checkIsFinished();\n\t\t\t\t\tthis.parseChunk(queue.shift());\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (error)\n\t\t\t{\n\t\t\t\tthis._streamError(error);\n\t\t\t}\n\t\t}, this);\n\n\t\tthis._streamError = bindFunction(function(error)\n\t\t{\n\t\t\tthis._streamCleanUp();\n\t\t\tthis._sendError(error);\n\t\t}, this);\n\n\t\tthis._streamEnd = bindFunction(function()\n\t\t{\n\t\t\tthis._streamCleanUp();\n\t\t\tstreamHasEnded = true;\n\t\t\tthis._streamData('');\n\t\t}, this);\n\n\t\tthis._streamCleanUp = bindFunction(function()\n\t\t{\n\t\t\tthis._input.removeListener('data', this._streamData);\n\t\t\tthis._input.removeListener('end', this._streamEnd);\n\t\t\tthis._input.removeListener('error', this._streamError);\n\t\t}, this);\n\t}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\tfunction isFunction(func)\n\t{\n\t\treturn typeof func === 'function';\n\t}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\t\tfunction guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) {\n\t\t\tvar bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount;\n\n\t\t\tdelimitersToGuess = delimitersToGuess || [',', '\\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP];\n\n\t\t\tfor (var i = 0; i < delimitersToGuess.length; i++) {\n\t\t\t\tvar delim = delimitersToGuess[i];\n\t\t\t\tvar delta = 0, avgFieldCount = 0, emptyLinesCount = 0;\n\t\t\t\tfieldCountPrevRow = undefined;\n\n\t\t\t\tvar preview = new Parser({\n\t\t\t\t\tcomments: comments,\n\t\t\t\t\tdelimiter: delim,\n\t\t\t\t\tnewline: newline,\n\t\t\t\t\tpreview: 10\n\t\t\t\t}).parse(input);\n\n\t\t\t\tfor (var j = 0; j < preview.data.length; j++) {\n\t\t\t\t\tif (skipEmptyLines && testEmptyLine(preview.data[j])) {\n\t\t\t\t\t\temptyLinesCount++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tvar fieldCount = preview.data[j].length;\n\t\t\t\t\tavgFieldCount += fieldCount;\n\n\t\t\t\t\tif (typeof fieldCountPrevRow === 'undefined') {\n\t\t\t\t\t\tfieldCountPrevRow = fieldCount;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse if (fieldCount > 0) {\n\t\t\t\t\t\tdelta += Math.abs(fieldCount - fieldCountPrevRow);\n\t\t\t\t\t\tfieldCountPrevRow = fieldCount;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (preview.data.length > 0)\n\t\t\t\t\tavgFieldCount /= (preview.data.length - emptyLinesCount);\n\n\t\t\t\tif ((typeof bestDelta === 'undefined' || delta <= bestDelta)\n\t\t\t\t\t&& (typeof maxFieldCount === 'undefined' || avgFieldCount > maxFieldCount) && avgFieldCount > 1.99) {\n\t\t\t\t\tbestDelta = delta;\n\t\t\t\t\tbestDelim = delim;\n\t\t\t\t\tmaxFieldCount = avgFieldCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t_config.delimiter = bestDelim;\n\n\t\t\treturn {\n\t\t\t\tsuccessful: !!bestDelim,\n\t\t\t\tbestDelimiter: bestDelim\n\t\t\t};\n\t\t}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\t\tthis._chunkError = function()\n\t\t{\n\t\t\tthis._sendError(reader.error);\n\t\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\tfunction getWorkerBlob() {\n\t\tvar URL = global.URL || global.webkitURL || null;\n\t\tvar code = moduleFactory.toString();\n\t\treturn Papa.BLOB_URL || (Papa.BLOB_URL = URL.createObjectURL(new Blob(['(', code, ')();'], {type: 'text/javascript'})));\n\t}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\t\tthis._readChunk = function()\n\t\t{\n\t\t\tif (this._finished)\n\t\t\t{\n\t\t\t\tthis._chunkLoaded();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\txhr = new XMLHttpRequest();\n\n\t\t\tif (this._config.withCredentials)\n\t\t\t{\n\t\t\t\txhr.withCredentials = this._config.withCredentials;\n\t\t\t}\n\n\t\t\tif (!IS_WORKER)\n\t\t\t{\n\t\t\t\txhr.onload = bindFunction(this._chunkLoaded, this);\n\t\t\t\txhr.onerror = bindFunction(this._chunkError, this);\n\t\t\t}\n\n\t\t\txhr.open(this._config.downloadRequestBody ? 'POST' : 'GET', this._input, !IS_WORKER);\n\t\t\t// Headers can only be set when once the request state is OPENED\n\t\t\tif (this._config.downloadRequestHeaders)\n\t\t\t{\n\t\t\t\tvar headers = this._config.downloadRequestHeaders;\n\n\t\t\t\tfor (var headerName in headers)\n\t\t\t\t{\n\t\t\t\t\txhr.setRequestHeader(headerName, headers[headerName]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this._config.chunkSize)\n\t\t\t{\n\t\t\t\tvar end = this._start + this._config.chunkSize - 1;\t// minus one because byte range is inclusive\n\t\t\t\txhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\txhr.send(this._config.downloadRequestBody);\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tthis._chunkError(err.message);\n\t\t\t}\n\n\t\t\tif (IS_WORKER && xhr.status === 0)\n\t\t\t\tthis._chunkError();\n\t\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\t\tthis._onRead = function()\n\t\t{\n\t\t\tif (this._handle.paused()) {\n\t\t\t\t// the writeable consumer can handle more data\n\t\t\t\t// so resume the chunk parsing\n\t\t\t\tthis._handle.resume();\n\t\t\t}\n\t\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\t\t\tfunction fileComplete()\n\t\t\t{\n\t\t\t\tqueue.splice(0, 1);\n\t\t\t\tparseNextFile();\n\t\t\t}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\t\tfunction testEmptyLine(s) {\n\t\t\treturn _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0;\n\t\t}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\t\tthis.resume = function()\n\t\t{\n\t\t\tChunkStreamer.prototype.resume.apply(this, arguments);\n\t\t\tthis._input.resume();\n\t\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": "\t\tthis._onCsvComplete = function()\n\t\t{\n\t\t\t// node will finish the read stream when\n\t\t\t// null is pushed\n\t\t\tstream.push(null);\n\t\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-1236", "cwe_name": "Improper Neutralization of Formula Elements in a CSV File", "description": "The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.", "url": "https://cwe.mitre.org/data/definitions/1236.html", "label_name": "safe"} {"code": " preload: path.resolve(basePath, './build/preload.js')\n }\n };\n\n mainWindow = new BrowserWindow(options);\n windowState.manage(mainWindow);\n mainWindow.loadURL(indexURL);\n\n initPopupsConfigurationMain(mainWindow);\n setupAlwaysOnTopMain(mainWindow);\n setupPowerMonitorMain(mainWindow);\n setupScreenSharingMain(mainWindow, config.default.appName);\n\n mainWindow.webContents.on('new-window', (event, url, frameName) => {\n const target = getPopupTarget(url, frameName);\n\n if (!target || target === 'browser') {\n event.preventDefault();\n openExternalLink(url);\n }\n });\n mainWindow.on('closed', () => {\n mainWindow = null;\n });\n mainWindow.once('ready-to-show', () => {\n mainWindow.show();\n });\n\n /**\n * This is for windows [win32]\n * so when someone tries to enter something like jitsi-meet://test\n * while app is closed\n * it will trigger this event below\n */\n if (process.platform === 'win32') {\n handleProtocolCall(process.argv.pop());\n }\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-345", "cwe_name": "Insufficient Verification of Data Authenticity", "description": "The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.", "url": "https://cwe.mitre.org/data/definitions/345.html", "label_name": "safe"} {"code": " date.compile = function (formatString) {\n var re = /\\[([^\\[\\]]|\\[[^\\[\\]]*])*]|([A-Za-z])\\2+|\\.{3}|./g, keys, pattern = [formatString];\n\n while ((keys = re.exec(formatString))) {\n pattern[pattern.length] = keys[0];\n }\n return pattern;\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": "c){return d.addMinutes(a,60*c)};d.addMinutes=function(a,c){return d.addSeconds(a,60*c)};d.addSeconds=function(a,c){return d.addMilliseconds(a,1E3*c)};d.addMilliseconds=function(a,c){return new Date(a.getTime()+c)};d.subtract=function(a,c){var b=a.getTime()-c.getTime();return{toMilliseconds:function(){return b},toSeconds:function(){return b/1E3},toMinutes:function(){return b/6E4},toHours:function(){return b/36E5},toDays:function(){return b/864E5}}};d.isLeapYear=function(a){return!(a%4)&&!!(a%100)||", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " _write(data, encoding, cb) {\n const channel = this._channel;\n const protocol = channel._client._protocol;\n const outgoing = channel.outgoing;\n const packetSize = outgoing.packetSize;\n const id = outgoing.id;\n let window = outgoing.window;\n const len = data.length;\n let p = 0;\n\n if (outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n let sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n if (p === 0 && sliceLen === len)\n protocol.channelExtData(id, data, STDERR);\n else\n protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR);\n\n p += sliceLen;\n window -= sliceLen;\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n channel._waitWindow = true;\n if (p > 0)\n channel._chunkErr = bufferSlice(data, p, len);\n else\n channel._chunkErr = data;\n channel._chunkcbErr = cb;\n return;\n }\n\n cb();\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => {\n const nprompts = (Array.isArray(prompts) ? prompts.length : 0);\n if (nprompts === 0) {\n debug && debug('Client: Sending automatic USERAUTH_INFO_RESPONSE');\n proto.authInfoRes();\n return;\n }\n // We sent a keyboard-interactive user authentication request and now\n // the server is sending us the prompts we need to present to the user\n this.emit('keyboard-interactive',\n name,\n instructions,\n '',\n prompts,\n (answers) => {\n proto.authInfoRes(answers);\n }\n );\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " openssh_forwardInStreamLocal(socketPath, cb) {\n if (!this._sock || !this._sock.writable)\n throw new Error('Not connected');\n\n const wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push((had_err) => {\n if (had_err) {\n cb(had_err !== true\n ? had_err\n : new Error(`Unable to bind to ${socketPath}`));\n return;\n }\n this._forwardingUnix[socketPath] = true;\n cb();\n });\n }\n\n this._protocol.openssh_streamLocalForward(socketPath, wantReply);\n return this;\n }\n\n if (!wantReply)\n return this;\n\n process.nextTick(\n cb,\n new Error(\n 'strictVendor enabled and server is not OpenSSH or compatible version'\n )\n );\n\n return this;\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " USERAUTH_BANNER: (p, msg) => {\n this.emit('banner', msg);\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " CHANNEL_OPEN: (p, info) => {\n // Handle incoming requests from server, typically a forwarded TCP or\n // X11 connection\n onCHANNEL_OPEN(this, info);\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " const wrapper = (err, stream) => {\n cb(err, stream);\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " USERAUTH_SUCCESS: (p) => {\n // Start keepalive mechanism\n resetKA();\n\n clearTimeout(this._readyTimeout);\n\n this.emit('ready');\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " const accept = () => {\n const chanInfo = {\n type: info.type,\n incoming: {\n id: localChan,\n window: MAX_WINDOW,\n packetSize: PACKET_SIZE,\n state: 'open'\n },\n outgoing: {\n id: info.sender,\n window: info.window,\n packetSize: info.packetSize,\n state: 'open'\n }\n };\n const stream = new Channel(self, chanInfo);\n self._chanMgr.update(localChan, stream);\n\n self._protocol.channelOpenConfirm(info.sender,\n localChan,\n MAX_WINDOW,\n PACKET_SIZE);\n return stream;\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "const noop = (err) => {};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " authHandler = (authsLeft, partial, cb) => {\n if (authPos === authsAllowed.length)\n return false;\n return authsAllowed[authPos++];\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " function hostbasedCb(buf, cb) {\n const signature = privateKey.sign(buf);\n if (signature instanceof Error) {\n signature.message =\n `Error while signing with privateKey: ${signature.message}`;\n signature.level = 'client-authentication';\n this.emit('error', signature);\n return tryNextAuth();\n }\n\n cb(signature);\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " hostVerifier = (key, verify) => {\n if (hasher) {\n hasher.update(key);\n key = hasher.digest('hex');\n }\n const ret = hashCb(key, verify);\n if (ret !== undefined)\n verify(ret);\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " function resetKA() {\n if (kainterval > 0) {\n kacount = 0;\n clearInterval(katimer);\n if (sock.writable)\n katimer = setInterval(sendKA, kainterval);\n }\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " service(name) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const nameLen = Buffer.byteLength(name);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + nameLen);\n\n packet[p] = MESSAGE.SERVICE_REQUEST;\n\n writeUInt32BE(packet, nameLen, ++p);\n packet.utf8Write(name, p += 4, nameLen);\n\n this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " tcpipForward(bindAddr, bindPort, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const addrLen = Buffer.byteLength(bindAddr);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4);\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 13, ++p);\n packet.utf8Write('tcpip-forward', p += 4, 13);\n\n packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, addrLen, ++p);\n packet.utf8Write(bindAddr, p += 4, addrLen);\n\n writeUInt32BE(packet, bindPort, p += addrLen);\n\n this._debug\n && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)');\n sendPacket(this, this._packetRW.write.finalize(packet));\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " channelFailure(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_FAILURE;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " openssh_streamLocalForward(socketPath, wantReply) {\n if (this._server)\n throw new Error('Client-only method called in server mode');\n\n const socketPathLen = Buffer.byteLength(socketPath);\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(\n 1 + 4 + 31 + 1 + 4 + socketPathLen\n );\n\n packet[p] = MESSAGE.GLOBAL_REQUEST;\n\n writeUInt32BE(packet, 31, ++p);\n packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31);\n\n packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0);\n\n writeUInt32BE(packet, socketPathLen, ++p);\n packet.utf8Write(socketPath, p += 4, socketPathLen);\n\n this._debug && this._debug(\n 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)'\n );\n sendPacket(this, this._packetRW.write.finalize(packet));\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " this.parse = () => {\n throw new Error(`Instance unusable after ${reason}`);\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function modesToBytes(modes) {\n const keys = Object.keys(modes);\n const bytes = Buffer.allocUnsafe((5 * keys.length) + 1);\n let b = 0;\n\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (key === 'TTY_OP_END')\n continue;\n\n const opcode = TERMINAL_MODE[key];\n if (opcode === undefined)\n continue;\n\n const val = modes[key];\n if (typeof val === 'number' && isFinite(val)) {\n bytes[b++] = opcode;\n bytes[b++] = val >>> 24;\n bytes[b++] = val >>> 16;\n bytes[b++] = val >>> 8;\n bytes[b++] = val;\n }\n }\n\n bytes[b++] = TERMINAL_MODE.TTY_OP_END;\n\n if (b < bytes.length)\n return bufferSlice(bytes, 0, b);\n\n return bytes;\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " channelEOF(chan) {\n // Does not consume window space\n\n let p = this._packetRW.write.allocStart;\n const packet = this._packetRW.write.alloc(1 + 4);\n\n packet[p] = MESSAGE.CHANNEL_EOF;\n\n writeUInt32BE(packet, chan, ++p);\n\n this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`);\n sendPacket(this, this._packetRW.write.finalize(packet));\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " const onwrite = (er, bytes) => {\n if (er) {\n this.destroy();\n return cb(er);\n }\n this.bytesWritten += bytes;\n if (--writesLeft === 0)\n cb();\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function attrsToBytes(attrs) {\n let flags = 0;\n let nb = 0;\n\n if (typeof attrs === 'object' && attrs !== null) {\n if (typeof attrs.size === 'number') {\n flags |= ATTR.SIZE;\n const val = attrs.size;\n // Big Endian\n ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56\n ATTRS_BUF[nb++] = val / 281474976710656; // 2**48\n ATTRS_BUF[nb++] = val / 1099511627776; // 2**40\n ATTRS_BUF[nb++] = val / 4294967296; // 2**32\n ATTRS_BUF[nb++] = val / 16777216; // 2**24\n ATTRS_BUF[nb++] = val / 65536; // 2**16\n ATTRS_BUF[nb++] = val / 256; // 2**8\n ATTRS_BUF[nb++] = val;\n }\n if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') {\n flags |= ATTR.UIDGID;\n const uid = attrs.uid;\n const gid = attrs.gid;\n // Big Endian\n ATTRS_BUF[nb++] = uid >>> 24;\n ATTRS_BUF[nb++] = uid >>> 16;\n ATTRS_BUF[nb++] = uid >>> 8;\n ATTRS_BUF[nb++] = uid;\n ATTRS_BUF[nb++] = gid >>> 24;\n ATTRS_BUF[nb++] = gid >>> 16;\n ATTRS_BUF[nb++] = gid >>> 8;\n ATTRS_BUF[nb++] = gid;\n }\n if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') {\n const mode = modeNum(attrs.mode);\n flags |= ATTR.PERMISSIONS;\n // Big Endian\n ATTRS_BUF[nb++] = mode >>> 24;\n ATTRS_BUF[nb++] = mode >>> 16;\n ATTRS_BUF[nb++] = mode >>> 8;\n ATTRS_BUF[nb++] = mode;\n }\n if ((typeof attrs.atime === 'number' || isDate(attrs.atime))\n && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) {\n const atime = toUnixTimestamp(attrs.atime);\n const mtime = toUnixTimestamp(attrs.mtime);\n\n flags |= ATTR.ACMODTIME;\n // Big Endian\n ATTRS_BUF[nb++] = atime >>> 24;\n ATTRS_BUF[nb++] = atime >>> 16;\n ATTRS_BUF[nb++] = atime >>> 8;\n ATTRS_BUF[nb++] = atime;\n ATTRS_BUF[nb++] = mtime >>> 24;\n ATTRS_BUF[nb++] = mtime >>> 16;\n ATTRS_BUF[nb++] = mtime >>> 8;\n ATTRS_BUF[nb++] = mtime;\n }\n // TODO: extended attributes\n }\n\n return { flags, nb };\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function writeAll(sftp, handle, buffer, offset, length, position, callback_) {\n const callback = (typeof callback_ === 'function' ? callback_ : undefined);\n\n sftp.write(handle,\n buffer,\n offset,\n length,\n position,\n (writeErr, written) => {\n if (writeErr) {\n return sftp.close(handle, () => {\n callback && callback(writeErr);\n });\n }\n if (written === length) {\n sftp.close(handle, callback);\n } else {\n offset += written;\n length -= written;\n position += written;\n writeAll(sftp, handle, buffer, offset, length, position, callback);\n }\n });\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function WriteStream(sftp, path, options) {\n if (options === undefined)\n options = {};\n else if (typeof options === 'string')\n options = { encoding: options };\n else if (options === null || typeof options !== 'object')\n throw new TypeError('\"options\" argument must be a string or an object');\n else\n options = Object.create(options);\n\n // For backwards compat do not emit close on destroy.\n options.emitClose = false;\n\n WritableStream.call(this, options);\n\n this.path = path;\n this.flags = options.flags === undefined ? 'w' : options.flags;\n this.mode = options.mode === undefined ? 0o666 : options.mode;\n\n this.start = options.start;\n this.autoClose = options.autoClose === undefined ? true : options.autoClose;\n this.pos = 0;\n this.bytesWritten = 0;\n this.closed = false;\n\n this.handle = options.handle === undefined ? null : options.handle;\n this.sftp = sftp;\n this._opening = false;\n\n if (this.start !== undefined) {\n checkPosition(this.start, 'start');\n\n this.pos = this.start;\n }\n\n if (options.encoding)\n this.setDefaultEncoding(options.encoding);\n\n // Node v6.x only\n this.on('finish', function() {\n if (this._writableState.finalCalled)\n return;\n if (this.autoClose)\n this.destroy();\n });\n\n if (!Buffer.isBuffer(this.handle))\n this.open();\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " const reread = (err, handle) => {\n if (err)\n return cb(err);\n\n this.readdir(handle, opts, (err, list) => {\n const eof = (err && err.code === STATUS_CODE.EOF);\n\n if (err && !eof)\n return this.close(handle, () => cb(err));\n\n if (eof) {\n return this.close(handle, (err) => {\n if (err)\n return cb(err);\n cb(undefined, entries);\n });\n }\n\n for (let i = 0; i < list.length; ++i, ++e)\n entries[e] = list[i];\n\n reread(undefined, handle);\n });\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function stringToFlags(str) {\n const flags = stringFlagMap[str];\n return (flags !== undefined ? flags : null);\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " rename(oldPath, newPath, cb) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n /*\n uint32 id\n string oldpath\n string newpath\n */\n const oldLen = Buffer.byteLength(oldPath);\n const newLen = Buffer.byteLength(newPath);\n let p = 9;\n const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen);\n\n writeUInt32BE(buf, buf.length - 4, 0);\n buf[4] = REQUEST.RENAME;\n const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;\n writeUInt32BE(buf, reqid, 5);\n\n writeUInt32BE(buf, oldLen, p);\n buf.utf8Write(oldPath, p += 4, oldLen);\n writeUInt32BE(buf, newLen, p += oldLen);\n buf.utf8Write(newPath, p += 4, newLen);\n\n this._requests[reqid] = { cb };\n\n const isBuffered = sendOrBuffer(this, buf);\n this._debug && this._debug(\n `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME`\n );\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " emit: () => {},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " isBlockDevice() {\n return ((this.mode & constants.S_IFMT) === constants.S_IFBLK);\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function closeStream(stream, cb, err) {\n if (!stream.handle)\n return onclose();\n\n stream.sftp.close(stream.handle, onclose);\n\n function onclose(er) {\n er = er || err;\n cb(er);\n stream.closed = true;\n if (!er)\n stream.emit('close');\n }\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " _init() {\n this._init = noop;\n if (!this.server)\n sendOrBuffer(this, CLIENT_VERSION_BUFFER);\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function F(a){if(String.prototype.startsWith?a.startsWith(V):0===a.indexOf(V)){a=a.slice(V.length);if(\"boolean\"===typeof x&&x){try{var c=Buffer.from(a,\"base64\")}catch(p){c=new Buffer(a,\"base64\")}var d=new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}else try{var e=va(a),k=new Uint8Array(e.length);for(c=0;c {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'function')\n return;\n\n const info = { reason, description };\n onChannelOpenFailure(this, recipient, info, channel);\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => {\n if (authCtx === ctx && !this.authenticated) {\n if (allowed) {\n authCtx = undefined;\n this.authenticated = true;\n proto.authSuccess();\n pendingAuths = [];\n this.emit('ready');\n } else {\n proto.authFailure(methodsLeft, isPartial);\n if (pendingAuths.length) {\n authCtx = pendingAuths.pop();\n if (listenerCount(this, 'authentication'))\n this.emit('authentication', authCtx);\n else\n authCtx.reject();\n }\n }\n }\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " listen(...args) {\n this._srv.listen(...args);\n return this;\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " CHANNEL_DATA: (p, recipient, data) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n // The remote party should not be sending us data if there is no\n // window space available ...\n // TODO: raise error on data with not enough window?\n if (channel.incoming.window === 0)\n return;\n\n channel.incoming.window -= data.length;\n\n if (channel.push(data) === false) {\n channel._waitChanDrain = true;\n return;\n }\n\n if (channel.incoming.window <= WINDOW_THRESHOLD)\n windowAdjust(channel);\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " function onClientPreHeaderError(err) {}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {\n // NOOP -- should not be sent by client\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " CHANNEL_FAILURE: (p, recipient) => {\n let channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n if (channel.constructor === Session) {\n channel = channel._channel;\n if (!channel)\n return;\n }\n\n if (channel._callbacks.length)\n channel._callbacks.shift()(true);\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " x11(originAddr, originPort, cb) {\n const opts = { originAddr, originPort };\n openChannel(this, 'x11', opts, cb);\n return this;\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function mustNotCall(msg) {\n const callSite = getCallSite(mustNotCall);\n return function mustNotCall(...args) {\n args = args.map(inspect).join(', ');\n const argsInfo = (args.length > 0\n ? `\\ncalled with arguments: ${args}`\n : '');\n assert.fail(\n `${msg || 'function should not have been called'} at ${callSite}`\n + argsInfo);\n };\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " stack: inspect(new Error()),\n name: fn.name || ''\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function mustCall(fn, exact) {\n return _mustCallInner(fn, exact, 'exact');\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function next() {\n if (Array.isArray(process._events.exit))\n process._events.exit = process._events.exit[1];\n if (++t === tests.length)\n return;\n\n const v = tests[t];\n v.next = once(next);\n v.msg = msg.bind(null, v.what);\n v.run(v.msg, v.next);\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " function onReady() {\n assert(++state.readies <= 4,\n msg(`Wrong ready count: ${state.readies}`));\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "function next() {\n if (Array.isArray(process._events.exit))\n process._events.exit = process._events.exit[1];\n if (++t === tests.length)\n return;\n\n const v = tests[t];\n v.next = once(next);\n v.msg = msg.bind(null, v.what);\n v.run(v.msg, v.next);\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " function onSFTP() {\n if (clientSFTP && serverSFTP)\n self.onReady(clientSFTP, serverSFTP);\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " attrs: new Stats({\n mode: 0o777 | constants.S_IFDIR,\n size: 4096,\n uid: 9001,\n gid: 8001,\n atime: 1368729954,\n mtime: 1368729999\n })\n },\n { filename: 'bar',\n longname: '-rw-r--r-- 1 nodejs nodejs 513901992 Dec 4 2009 bar',\n attrs: new Stats({\n mode: 0o644 | constants.S_IFREG,\n size: 513901992,\n uid: 9001,\n gid: 8001,\n atime: 1259972199,\n mtime: 1259972199\n })\n }\n ];\n server.on('READDIR', mustCall((id, handle) => {\n assert(id === 0, msg(`Wrong request id: ${id}`));\n assert.deepStrictEqual(handle, handle_, msg('handle mismatch'));\n server.name(id, list_);\n server.end();\n }));\n client.readdir(handle_, mustCall((err, list) => {\n assert(!err, msg(`Unexpected readdir() error: ${err}`));\n assert.deepStrictEqual(list,\n list_.slice(2),\n msg('dir list mismatch'));\n }));\n });\n }),", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "exports.merge = function merge(to, from) {\n var keys = Object.keys(from),\n i = keys.length,\n key;\n\n while (i--) {\n key = keys[i];\n if (specialProperties.indexOf(key) !== -1) {\n continue;\n }\n if ('undefined' === typeof to[key]) {\n to[key] = from[key];\n } else {\n if (exports.isObject(from[key])) {\n merge(to[key], from[key]);\n } else {\n to[key] = from[key];\n }\n }\n }\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "module.exports.checkout = function (callback) {\n cp.exec(gitApp + \" checkout -- .\", gitExtra, callback);\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-77", "cwe_name": "Improper Neutralization of Special Elements used in a Command ('Command Injection')", "description": "The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/77.html", "label_name": "safe"} {"code": "module.exports.commit = function (files, message, newVer, tagName, callback) {\n message = escapeQuotes(message.replace(\"%s\", newVer));\n files = files.map(escapeQuotes).join(\" \");\n var functionSeries = [\n function (done) {\n cp.exec(gitApp + \" add \" + files, gitExtra, done);\n },\n\n function (done) {\n cp.exec([gitApp, \"commit\", \"-m\", message].join(\" \"), gitExtra, done);\n },\n\n function (done) {\n cp.exec(\n [gitApp, \"tag\", \"-a\", tagName, \"-m\", message].join(\" \"),\n gitExtra,\n done\n );\n },\n ];\n contra.series(functionSeries, callback);\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-77", "cwe_name": "Improper Neutralization of Special Elements used in a Command ('Command Injection')", "description": "The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/77.html", "label_name": "safe"} {"code": " git.commit = function (files, message, newVer, tagName, callback) {\n assert.equal(message, \"Message\");\n assert.equal(newVer, \"1.0.0\");\n assert.equal(files[0], expectedPath);\n assert.equal(tagName, \"v1.0.0\");\n return callback(null);\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-77", "cwe_name": "Improper Neutralization of Special Elements used in a Command ('Command Injection')", "description": "The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/77.html", "label_name": "safe"} {"code": " cp.exec = function (cmd, extra, cb) {\n if (cmd.indexOf(\"-a\") === -1) return cb(null);\n assert.equal('git tag -a v1.0.0 -m \"Message \\\\`touch file\\\\`\"', cmd);\n done();\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-77", "cwe_name": "Improper Neutralization of Special Elements used in a Command ('Command Injection')", "description": "The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/77.html", "label_name": "safe"} {"code": " function (done) {\n cp.exec(\n [gitApp, \"tag\", \"-a\", escapeQuotes(tagName), \"-m\", message].join(\" \"),\n gitExtra,\n done\n );\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "\tunsafeMember: function (left, right, computed) {\n\t\tif (computed) return this.unsafeComputedMember(left, right);\n\t\treturn this.unsafeNonComputedMember(left, right);\n\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "function assertNotHasOwnProperty(name, context) {\n\tif (name === \"hasOwnProperty\") {\n\t\tthrow ngMinErr(\n\t\t\t\"badname\",\n\t\t\t\"hasOwnProperty is not a valid {0} name\",\n\t\t\tcontext\n\t\t);\n\t}\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "function isStateless($filter, filterName) {\n\tvar fn = $filter(filterName);\n\treturn !fn.$stateful;\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "\t\t\t\tnoUnsafeEval: noUnsafeEval(),\n\t\t\t\tnoInlineStyle: false\n\t\t\t};\n\t\t}\n\t}\n\n\treturn csp.rules;\n\n\tfunction noUnsafeEval() {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-new, no-new-func\n\t\t\tnew Function(\"\");\n\t\t\treturn false;\n\t\t} catch (e) {\n\t\t\treturn true;\n\t\t}\n\t}\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "\tcomputedMember: function(left, right) {\n\t\treturn left + \"[\" + right + \"]\";\n\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "function bind(self, fn) {\n\tvar curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];\n\tif (isFunction(fn) && !(fn instanceof RegExp)) {\n\t\treturn curryArgs.length\n\t\t\t? function() {\n\t\t\t\t\treturn arguments.length\n\t\t\t\t\t\t? fn.apply(self, concat(curryArgs, arguments, 0))\n\t\t\t\t\t\t: fn.apply(self, curryArgs);\n\t\t\t }\n\t\t\t: function() {\n\t\t\t\t\treturn arguments.length ? fn.apply(self, arguments) : fn.call(self);\n\t\t\t };\n\t} else {\n\t\t// In IE, native methods are not functions so they cannot be bound (note: they don't need to be).\n\t\treturn fn;\n\t}\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "\tprogram: function() {\n\t\tvar body = [];\n\t\twhile (true) {\n\t\t\tif (this.tokens.length > 0 && !this.peek(\"}\", \")\", \";\", \"]\"))\n\t\t\t\tbody.push(this.expressionStatement());\n\t\t\tif (!this.expect(\";\")) {\n\t\t\t\treturn { type: AST.Program, body: body };\n\t\t\t}\n\t\t}\n\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "function isNumber(value) {\n\treturn typeof value === \"number\";\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "\tternary: function() {\n\t\tvar test = this.logicalOR();\n\t\tvar alternate;\n\t\tvar consequent;\n\t\tif (this.expect(\"?\")) {\n\t\t\talternate = this.expression();\n\t\t\tif (this.consume(\":\")) {\n\t\t\t\tconsequent = this.expression();\n\t\t\t\treturn {\n\t\t\t\t\ttype: AST.ConditionalExpression,\n\t\t\t\t\ttest: test,\n\t\t\t\t\talternate: alternate,\n\t\t\t\t\tconsequent: consequent\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn test;\n\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "\tlazyAssign: function(id, value) {\n\t\tvar self = this;\n\t\treturn function() {\n\t\t\tself.assign(id, value);\n\t\t};\n\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "\t\t\tfn.assign = function(scope, value, locals) {\n\t\t\t\treturn assign(scope, locals, value);\n\t\t\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "function assertArgFn(arg, name, acceptArrayAnnotation) {\n\tif (acceptArrayAnnotation && isArray(arg)) {\n\t\targ = arg[arg.length - 1];\n\t}\n\n\tassertArg(\n\t\tisFunction(arg),\n\t\tname,\n\t\t\"not a function, got \" +\n\t\t\t(arg && typeof arg === \"object\"\n\t\t\t\t? arg.constructor.name || \"Object\"\n\t\t\t\t: typeof arg)\n\t);\n\treturn arg;\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "\tnot: function(expression) {\n\t\treturn \"!(\" + expression + \")\";\n\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "\t\t\t\t\tfunction constantWatch(scope) {\n\t\t\t\t\t\tunwatch();\n\t\t\t\t\t\treturn parsedExpression(scope);\n\t\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " me.urls2links = function(element)\n {\n element.html(\n DOMPurify.sanitize(\n element.html().replace(\n /(((https?|ftp):\\/\\/[\\w?!=&.\\/-;#@~%+*-]+(?![\\w\\s?!&.\\/;#~%\"=-]>))|((magnet):[\\w?=&.\\/-;#@~%+*-]+))/ig,\n '$1'\n ),\n purifyHtmlConfig\n )\n );\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\texports.deepCopy = function(target, source) {\n\t\tfor (var name in source) {\n\t\t\tvar tval = target[name],\n \t\t\t sval = source[name];\n\t\t\tif (name !== '__proto__' && tval !== sval) {\n\t\t\t\tif (shouldDeepCopy(sval)) {\n\t\t\t\t\tif (Object.prototype.toString.call(sval) === '[object Date]') { // use this date test to handle crossing frame boundaries\n\t\t\t\t\t\ttarget[name] = new Date(sval);\n\t\t\t\t\t} else if (lang.isArray(sval)) {\n \t\t\t\t\t\t target[name] = exports.deepCopyArray(sval);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (tval && typeof tval === 'object') {\n\t\t\t\t\t\t\texports.deepCopy(tval, sval);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[name] = exports.deepCopy({}, sval);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttarget[name] = sval;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn target;\n\t};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "safe"} {"code": "lex:function lex () {\n var r = this.next();\n if (r) {\n return r;\n } else {\n return this.lex();\n }\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "safe"} {"code": "function createWrapper(fn, options) {\n options = options || {}\n var name = fn.name;\n name = (name || '').replace(/\\s|bound(?!$)/g, '')\n var newFn = function () {\n var self = this\n var len = arguments.length\n if (options.withCallback) {\n var lastType = typeof arguments[len - 1]\n if (lastType === 'function') return fn.apply(self, arguments)\n }\n var args = new Array(len + 1)\n for (var i = 0; i < len; ++i) args[i] = arguments[i]\n var lastIndex = i\n return new Promise(function (resolve, reject) {\n args[lastIndex] = createCallback(resolve, reject, options.multiArgs)\n fn.apply(self, args)\n })\n }\n Object.defineProperty(newFn, 'name', { value: name })\n return newFn\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " function fn(a, b, c, cb) {\n cb(null, a, b, c)\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " forEach: function (path, cb, thisArg) {\n forEach(Array.isArray(path) ? path : split(path), cb, thisArg)\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-915", "cwe_name": "Improperly Controlled Modification of Dynamically-Determined Object Attributes", "description": "The software receives input from an upstream component that specifies multiple attributes, properties, or fields that are to be initialized or updated in an object, but it does not properly control which attributes can be modified.", "url": "https://cwe.mitre.org/data/definitions/915.html", "label_name": "safe"} {"code": "file._copy = function(srcpath, destpath, options) {\n if (!options) { options = {}; }\n // If a process function was specified, and noProcess isn't true or doesn't\n // match the srcpath, process the file's source.\n var process = options.process && options.noProcess !== true &&\n !(options.noProcess && file.isMatch(options.noProcess, srcpath));\n // If the file will be processed, use the encoding as-specified. Otherwise,\n // use an encoding of null to force the file to be read/written as a Buffer.\n var readWriteOptions = process ? options : {encoding: null};\n // Actually read the file.\n var contents = file.read(srcpath, readWriteOptions);\n if (process) {\n grunt.verbose.write('Processing source...');\n try {\n contents = options.process(contents, srcpath, destpath);\n grunt.verbose.ok();\n } catch (e) {\n grunt.verbose.error();\n throw grunt.util.error('Error while processing \"' + srcpath + '\" file.', e);\n }\n }\n // Abort copy if the process function returns false.\n if (contents === false || file.isLink(destpath)) {\n grunt.verbose.writeln('Write aborted. Either the process function returned false or the destination is a symlink');\n } else {\n file.write(destpath, contents, readWriteOptions);\n }\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-367", "cwe_name": "Time-of-check Time-of-use (TOCTOU) Race Condition", "description": "The software checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the software to perform invalid actions when the resource is in an unexpected state.", "url": "https://cwe.mitre.org/data/definitions/367.html", "label_name": "safe"} {"code": " let tempSocketErr = function (err) {\n if (finished) {\n return;\n }\n finished = true;\n try {\n socket.destroy();\n } catch (E) {\n // ignore\n }\n callback(err);\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-88", "cwe_name": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", "description": "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", "url": "https://cwe.mitre.org/data/definitions/88.html", "label_name": "safe"} {"code": "function proxyConnect(port, host, destinationPort, destinationHost, callback) {\n let socket = net.connect(port, host, function () {\n socket.write('CONNECT ' + destinationHost + ':' + destinationPort + ' HTTP/1.1\\r\\n\\r\\n');\n\n let headers = '';\n let onSocketData = function (chunk) {\n let match;\n let remainder;\n\n headers += chunk.toString('binary');\n if ((match = headers.match(/\\r\\n\\r\\n/))) {\n socket.removeListener('data', onSocketData);\n remainder = headers.substr(match.index + match[0].length);\n headers = headers.substr(0, match.index);\n if (remainder) {\n socket.unshift(Buffer.from(remainder, 'binary'));\n }\n // proxy connection is now established\n return callback(null, socket);\n }\n };\n socket.on('data', onSocketData);\n });\n\n socket.on('error', function (err) {\n expect(err).to.not.exist;\n });\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-88", "cwe_name": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", "description": "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", "url": "https://cwe.mitre.org/data/definitions/88.html", "label_name": "safe"} {"code": " oauth2: new XOAuth2({\n user: 'testuser',\n clientId: '{Client ID}',\n clientSecret: '{Client Secret}',\n refreshToken: 'refresh-token',\n accessToken: 'uuuuu',\n accessUrl: 'http://localhost:' + XOAUTH_PORT\n })\n },\n function (err) {\n expect(err).to.not.exist;\n expect(client.authenticated).to.be.true;\n done();\n }\n );\n });", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-88", "cwe_name": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", "description": "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", "url": "https://cwe.mitre.org/data/definitions/88.html", "label_name": "safe"} {"code": " let onSocketData = function (chunk) {\n let match;\n let remainder;\n\n headers += chunk.toString('binary');\n if ((match = headers.match(/\\r\\n\\r\\n/))) {\n socket.removeListener('data', onSocketData);\n remainder = headers.substr(match.index + match[0].length);\n headers = headers.substr(0, match.index);\n if (remainder) {\n socket.unshift(Buffer.from(remainder, 'binary'));\n }\n // proxy connection is now established\n return callback(null, socket);\n }\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-88", "cwe_name": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", "description": "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", "url": "https://cwe.mitre.org/data/definitions/88.html", "label_name": "safe"} {"code": "OAuthServer.prototype.stop = function (callback) {\n this.server.close(callback);\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-88", "cwe_name": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", "description": "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", "url": "https://cwe.mitre.org/data/definitions/88.html", "label_name": "safe"} {"code": " message: new MockBuilder(\n {\n from: isErr ? 'test@invalid.sender' : 'test@valid.sender',\n to: 'test@valid.recipient'\n },\n message\n )\n },\n function (err) {\n if (isErr) {\n expect(err).to.exist;\n } else {\n expect(err).to.not.exist;\n }\n\n callback();\n }\n );\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-88", "cwe_name": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", "description": "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", "url": "https://cwe.mitre.org/data/definitions/88.html", "label_name": "safe"} {"code": "function loadProject(name) {\n let fullPath = fspath.resolve(fspath.join(projectsDir,name));\n var projectPath = name;\n if (projectPath.indexOf(fspath.sep) === -1) {\n projectPath = fullPath;\n } else {\n // Ensure this project dir is under projectsDir;\n let relativePath = fspath.relative(projectsDir,fullPath);\n if (/^\\.\\./.test(relativePath)) {\n throw new Error(\"Invalid project name\")\n }\n }\n return Projects.load(projectPath).then(function(project) {\n activeProject = project;\n flowsFullPath = project.getFlowFile();\n flowsFileBackup = project.getFlowFileBackup();\n credentialsFile = project.getCredentialsFile();\n credentialsFileBackup = project.getCredentialsFileBackup();\n return project;\n })\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " e: function (str) {\n /* BEGIN MODIFICATION */\n // Removed handling of tree.JavaScript\n return new(tree.Anonymous)(str);\n /* END MODIFICATION */\n\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "function buildURL (source, reqBase) {\n const dest = new URL(source, reqBase)\n\n // if base is specified, source url should not override it\n if (reqBase) {\n if (!reqBase.endsWith('/') && dest.href.length > reqBase.length) {\n reqBase = reqBase + '/'\n }\n\n if (!dest.href.startsWith(reqBase)) {\n throw new Error('source must be a relative path string')\n }\n }\n\n return dest\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "async function httpProxy (fastify, opts) {\n if (!opts.upstream) {\n throw new Error('upstream must be specified')\n }\n\n const preHandler = opts.preHandler || opts.beforeHandler\n const rewritePrefix = generateRewritePrefix(fastify.prefix, opts)\n\n const fromOpts = Object.assign({}, opts)\n fromOpts.base = opts.upstream\n fromOpts.prefix = undefined\n\n const oldRewriteHeaders = (opts.replyOptions || {}).rewriteHeaders\n const replyOpts = Object.assign({}, opts.replyOptions, {\n rewriteHeaders\n })\n fromOpts.rewriteHeaders = rewriteHeaders\n\n fastify.register(From, fromOpts)\n\n if (opts.proxyPayloads !== false) {\n fastify.addContentTypeParser('application/json', bodyParser)\n fastify.addContentTypeParser('*', bodyParser)\n }\n\n function rewriteHeaders (headers) {\n const location = headers.location\n if (location) {\n headers.location = location.replace(rewritePrefix, fastify.prefix)\n }\n if (oldRewriteHeaders) {\n headers = oldRewriteHeaders(headers)\n }\n return headers\n }\n\n function bodyParser (req, payload, done) {\n done(null, payload)\n }\n\n fastify.route({\n url: '/',\n method: httpMethods,\n preHandler,\n config: opts.config || {},\n handler\n })\n fastify.route({\n url: '/*',\n method: httpMethods,\n preHandler,\n config: opts.config || {},\n handler\n })\n\n function handler (request, reply) {\n let dest = request.raw.url\n dest = dest.replace(this.prefix, rewritePrefix)\n reply.from(dest || '/', replyOpts)\n }\n\n if (opts.websocket) {\n setupWebSocketProxy(fastify, opts, rewritePrefix)\n }\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "function parseDCC(source,start,domBuilder,errorHandler){//sure start with '',start+4);\n\t\t\t//append comment source.substring(4,end)//', 'gsi'), '');\r\n }\r\n var parser = new DOMParser();\r\n var d = parser.parseFromString(data, \"text/html\");\r\n parse(d);\r\n var span = document.createElement('span');\r\n span.innerHTML = d.firstChild.innerHTML;\r\n return span;\r\n } \r", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " obj.refresh = function() {\r\n if (obj.options.responsive == true) {\r\n // Width of the c\r\n var rect = el.parentNode.getBoundingClientRect();\r\n if (! obj.options.maxWidth) {\r\n obj.options.maxWidth = rect.width;\r\n }\r\n // Max width\r\n var width = parseInt(obj.options.maxWidth); \r\n // Remove arrow\r\n toolbarArrow.remove();\r\n // Move all items to the toolbar\r\n while (toolbarFloating.firstChild) {\r\n toolbarContent.appendChild(toolbarFloating.firstChild);\r\n }\r\n // Available parent space\r\n var available = obj.options.maxWidth;\r\n // Toolbar is larger than the parent, move elements to the floating element\r\n if (available < toolbarContent.offsetWidth) {\r\n // Give space to the floating element\r\n available -= 50;\r\n // Move to the floating option\r\n while (toolbarContent.lastChild && available < toolbarContent.offsetWidth) {\r\n toolbarFloating.insertBefore(toolbarContent.lastChild, toolbarFloating.firstChild);\r\n }\r\n }\r\n // Show arrow\r\n if (toolbarFloating.children.length > 0) {\r\n toolbarContent.appendChild(toolbarArrow);\r\n }\r\n }\r\n }\r", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " setTemplates: function() {\n var iconHTML = '';\n if (this.options.suggestionIcon !== '') {\n iconHTML = '';\n }\n\n // suggestions\n if (this.options.fields.length) {\n this.suggestionTpl = this.sandbox.util.template('' +\n '
    \">' +\n '
    ' +\n '
    ' +\n ' <% _.each(fields, function(field, idx) { %>' +\n '
    ;\"><%- context[field.id] %>
    ' +\n ' <% }) %>' +\n '
    ' +\n '
    ' +\n '
    ');\n } else {\n this.suggestionTpl = this.sandbox.util.template('' +\n '
    \">' +\n '
    ' +\n iconHTML +\n '
    <%- context[this.options.valueKey] %>
    ' +\n '
    ' +\n '
    ');\n }\n\n if (!!this.options.footerContent) {\n this.footerTpl = this.sandbox.util.template(\n '
    ' +\n this.options.footerContent +\n '
    '\n );\n }\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "const escape = (str, re = /[&<>'\"]/g) => str.replace(re, (m) => ESCAPE[m]);", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "const get = async (req, res) => {\n logger.debug('URL file import handler running', null, req.id)\n const { allowLocalUrls } = req.companion.options\n if (!validateURL(req.body.url, allowLocalUrls)) {\n logger.debug('Invalid request body detected. Exiting url import handler.', null, req.id)\n res.status(400).json({ error: 'Invalid request body' })\n return\n }\n\n async function getSize () {\n const { size } = await getURLMeta(req.body.url, !allowLocalUrls)\n return size\n }\n\n async function download () {\n return downloadURL(req.body.url, !allowLocalUrls, req.id)\n }\n\n function onUnhandledError (err) {\n logger.error(err, 'controller.url.error', req.id)\n // @todo send more meaningful error message and status code to client if possible\n res.status(err.status || 500).json({ message: 'failed to fetch URL metadata' })\n }\n\n startDownUpload({ req, res, getSize, download, onUnhandledError })\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-863", "cwe_name": "Incorrect Authorization", "description": "The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.", "url": "https://cwe.mitre.org/data/definitions/863.html", "label_name": "safe"} {"code": "var _getStorageId = function(client) {\n // TODO: include browser in ID to avoid sharing cookies between\n // browsers (if this is undesirable)\n // navigator.userAgent\n return 'forge.http.' +\n client.url.protocol.slice(0, -1) + '.' +\n client.url.hostname + '.' +\n client.url.port;\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "safe"} {"code": "asn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n parseAllBytes: true,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('parseAllBytes' in options)) {\n options.parseAllBytes = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var byteCount = bytes.length();\n var value = _fromDer(bytes, bytes.length(), 0, options);\n if(options.parseAllBytes && bytes.length() !== 0) {\n var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');\n error.byteCount = byteCount;\n error.remaining = bytes.length();\n throw error;\n }\n return value;\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "safe"} {"code": "\t\t\t\tsuccess( response ) {\n\t\t\t\t\tel.$().removeAttr( 'data-custom' );\n\t\t\t\t\tel.$( '.profile-picture' ).toggleClass( 'profile-avatar-current' );\n\t\t\t\t\tel.$( '#submit' ).prop( 'disabled', false );\n\n\t\t\t\t\t$( '.lp-user-profile-avatar' ).html( el.$( '.profile-avatar-current' ).find( 'img' ).clone() );\n\t\t\t\t},", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-610", "cwe_name": "Externally Controlled Reference to a Resource in Another Sphere", "description": "The product uses an externally controlled name or reference that resolves to a resource that is outside of the intended control sphere.", "url": "https://cwe.mitre.org/data/definitions/610.html", "label_name": "safe"} {"code": " URI.parse = function(string, parts) {\n var pos;\n if (!parts) {\n parts = {\n preventInvalidHostname: URI.preventInvalidHostname\n };\n }\n\n string = string.replace(URI.leading_whitespace_expression, '')\n\n // [protocol\"://\"[username[\":\"password]\"@\"]hostname[\":\"port]\"/\"?][path][\"?\"querystring][\"#\"fragment]\n\n // extract fragment\n pos = string.indexOf('#');\n if (pos > -1) {\n // escaping?\n parts.fragment = string.substring(pos + 1) || null;\n string = string.substring(0, pos);\n }\n\n // extract query\n pos = string.indexOf('?');\n if (pos > -1) {\n // escaping?\n parts.query = string.substring(pos + 1) || null;\n string = string.substring(0, pos);\n }\n\n // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)\n string = string.replace(/^(https?|ftp|wss?)?:+[/\\\\]*/i, '$1://');\n\n // extract protocol\n if (string.substring(0, 2) === '//') {\n // relative-scheme\n parts.protocol = null;\n string = string.substring(2);\n // extract \"user:pass@host:port\"\n string = URI.parseAuthority(string, parts);\n } else {\n pos = string.indexOf(':');\n if (pos > -1) {\n parts.protocol = string.substring(0, pos) || null;\n if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {\n // : may be within the path\n parts.protocol = undefined;\n } else if (string.substring(pos + 1, pos + 3).replace(/\\\\/g, '/') === '//') {\n string = string.substring(pos + 3);\n\n // extract \"user:pass@host:port\"\n string = URI.parseAuthority(string, parts);\n } else {\n string = string.substring(pos + 1);\n parts.urn = true;\n }\n }\n }\n\n // what's left must be the path\n parts.path = string;\n\n // and we're done\n return parts;\n };", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "safe"} {"code": "function * saveEditAccount ({ payload }) {\n try {\n const response = yield call(api.accounts.updateUser, payload)\n yield put({ type: SAVE_EDIT_ACCOUNT.SUCCESS, response })\n yield put({ type: HIDE_MODAL.ACTION })\n helpers.UI.showSnackbar('Account updated successfully')\n } catch (error) {\n let errorText = ''\n if (error.response) errorText = error.response.data.error\n if (errorText.message) errorText = errorText.message\n helpers.UI.showSnackbar(`Error: ${errorText}`, true)\n Log.error(errorText, error.response || error)\n yield put({ type: SAVE_EDIT_ACCOUNT.ERROR, error })\n }\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-521", "cwe_name": "Weak Password Requirements", "description": "The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.", "url": "https://cwe.mitre.org/data/definitions/521.html", "label_name": "safe"} {"code": "departmentSchema.statics.getUserDepartments = async function (userId, callback) {\n const self = this\n return new Promise((resolve, reject) => {\n ;(async () => {\n try {\n const teams = await Teams.getTeamsOfUser(userId)\n const exec = self.model(COLLECTION).find({ teams: { $in: teams } })\n if (typeof callback === 'function') {\n return exec.exec(callback)\n }\n\n const departments = await exec.exec()\n return resolve(departments)\n } catch (e) {\n return reject(e)\n }\n })()\n })\n}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-521", "cwe_name": "Weak Password Requirements", "description": "The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.", "url": "https://cwe.mitre.org/data/definitions/521.html", "label_name": "safe"} {"code": " $scope.updateUser = function ($event) {\n $event.preventDefault()\n\n var id = $('div[data-user_id]').attr('data-user_id')\n if (_.isUndefined(id)) return\n var data = getFormData()\n\n if (\n data.fullname.toString().length > 25 ||\n data.password.toString().length > 255 ||\n data.cPassword.toString().length > 255 ||\n data.email.toString().length > 255 ||\n !validateEmail(data.email.toString())\n ) {\n helpers.UI.showSnackbar('Form data invalid.', true)\n return false\n }\n\n $http\n .put('/api/v1/users/' + data.username, {\n aId: id,\n aFullname: data.fullname,\n aPass: data.password,\n aPassConfirm: data.cPassword,\n aEmail: data.email,\n\n saveGroups: false\n })\n .success(function () {\n resetForm()\n helpers.UI.showSnackbar({\n text: 'Profile Successfully Saved',\n textColor: '#f8f8f2'\n })\n })\n .error(function (e) {\n if (e.error.message) {\n $log.log('[trudesk:profile:updateUser] - ' + e.error.message)\n helpers.UI.showSnackbar('Error ' + e.error.message, true)\n } else {\n $log.log('[trudesk:profile:updateUser] - ' + e.error)\n helpers.UI.showSnackbar('Error: ' + e.error, true)\n }\n })\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-521", "cwe_name": "Weak Password Requirements", "description": "The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.", "url": "https://cwe.mitre.org/data/definitions/521.html", "label_name": "safe"} {"code": " success: function (response) {\n if (response.success) {\n // Check if on conversation\n const $convo = $('#message-content[data-conversation-id=\"' + response.conversation._id + '\"]')\n if ($convo.length > 0) {\n History.pushState(null, null, '/messages', false)\n } else {\n const $convoLI = $('#convo-list').find('li[data-conversation-id=\"' + response.conversation._id + '\"]')\n if ($convoLI.length > 0) {\n $convoLI.remove()\n }\n }\n\n $.event.trigger('$trudesk:chat:conversation:deleted', {\n conversation: response.conversation\n })\n\n helpers.UI.showSnackbar('Conversation Deleted.', false)\n }\n },", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-662", "cwe_name": "Improper Synchronization", "description": "The software utilizes multiple threads or processes to allow temporary access to a shared resource that can only be exclusive to one process at a time, but it does not properly synchronize these actions, which might cause simultaneous accesses of this resource by multiple threads or processes.", "url": "https://cwe.mitre.org/data/definitions/662.html", "label_name": "safe"} {"code": " function loadMoreMessages () {\n if (!$enabled || $loading) return false\n if (_.isUndefined($convoId)) return false\n $loading = true\n $spinner.removeClass('uk-hidden')\n\n // Load Messages\n $.ajax({\n url: '/api/v1/messages/conversation/' + $convoId + '?page=' + $nextPage\n })\n .done(function (data) {\n $spinner.addClass('uk-hidden')\n const messages = data.messages\n if (_.size(messages) < 1) {\n $enabled = false\n $loading = false\n return false\n }\n\n let html = ''\n\n _.each(messages, function (m) {\n const h = buildMessageHTML(m)\n if (h.length > 0) html += h\n })\n\n const stage = $('
    ')\n .appendTo('body')\n .addClass('stage')\n .css({\n opacity: 0,\n visibility: 'hidden',\n position: 'absolute',\n top: '-9999em',\n left: '-9999em'\n })\n .append(html)\n const height = $(stage).outerHeight()\n $(stage).remove()\n\n $messagesWrapper.prepend(html)\n\n UIKit.$html.trigger('changed.uk.dom')\n $messageScroller.scrollTop(height, true)\n\n $nextPage = $nextPage + 1\n $loading = false\n })\n .error(function (err) {\n console.log(err)\n })\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-662", "cwe_name": "Improper Synchronization", "description": "The software utilizes multiple threads or processes to allow temporary access to a shared resource that can only be exclusive to one process at a time, but it does not properly synchronize these actions, which might cause simultaneous accesses of this resource by multiple threads or processes.", "url": "https://cwe.mitre.org/data/definitions/662.html", "label_name": "safe"} {"code": " function onSearchKeyUp () {\n const searchTerm = $searchBox.val().toLowerCase()\n $('.all-user-list li').each(function () {\n if ($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) {\n $(this).show()\n } else {\n $(this).hide()\n }\n })\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-662", "cwe_name": "Improper Synchronization", "description": "The software utilizes multiple threads or processes to allow temporary access to a shared resource that can only be exclusive to one process at a time, but it does not properly synchronize these actions, which might cause simultaneous accesses of this resource by multiple threads or processes.", "url": "https://cwe.mitre.org/data/definitions/662.html", "label_name": "safe"} {"code": " function deleteConversation (convoId) {\n $.ajax({\n url: '/api/v1/messages/conversation/' + convoId,\n method: 'DELETE',\n success: function (response) {\n if (response.success) {\n // Check if on conversation\n const $convo = $('#message-content[data-conversation-id=\"' + response.conversation._id + '\"]')\n if ($convo.length > 0) {\n History.pushState(null, null, '/messages', false)\n } else {\n const $convoLI = $('#convo-list').find('li[data-conversation-id=\"' + response.conversation._id + '\"]')\n if ($convoLI.length > 0) {\n $convoLI.remove()\n }\n }\n\n $.event.trigger('$trudesk:chat:conversation:deleted', {\n conversation: response.conversation\n })\n\n helpers.UI.showSnackbar('Conversation Deleted.', false)\n }\n },\n error: function (error) {\n console.log(error)\n }\n })\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-662", "cwe_name": "Improper Synchronization", "description": "The software utilizes multiple threads or processes to allow temporary access to a shared resource that can only be exclusive to one process at a time, but it does not properly synchronize these actions, which might cause simultaneous accesses of this resource by multiple threads or processes.", "url": "https://cwe.mitre.org/data/definitions/662.html", "label_name": "safe"} {"code": " groups: function (done) {\n groupSchema.getAllGroupsOfUser(obj._id, done)\n }", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-269", "cwe_name": "Improper Privilege Management", "description": "The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.", "url": "https://cwe.mitre.org/data/definitions/269.html", "label_name": "safe"} {"code": "var getExternalHostUrl = function () {\n var loc = window.location;\n var port = \"\";\n if (\n (loc.protocol === \"http:\" && loc.port !== \"80\") ||\n (loc.protocol === \"https:\" && loc.port !== \"443\")\n ) {\n port = \":\" + loc.port;\n }\n return loc.protocol + \"//\" + loc.hostname + port;\n};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "f.desc.headRevisionId+\"-mod_\"+f.desc.modifiedDate+\"-size_\"+f.getSize()+\"-mime_\"+f.desc.mimeType+(this.ui.editor.autosave?\"\":\"-nosave\")+(f.isAutosave()?\"\":\"-noauto\")+(f.changeListenerEnabled?\"\":\"-nolisten\")+(f.inConflictState?\"-conflict\":\"\")+(f.invalidChecksum?\"-invalid\":\"\"),label:(null!=this.user?\"user_\"+this.user.id:\"nouser\")+(null!=f.sync?\"-client_\"+f.sync.clientId:\"-nosync\")})}catch(ba){}}else\"1\"==urlParams.test&&R.headRevisionId==I&&EditorUi.debug(\"DriveClient: Remote Etag Changed\",\"local\",W,\n\"remote\",R.etag,\"rev\",f.desc.headRevisionId,\"response\",[R],\"file\",[f]),q(Q,R)}catch(ba){x(ba)}}),mxUtils.bind(this,function(){q(Q)})):q(Q)}catch(R){x(R)}}}))}catch(Q){x(Q)}}),X=mxUtils.bind(this,function(D){f.saveLevel=9;if(D||null==W)U(D);else{var K=!0,T=null;try{T=window.setTimeout(mxUtils.bind(this,function(){K=!1;q({code:App.ERROR_TIMEOUT})}),3*this.ui.timeout)}catch(N){}this.executeRequest({url:\"/files/\"+f.getId()+\"?supportsAllDrives=true&fields=\"+this.catchupFields},mxUtils.bind(this,function(N){window.clearTimeout(T);", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "0==T?ba():R()}else this.stoppingCustomActions=this.executingCustomActions=!1,R(),null!=D&&D()});ba()}};Graph.prototype.doUpdateCustomLinksForCell=function(u,D){var K=this.getLinkForCell(D);null!=K&&\"data:action/json,\"==K.substring(0,17)&&this.setLinkForCell(D,this.updateCustomLink(u,K));if(this.isHtmlLabel(D)){var T=document.createElement(\"div\");T.innerHTML=this.sanitizeHtml(this.getLabel(D));for(var N=T.getElementsByTagName(\"a\"),Q=!1,R=0;R=Ia.getStatus()&&(ra=Ia.getText());Ka(ra)}))):Ka(ra)}", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "H.x+\" \"+H.y;S=\"\";d=[];for(V=2;Vf;)x.shift()},P=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "\"stencil(\"+I+\")\",[A])}catch(z){throw z;}finally{y.getModel().endUpdate()}O&&(y.setSelectionCell(A),y.scrollCellToVisible(A))}};f=mxUtils.button(mxResources.get(\"preview\"),function(){x(l,p,!1)});f.className=\"geBtn\";g.appendChild(f);f=mxUtils.button(mxResources.get(\"apply\"),function(){x(b.editor.graph,e,!0)});f.className=\"geBtn gePrimaryBtn\";g.appendChild(f);b.editor.cancelFirst||g.appendChild(m);d.appendChild(g);v.appendChild(d);n.appendChild(v);this.container=n},CustomDialog=function(b,e,f,c,m,n,\nv,d,g,k,l){var p=document.createElement(\"div\");p.appendChild(e);var q=document.createElement(\"div\");q.style.marginTop=\"30px\";q.style.textAlign=\"center\";null!=v&&q.appendChild(v);b.isOffline()||null==n||(e=mxUtils.button(mxResources.get(\"help\"),function(){b.openLink(n)}),e.className=\"geBtn\",q.appendChild(e));g=mxUtils.button(g||mxResources.get(\"cancel\"),function(){b.hideDialog();null!=c&&c()});g.className=\"geBtn\";d&&(g.style.display=\"none\");b.editor.cancelFirst&&q.appendChild(g);m=mxUtils.button(m||\nmxResources.get(\"ok\"),mxUtils.bind(this,function(){k||b.hideDialog(null,null,this.container);if(null!=f){var x=f();if(\"string\"===typeof x){b.showError(mxResources.get(\"error\"),x);return}}k&&b.hideDialog(null,null,this.container)}));q.appendChild(m);m.className=\"geBtn gePrimaryBtn\";b.editor.cancelFirst||q.appendChild(g);if(null!=l)for(d=0;d
    ');null==m&&(m=function(){var N=null;try{N=JSON.parse(localStorage.getItem(\"mxODPickerRecentList\"))}catch(Q){}return N});null==n&&(n=function(N){if(null!=N){var Q=m()||{};delete N[\"@microsoft.graph.downloadUrl\"];", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "null!=this.formatWindow&&this.formatWindow.window.setVisible(!1)};EditorUi.prototype.chromelessWindowResize=function(){};var O=DiagramFormatPanel.prototype.addView;DiagramFormatPanel.prototype.addView=function(C){C=O.apply(this,arguments);var E=this.editorUi,G=E.editor.graph;if(G.isEnabled()&&\"1\"==urlParams.sketch){var P=this.createOption(mxResources.get(\"sketch\"),function(){return Editor.sketchMode},function(J,F){E.setSketchMode(!Editor.sketchMode);null!=F&&mxEvent.isShiftDown(F)||G.updateCellStyles({sketch:J?", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "u.appendChild(D));return u}}Graph.fontMapping={\"https://fonts.googleapis.com/css?family=Architects+Daughter\":'@font-face { font-family: \"Architects Daughter\"; src: url('+STYLE_PATH+'/fonts/ArchitectsDaughter-Regular.ttf) format(\"truetype\"); }'};Graph.customFontElements={};Graph.recentCustomFonts={};Graph.isGoogleFontUrl=function(u){return u.substring(0,Editor.GOOGLE_FONTS.length)==Editor.GOOGLE_FONTS};Graph.isCssFontUrl=function(u){return Graph.isGoogleFontUrl(u)};Graph.createFontElement=function(u,\nD){var K=Graph.fontMapping[D];null==K&&Graph.isCssFontUrl(D)?(u=document.createElement(\"link\"),u.setAttribute(\"rel\",\"stylesheet\"),u.setAttribute(\"type\",\"text/css\"),u.setAttribute(\"charset\",\"UTF-8\"),u.setAttribute(\"href\",D)):(null==K&&(K='@font-face {\\nfont-family: \"'+u+'\";\\nsrc: url(\"'+D+'\");\\n}'),u=document.createElement(\"style\"),mxUtils.write(u,K));return u};Graph.addFont=function(u,D,K){if(null!=u&&0=Z.scrollHeight&&", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "function(J){l=J};this.setAutoScroll=function(J){p=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){B=J};this.setSmoothing=function(J){f=J};this.setPerfectFreehandMode=function(J){O=J};this.setBrushSize=function(J){I.size=J};this.getBrushSize=function(){return I.size};var t=function(J){y=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "function(J){l=J};this.setAutoScroll=function(J){p=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){B=J};this.setSmoothing=function(J){f=J};this.setPerfectFreehandMode=function(J){O=J};this.setBrushSize=function(J){I.size=J};this.getBrushSize=function(){return I.size};var t=function(J){y=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "function(){return null!=q?q.readyState:3};this.getLastError=function(){return S};this.mouseListeners={startX:0,startY:0,scrollLeft:0,scrollTop:0,mouseDown:function(M,W){},mouseMove:function(M,W){var U,X=-1;return function(){clearTimeout(U);var u=this,D=arguments,K=function(){U=null;X=Date.now();M.apply(u,D)};Date.now()-X>W?K():U=setTimeout(K,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "var GoogleSitesDialog=function(b,e){function f(){var E=null!=C&&null!=C.getTitle()?C.getTitle():this.defaultFilename;if(z.checked&&\"\"!=q.value){var G=\"https://www.draw.io/gadget.xml?type=4&diagram=\"+encodeURIComponent(mxUtils.htmlEntities(q.value));null!=E&&(G+=\"&title=\"+encodeURIComponent(E));0=k.scrollHeight-k.offsetHeight&&C()},mxEvent.addListener(k,\"scroll\",B))}),y)});t()};GitHubClient.prototype.logout=function(){this.clearPersistentToken();this.setUser(null);b=null}})();TrelloFile=function(b,e,f){DrawioFile.call(this,b,e);this.meta=f;this.saveNeededCounter=0};mxUtils.extend(TrelloFile,DrawioFile);TrelloFile.prototype.getHash=function(){return\"T\"+encodeURIComponent(this.meta.compoundId)};TrelloFile.prototype.getMode=function(){return App.MODE_TRELLO};TrelloFile.prototype.isAutosave=function(){return!0};TrelloFile.prototype.getTitle=function(){return this.meta.name};TrelloFile.prototype.isRenamable=function(){return!1};TrelloFile.prototype.getSize=function(){return this.meta.bytes};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "\"geCommentActionLnk\";mxUtils.write(ba,N);Y.appendChild(ba);mxEvent.addListener(ba,\"click\",function(ea){Q(ea,J);ea.preventDefault();mxEvent.consume(ea)});T.appendChild(Y);R&&(Y.style.display=\"none\")}function W(){function N(Y){Q.push(R);if(null!=Y.replies)for(var ba=0;ba>>8;return u};Editor.crc32=function(u){for(var D=-1,K=0;K>>8^Editor.crcTable[(D^u.charCodeAt(K))&255];return(D^-1)>>>0};Editor.writeGraphModelToPng=function(u,D,K,T,N){function Q(Z,fa){var aa=ba;ba+=fa;return Z.substring(aa,ba)}function R(Z){Z=Q(Z,4);return Z.charCodeAt(3)+(Z.charCodeAt(2)<<8)+(Z.charCodeAt(1)<<16)+(Z.charCodeAt(0)<<24)}function Y(Z){return String.fromCharCode(Z>>24&255,Z>>16&255,Z>>8&255,Z&255)}u=u.substring(u.indexOf(\",\")+", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "mxDualRuler.prototype.setUnit=function(b){this.vRuler.setUnit(b);this.hRuler.setUnit(b)};mxDualRuler.prototype.setStyle=function(b){this.vRuler.setStyle(b);this.hRuler.setStyle(b)};mxDualRuler.prototype.destroy=function(){this.vRuler.destroy();this.hRuler.destroy();this.ui.refresh=this.editorUiRefresh;mxGuide.prototype.move=this.origGuideMove;mxGuide.prototype.destroy=this.origGuideDestroy;this.ui.getDiagramContainerOffset=this.editorUiGetDiagContOffset};function mxFreehand(b){var e=null!=b.view&&null!=b.view.canvas?b.view.canvas.ownerSVGElement:null;if(null!=b.container&&null!=e){b.addListener(mxEvent.ESCAPE,mxUtils.bind(this,function(){this.stopDrawing()}));var f=mxFreehand.prototype.NORMAL_SMOOTHING,c=null,m=[],n,v=[],d,g=!1,k=!0,l=!0,p=!0,q=!0,x=[],y=!1,A=!0,B=!1,I={size:12,thinning:.5,smoothing:.5,streamline:.5,start:{taper:0,cap:!0},end:{taper:0,cap:!0}},O=!1;this.setClosedPath=function(J){g=J};this.setAutoClose=function(J){k=J};this.setAutoInsert=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "this.getInsertPoint=function(){return null!=D?this.getPointForEvent(D):K.apply(this,arguments)};var T=this.layoutManager.getLayout;this.layoutManager.getLayout=function(N){var Q=this.graph.getCellStyle(N);if(null!=Q&&\"rack\"==Q.childLayout){var R=new mxStackLayout(this.graph,!1);R.gridSize=null!=Q.rackUnitSize?parseFloat(Q.rackUnitSize):\"undefined\"!==typeof mxRackContainer?mxRackContainer.unitSize:20;R.marginLeft=Q.marginLeft||0;R.marginRight=Q.marginRight||0;R.marginTop=Q.marginTop||0;R.marginBottom=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "function(aa){T--;N()}),!0,null,\"data:\"+Z+\";charset=utf-8;base64,\")}))}})(Editor.trimCssUrl(K[u].substring(0,Q)),R)}N()}else D(u)};Editor.prototype.loadFonts=function(u){null!=this.fontCss&&null==this.resolvedFontCss?this.embedCssFonts(this.fontCss,mxUtils.bind(this,function(D){this.resolvedFontCss=D;null!=u&&u()})):null!=u&&u()};Editor.prototype.createGoogleFontCache=function(){var u={},D;for(D in Graph.fontMapping)Graph.isCssFontUrl(D)&&(u[D]=Graph.fontMapping[D]);return u};Editor.prototype.embedExtFonts=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "document.createElement(\"link\");N.setAttribute(\"rel\",\"preload\");N.setAttribute(\"href\",T);N.setAttribute(\"as\",\"font\");N.setAttribute(\"crossorigin\",\"\");D.parentNode.insertBefore(N,D)}}}};Editor.trimCssUrl=function(u){return u.replace(RegExp(\"^[\\\\s\\\"']+\",\"g\"),\"\").replace(RegExp(\"[\\\\s\\\"']+$\",\"g\"),\"\")};Editor.GOOGLE_FONTS=\"https://fonts.googleapis.com/css?family=\";Editor.GUID_ALPHABET=\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_\";Editor.GUID_LENGTH=20;Editor.guid=function(u){u=null!=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "e()};OneDriveClient.prototype.getItemRef=function(e){var f=e.split(\"/\");return 1').src;mxWindow.prototype.closeImage=Graph.createSvgImage(18,10,'').src;", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "function(u){var D=this.graph.getCustomFonts();if(0T.indexOf(\"mxPageSelector\")&&0=k.scrollHeight-k.offsetHeight&&P()},mxEvent.addListener(k,\"scroll\",B))}),y)}}))});b?this.user?t():this.updateUser(function(){t()},y,!0):this.authenticate(mxUtils.bind(this,function(){this.updateUser(function(){t()},y,!0)}),y)};GitLabClient.prototype.logout=function(){this.ui.editor.loadUrl(this.redirectUri+\n\"?doLogout=1&state=\"+encodeURIComponent(\"cId=\"+this.clientId+\"&domain=\"+window.location.hostname));this.clearPersistentToken();this.setUser(null);b=null;this.setToken(null)}})();DrawioComment=function(b,e,f,c,m,n,v){this.file=b;this.id=e;this.content=f;this.modifiedDate=c;this.createdDate=m;this.isResolved=n;this.user=v;this.replies=[]};DrawioComment.prototype.addReplyDirect=function(b){null!=b&&this.replies.push(b)};DrawioComment.prototype.addReply=function(b,e,f,c,m){e()};DrawioComment.prototype.editComment=function(b,e,f){e()};DrawioComment.prototype.deleteComment=function(b,e){b()};DriveComment=function(b,e,f,c,m,n,v,d){DrawioComment.call(this,b,e,f,c,m,n,v);this.pCommentId=d};mxUtils.extend(DriveComment,DrawioComment);DriveComment.prototype.addReply=function(b,e,f,c,m){b={content:b.content};c?b.verb=\"resolve\":m&&(b.verb=\"reopen\");this.file.ui.drive.executeRequest({url:\"/files/\"+this.file.getId()+\"/comments/\"+this.id+\"/replies\",params:b,method:\"POST\"},mxUtils.bind(this,function(n){e(n.replyId)}),f)};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "u[D]}catch(K){null!=window.console&&console.log(\"Error in vars URL parameter: \"+K)}};Graph.prototype.getExportVariables=function(){return null!=this.globalVars?mxUtils.clone(this.globalVars):{}};var z=Graph.prototype.getGlobalVariable;Graph.prototype.getGlobalVariable=function(u){var D=z.apply(this,arguments);null==D&&null!=this.globalVars&&(D=this.globalVars[u]);return D};Graph.prototype.getDefaultStylesheet=function(){if(null==this.defaultStylesheet){var u=this.themes[\"default-style2\"];this.defaultStylesheet=\n(new mxCodec(u.ownerDocument)).decode(u)}return this.defaultStylesheet};Graph.prototype.isViewer=function(){return urlParams.viewer};var L=Graph.prototype.getSvg;Graph.prototype.getSvg=function(u,D,K,T,N,Q,R,Y,ba,ea,Z,fa,aa,va){var ja=null,Ba=null,Da=null;fa||null==this.themes||\"darkTheme\"!=this.defaultThemeName||(ja=this.stylesheet,Ba=this.shapeForegroundColor,Da=this.shapeBackgroundColor,this.shapeForegroundColor=\"darkTheme\"==this.defaultThemeName?\"#000000\":Editor.lightColor,this.shapeBackgroundColor=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "D);null!=T&&K.setAttribute(\"backgroundImage\",JSON.stringify(T));K.setAttribute(\"math\",this.graph.mathEnabled?\"1\":\"0\");K.setAttribute(\"shadow\",this.graph.shadowVisible?\"1\":\"0\");null!=this.graph.extFonts&&0=B)break;D[K.id]={replAllMrk:I,replAllPos:B};l.isCellEditable(K)&&(l.model.setValue(K,H(T,A,L.value,B-A.length,l.getCurrentCellStyle(K))),u++)}U!=b.currentPage&&b.editor.graph.model.execute(new SelectPage(b,U));mxUtils.write(F,mxResources.get(\"matchesRepl\",[u]))}catch(Q){b.handleError(Q)}finally{l.getModel().endUpdate(),b.editor.graph.setSelectionCells(X),b.editor.graph.rendering=!0}I++}});M.setAttribute(\"title\",mxResources.get(\"replaceAll\"));M.style.float=\"none\";M.style.width=\"120px\";", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "d(null,null,0,0,0,0,{xml:X,w:ea.width,h:ea.height})}F=!0}}catch(Z){}F||(b.spinner.stop(),b.handleError({message:mxResources.get(\"errorLoadingFile\")}))}}catch(Z){}return null}function g(E){E.dataTransfer.dropEffect=null!=B?\"move\":\"copy\";E.stopPropagation();E.preventDefault()}function k(E){E.stopPropagation();E.preventDefault();z=!1;I=v(E);if(null!=B)null!=I&&IB?I-1:I,0,l.splice(B,1)[0]),x.insertBefore(x.children[B],x.children[I])):(l.push(l.splice(B,1)[0]),x.appendChild(x.children[B]));", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "function(J){l=J};this.setAutoScroll=function(J){p=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){B=J};this.setSmoothing=function(J){f=J};this.setPerfectFreehandMode=function(J){O=J};this.setBrushSize=function(J){I.size=J};this.getBrushSize=function(){return I.size};var t=function(J){y=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "\"\\n\":\"\")+Graph.svgDoctype+\"\\n\"+mxUtils.getXml(F))});this.editor.graph.mathEnabled&&this.editor.addMathCss(E);var J=mxUtils.bind(this,function(F){q?(null==this.thumbImageCache&&(this.thumbImageCache={}),this.editor.convertImages(F,P,this.thumbImageCache)):P(F)});t?this.embedFonts(E,J):(this.editor.addFontCss(E),J(E))}catch(F){this.handleError(F)}};EditorUi.prototype.addRadiobox=function(d,g,k,l,p,q,x){return this.addCheckbox(d,k,l,p,q,x,!0,g)};EditorUi.prototype.addCheckbox=function(d,g,k,l,p,q,x,", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "u.substring(0,29)||\"https://fonts.gstatic.com/\"===u.substring(0,26)};Editor.prototype.createImageUrlConverter=function(){var u=new mxUrlConverter;u.updateBaseUrl();var D=u.convert,K=this;u.convert=function(T){if(null!=T){var N=\"http://\"==T.substring(0,7)||\"https://\"==T.substring(0,8);N&&!navigator.onLine?T=Editor.svgBrokenImage.src:!N||T.substring(0,u.baseUrl.length)==u.baseUrl||K.crossOriginImages&&K.isCorsEnabledForUrl(T)?\"chrome-extension://\"==T.substring(0,19)||mxClient.IS_CHROMEAPP||(T=D.apply(this,\narguments)):T=PROXY_URL+\"?url=\"+encodeURIComponent(T)}return T};return u};Editor.createSvgDataUri=function(u){return\"data:image/svg+xml;base64,\"+btoa(unescape(encodeURIComponent(u)))};Editor.prototype.convertImageToDataUri=function(u,D){try{var K=!0,T=window.setTimeout(mxUtils.bind(this,function(){K=!1;D(Editor.svgBrokenImage.src)}),this.timeout);if(/(\\.svg)$/i.test(u))mxUtils.get(u,mxUtils.bind(this,function(Q){window.clearTimeout(T);K&&D(Editor.createSvgDataUri(Q.getText()))}),function(){window.clearTimeout(T);", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "arguments)):T=PROXY_URL+\"?url=\"+encodeURIComponent(T)}return T};return u};Editor.createSvgDataUri=function(u){return\"data:image/svg+xml;base64,\"+btoa(unescape(encodeURIComponent(u)))};Editor.prototype.convertImageToDataUri=function(u,D){try{var K=!0,T=window.setTimeout(mxUtils.bind(this,function(){K=!1;D(Editor.svgBrokenImage.src)}),this.timeout);if(/(\\.svg)$/i.test(u))mxUtils.get(u,mxUtils.bind(this,function(Q){window.clearTimeout(T);K&&D(Editor.createSvgDataUri(Q.getText()))}),function(){window.clearTimeout(T);\nK&&D(Editor.svgBrokenImage.src)});else{var N=new Image;this.crossOriginImages&&(N.crossOrigin=\"anonymous\");N.onload=function(){window.clearTimeout(T);if(K)try{var Q=document.createElement(\"canvas\"),R=Q.getContext(\"2d\");Q.height=N.height;Q.width=N.width;R.drawImage(N,0,0);D(Q.toDataURL())}catch(Y){D(Editor.svgBrokenImage.src)}};N.onerror=function(){window.clearTimeout(T);K&&D(Editor.svgBrokenImage.src)};N.src=u}}catch(Q){D(Editor.svgBrokenImage.src)}};Editor.prototype.convertImages=function(u,D,K,", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "this.setPersistentToken(JSON.stringify(n),!n.remember));e();return}}catch(v){}f({message:mxResources.get(\"unknownError\")+\" (Code: \"+c.getStatus()+\")\"})}),f)};OneDriveClient.prototype.executeRequest=function(e,f,c){var m=mxUtils.bind(this,function(n){var v=!0,d=window.setTimeout(mxUtils.bind(this,function(){v=!1;c({code:App.ERROR_TIMEOUT,retry:m})}),this.ui.timeout);this.get(e,mxUtils.bind(this,function(g){window.clearTimeout(d);v&&(200<=g.getStatus()&&299>=g.getStatus()||404==g.getStatus()?(null==\nthis.user&&this.updateUser(this.emptyFn,this.emptyFn,!0),f(g)):n||401!==g.getStatus()&&400!==g.getStatus()?c(this.parseRequestText(g)):this.authenticate(function(){m(!0)},c,n))}),mxUtils.bind(this,function(g){window.clearTimeout(d);v&&c(g)}))});null==b||6E4>this.tokenExpiresOn-Date.now()?this.authenticate(function(){m(!0)},c):m(!1)};OneDriveClient.prototype.checkToken=function(e,f){null==b||null==this.tokenRefreshThread||6E4>this.tokenExpiresOn-Date.now()?this.authenticate(e,null!=f?f:this.emptyFn):", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "(q.parentNode.removeChild(q),q=null)});null!=X&&null!=W&&(/(\\.v(dx|sdx?))($|\\?)/i.test(W)||/(\\.vs(x|sx?))($|\\?)/i.test(W))?this.importVisio(X,function(K){D(K,\"text/xml\")},null,W):(new XMLHttpRequest).upload&&this.isRemoteFileFormat(J,W)&&null!=X?this.isExternalDataComms()?this.parseFile(X,mxUtils.bind(this,function(K){4==K.readyState&&(this.spinner.stop(),200<=K.status&&299>=K.status?D(K.responseText,\"text/xml\"):this.handleError({message:mxResources.get(413==K.status?\"drawingTooLarge\":\"invalidOrMissingFile\")},\nmxResources.get(\"errorLoadingFile\")))})):(this.spinner.stop(),this.showError(mxResources.get(\"error\"),mxResources.get(\"notInOffline\"))):D(J,F)}}));P.stopPropagation();P.preventDefault()})),mxEvent.addListener(y,\"dragleave\",function(P){y.style.cursor=\"\";y.style.backgroundColor=\"\";P.stopPropagation();P.preventDefault()}));I=I.cloneNode(!1);I.setAttribute(\"src\",Editor.editImage);I.setAttribute(\"title\",mxResources.get(\"edit\"));B.insertBefore(I,B.firstChild);mxEvent.addListener(I,\"click\",L);mxEvent.addListener(y,", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "b.setSelectionCells([F])}}for(F=0;F').src);ea.style.width=\"10px\";D.appendChild(ea);ea=document.createElement(\"div\");ea.style.backgroundColor=ba;ea.style.color=Y;ea.style.fontSize=\"9pt\";ea.style.padding=\n\"3px 7px\";ea.style.marginTop=\"8px\";ea.style.borderRadius=\"10px\";ea.style.maxWidth=\"100px\";ea.style.overflow=\"hidden\";ea.style.textOverflow=\"ellipsis\";ea.style.whiteSpace=\"nowrap\";mxUtils.write(ea,X);D.appendChild(ea);b.diagramContainer.appendChild(D)}else D=y[u].cursor;K=y[u].selection}if(!P){M=JSON.parse(M);J&&\"cursor\"!=M.type&&EditorUi.debug(\"P2PCollab: msg received\",[M]);if(null!=W){if(M.from==z||B[M.from]>=M.id){EditorUi.debug(\"P2PCollab: Dropped Message\",M,z,B[M.from]);return}B[M.from]=M.id}var X=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "\"25px\";btn.className=\"geColorBtn\";return btn}function Y(za,ta,ka,oa,sa,ya,wa){if(0d.length;H||v.push.apply(v,d);d=[];v.push(null);m.push(c);c=null;(H||l)&&this.stopDrawing();l&&2<=F&&this.startDrawing();mxEvent.consume(J)}}),L=new mxCell;L.edge=!0;var C=function(){var J=b.getCurrentCellStyle(L);J=mxUtils.getValue(b.currentVertexStyle,mxConstants.STYLE_STROKECOLOR,mxUtils.getValue(J,mxConstants.STYLE_STROKECOLOR,\"#000\"));\"default\"==", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "y.style.position=\"absolute\";y.style.width=\"640px\";y.style.top=\"260px\";y.style.textAlign=\"center\";y.style.fontSize=\"22px\";y.style.color=\"#a0c3ff\";mxUtils.write(y,mxResources.get(\"dragImagesHere\"));f.appendChild(y);var A={},B=null,I=null,O=null;e=function(E){\"true\"!=mxEvent.getSource(E).getAttribute(\"contentEditable\")&&null!=O&&(O(),O=null,mxEvent.consume(E))};mxEvent.addListener(x,\"mousedown\",e);mxEvent.addListener(x,\"pointerdown\",e);mxEvent.addListener(x,\"touchstart\",e);var t=new mxUrlConverter,z=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "this.menus.addPopupMenuEditItems=function(E,G,P){d.editor.graph.isSelectionEmpty()?B.apply(this,arguments):d.menus.addMenuItems(E,\"delete - cut copy copyAsImage - duplicate\".split(\" \"),null,P)}}d.actions.get(\"print\").funct=function(){d.showDialog((new PrintDialog(d)).container,360,null!=d.pages&&1','',isLocalStorage||mxClient.IS_CHROMEAPP)).container,340,isLocalStorage||mxClient.IS_CHROMEAPP?220:200,\n!0,!0):p(!1,l)};EditorUi.prototype.parseFile=function(d,g,k){k=null!=k?k:d.name;var l=new FileReader;l.onload=mxUtils.bind(this,function(){this.parseFileData(l.result,g,k)});l.readAsText(d)};EditorUi.prototype.parseFileData=function(d,g,k){var l=new XMLHttpRequest;l.open(\"POST\",OPEN_URL);l.setRequestHeader(\"Content-Type\",\"application/x-www-form-urlencoded\");l.onreadystatechange=function(){g(l)};l.send(\"format=xml&filename=\"+encodeURIComponent(k)+\"&data=\"+encodeURIComponent(d));try{EditorUi.logEvent({category:\"GLIFFY-IMPORT-FILE\",", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "\"&from=\"+q;break}q=z.background;\"png\"!=g&&\"pdf\"!=g&&\"svg\"!=g||!p?p||null!=q&&q!=mxConstants.NONE||(q=\"#ffffff\"):q=mxConstants.NONE;p={globalVars:z.getExportVariables()};A&&(p.grid={size:z.gridSize,steps:z.view.gridSteps,color:z.view.gridColor});Graph.translateDiagram&&(p.diagramLanguage=Graph.diagramLanguage);return new mxXmlRequest(EXPORT_URL,\"format=\"+g+C+E+\"&bg=\"+(null!=q?q:mxConstants.NONE)+\"&base64=\"+l+\"&embedXml=\"+B+\"&xml=\"+encodeURIComponent(k)+(null!=d?\"&filename=\"+encodeURIComponent(d):\"\")+\n\"&extras=\"+encodeURIComponent(JSON.stringify(p))+(null!=x?\"&scale=\"+x:\"\")+(null!=y?\"&border=\"+y:\"\")+(O&&isFinite(O)?\"&w=\"+O:\"\")+(t&&isFinite(t)?\"&h=\"+t:\"\"))};EditorUi.prototype.setMode=function(d,g){this.mode=d};EditorUi.prototype.loadDescriptor=function(d,g,k){var l=window.location.hash,p=mxUtils.bind(this,function(q){var x=null!=d.data?d.data:\"\";null!=q&&0W?K():U=setTimeout(K,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "return u};Graph.getFontUrl=function(u,D){u=Graph.customFontElements[u.toLowerCase()];null!=u&&(D=u.url);return D};Graph.processFontAttributes=function(u){u=u.getElementsByTagName(\"*\");for(var D=0;Dthis.status)if(\"txt\"==g)k(this.response);else{var A=new FileReader;A.readAsDataURL(this.response);A.onloadend=function(B){var I=new Image;I.onload=\nfunction(){try{var O=I.width,t=I.height;if(0==O&&0==t){var z=A.result,L=z.indexOf(\",\"),C=decodeURIComponent(escape(atob(z.substring(L+1)))),E=mxUtils.parseXml(C).getElementsByTagName(\"svg\");0N.offsetTop-N.offsetHeight/2?\"70px\":\"10px\");else{for(var da=S.firstChild;null!=da;){var ca=da.nextSibling;", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "urlParams.edge;Graph.prototype.hiddenTags=null;Graph.prototype.defaultMathEnabled=!1;var A=Graph.prototype.init;Graph.prototype.init=function(){function u(N){D=N}A.apply(this,arguments);this.hiddenTags=[];window.mxFreehand&&(this.freehand=new mxFreehand(this));var D=null;mxEvent.addListener(this.container,\"mouseenter\",u);mxEvent.addListener(this.container,\"mousemove\",u);mxEvent.addListener(this.container,\"mouseleave\",function(N){D=null});this.isMouseInsertPoint=function(){return null!=D};var K=this.getInsertPoint;\nthis.getInsertPoint=function(){return null!=D?this.getPointForEvent(D):K.apply(this,arguments)};var T=this.layoutManager.getLayout;this.layoutManager.getLayout=function(N){var Q=this.graph.getCellStyle(N);if(null!=Q&&\"rack\"==Q.childLayout){var R=new mxStackLayout(this.graph,!1);R.gridSize=null!=Q.rackUnitSize?parseFloat(Q.rackUnitSize):\"undefined\"!==typeof mxRackContainer?mxRackContainer.unitSize:20;R.marginLeft=Q.marginLeft||0;R.marginRight=Q.marginRight||0;R.marginTop=Q.marginTop||0;R.marginBottom=\nQ.marginBottom||0;R.allowGaps=Q.allowGaps||0;R.horizontal=\"1\"==mxUtils.getValue(Q,\"horizontalRack\",\"0\");R.resizeParent=!1;R.fill=!0;return R}return T.apply(this,arguments)};this.updateGlobalUrlVariables()};var B=Graph.prototype.postProcessCellStyle;Graph.prototype.postProcessCellStyle=function(u,D){return Graph.processFontStyle(B.apply(this,arguments))};var I=mxSvgCanvas2D.prototype.updateTextNodes;mxSvgCanvas2D.prototype.updateTextNodes=function(u,D,K,T,N,Q,R,Y,ba,ea,Z){I.apply(this,arguments);Graph.processFontAttributes(Z)};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "E;var D=y(\".odPreview\"),K=y(\"#odFiles\");b=function(N,Q){Q=Q||document;return Q.querySelectorAll(N)}(\".odCatListTitle\");for(E=0;Eq.length){A.view.validate();var ca=new mxFastOrganicLayout(A);ca.forceConstant=3*W;ca.disableEdgeStyle=!1;ca.resetEdges=!1;var la=ca.isVertexIgnored;ca.isVertexIgnored=function(ia){return la.apply(this,arguments)||0>mxUtils.indexOf(q,\nia)};this.executeLayout(function(){ca.execute(A.getDefaultParent());ya()},!0,u);u=null}}this.hideDialog()}finally{A.model.endUpdate()}null!=u&&u()}}catch(ia){this.handleError(ia)}};EditorUi.prototype.getSearch=function(d){var g=\"\";if(\"1\"!=urlParams.offline&&\"1\"!=urlParams.demo&&null!=d&&0mxUtils.indexOf(d,l)&&null!=urlParams[l]&&(g+=k+l+\"=\"+urlParams[l],k=\"&\")}else g=window.location.search;return g};EditorUi.prototype.getUrl=function(d){d=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "u.substring(0,29)||\"https://fonts.gstatic.com/\"===u.substring(0,26)};Editor.prototype.createImageUrlConverter=function(){var u=new mxUrlConverter;u.updateBaseUrl();var D=u.convert,K=this;u.convert=function(T){if(null!=T){var N=\"http://\"==T.substring(0,7)||\"https://\"==T.substring(0,8);N&&!navigator.onLine?T=Editor.svgBrokenImage.src:!N||T.substring(0,u.baseUrl.length)==u.baseUrl||K.crossOriginImages&&K.isCorsEnabledForUrl(T)?\"chrome-extension://\"==T.substring(0,19)||mxClient.IS_CHROMEAPP||(T=D.apply(this,\narguments)):T=PROXY_URL+\"?url=\"+encodeURIComponent(T)}return T};return u};Editor.createSvgDataUri=function(u){return\"data:image/svg+xml;base64,\"+btoa(unescape(encodeURIComponent(u)))};Editor.prototype.convertImageToDataUri=function(u,D){try{var K=!0,T=window.setTimeout(mxUtils.bind(this,function(){K=!1;D(Editor.svgBrokenImage.src)}),this.timeout);if(/(\\.svg)$/i.test(u))mxUtils.get(u,mxUtils.bind(this,function(Q){window.clearTimeout(T);K&&D(Editor.createSvgDataUri(Q.getText()))}),function(){window.clearTimeout(T);", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "u&&K[T].getAttribute(\"data-font-src\")!=D&&K[T].setAttribute(\"data-font-src\",D)}};var t=Graph.prototype.isFastZoomEnabled;Graph.prototype.isFastZoomEnabled=function(){return t.apply(this,arguments)&&(!this.shadowVisible||!mxClient.IS_SF)};Graph.prototype.updateGlobalUrlVariables=function(){this.globalVars=Editor.globalVars;if(null!=urlParams.vars)try{this.globalVars=null!=this.globalVars?mxUtils.clone(this.globalVars):{};var u=JSON.parse(decodeURIComponent(urlParams.vars));if(null!=u)for(var D in u)this.globalVars[D]=\nu[D]}catch(K){null!=window.console&&console.log(\"Error in vars URL parameter: \"+K)}};Graph.prototype.getExportVariables=function(){return null!=this.globalVars?mxUtils.clone(this.globalVars):{}};var z=Graph.prototype.getGlobalVariable;Graph.prototype.getGlobalVariable=function(u){var D=z.apply(this,arguments);null==D&&null!=this.globalVars&&(D=this.globalVars[u]);return D};Graph.prototype.getDefaultStylesheet=function(){if(null==this.defaultStylesheet){var u=this.themes[\"default-style2\"];this.defaultStylesheet=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "2)?O.substring(45,O.lastIndexOf(\"%26ex\")):O.substring(2);this.showError(g,x,mxResources.get(\"openInNewWindow\"),mxUtils.bind(this,function(){this.editor.graph.openLink(\"https://drive.google.com/open?id=\"+O);this.handleError(d,g,k,l,p)}),I,mxResources.get(\"changeUser\"),mxUtils.bind(this,function(){function z(){G.innerHTML=\"\";for(var P=0;P\");J.setAttribute(\"disabled\",\"disabled\");G.appendChild(J)}J=document.createElement(\"option\");mxUtils.write(J,mxResources.get(\"addAccount\"));J.value=L.length;G.appendChild(J)}var L=this.drive.getUsersList(),C=document.createElement(\"div\"),E=document.createElement(\"span\");E.style.marginTop=\"6px\";mxUtils.write(E,mxResources.get(\"changeUser\")+\": \");C.appendChild(E);var G=document.createElement(\"select\");G.style.width=\"200px\";z();mxEvent.addListener(G,\"change\",mxUtils.bind(this,", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "null,G)};var A=Menus.prototype.addPopupMenuEditItems;Menus.prototype.addPopupMenuEditItems=function(C,E,G){A.apply(this,arguments);this.editorUi.editor.graph.isSelectionEmpty()&&this.addMenuItems(C,[\"copyAsImage\"],null,G)};EditorUi.prototype.toggleFormatPanel=function(C){null!=this.formatWindow?this.formatWindow.window.setVisible(null!=C?C:!this.formatWindow.window.isVisible()):b(this)};DiagramFormatPanel.prototype.isMathOptionVisible=function(){return!0};var B=EditorUi.prototype.destroy;EditorUi.prototype.destroy=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "\"stencil(\"+I+\")\",[A])}catch(z){throw z;}finally{y.getModel().endUpdate()}O&&(y.setSelectionCell(A),y.scrollCellToVisible(A))}};f=mxUtils.button(mxResources.get(\"preview\"),function(){x(l,p,!1)});f.className=\"geBtn\";g.appendChild(f);f=mxUtils.button(mxResources.get(\"apply\"),function(){x(b.editor.graph,e,!0)});f.className=\"geBtn gePrimaryBtn\";g.appendChild(f);b.editor.cancelFirst||g.appendChild(m);d.appendChild(g);v.appendChild(d);n.appendChild(v);this.container=n},CustomDialog=function(b,e,f,c,m,n,", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "m=P.name;v=\"\";O(null,!0)})));k.appendChild(F)})(E[G],G)}100==E.length&&(k.appendChild(A),B=function(){k.scrollTop>=k.scrollHeight-k.offsetHeight&&C()},mxEvent.addListener(k,\"scroll\",B))}),y)});t()};GitHubClient.prototype.logout=function(){this.clearPersistentToken();this.setUser(null);b=null}})();TrelloFile=function(b,e,f){DrawioFile.call(this,b,e);this.meta=f;this.saveNeededCounter=0};mxUtils.extend(TrelloFile,DrawioFile);TrelloFile.prototype.getHash=function(){return\"T\"+encodeURIComponent(this.meta.compoundId)};TrelloFile.prototype.getMode=function(){return App.MODE_TRELLO};TrelloFile.prototype.isAutosave=function(){return!0};TrelloFile.prototype.getTitle=function(){return this.meta.name};TrelloFile.prototype.isRenamable=function(){return!1};TrelloFile.prototype.getSize=function(){return this.meta.bytes};", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "mxDualRuler.prototype.setUnit=function(b){this.vRuler.setUnit(b);this.hRuler.setUnit(b)};mxDualRuler.prototype.setStyle=function(b){this.vRuler.setStyle(b);this.hRuler.setStyle(b)};mxDualRuler.prototype.destroy=function(){this.vRuler.destroy();this.hRuler.destroy();this.ui.refresh=this.editorUiRefresh;mxGuide.prototype.move=this.origGuideMove;mxGuide.prototype.destroy=this.origGuideDestroy;this.ui.getDiagramContainerOffset=this.editorUiGetDiagContOffset};function mxFreehand(b){var e=null!=b.view&&null!=b.view.canvas?b.view.canvas.ownerSVGElement:null;if(null!=b.container&&null!=e){b.addListener(mxEvent.ESCAPE,mxUtils.bind(this,function(){this.stopDrawing()}));var f=mxFreehand.prototype.NORMAL_SMOOTHING,c=null,m=[],n,v=[],d,g=!1,k=!0,l=!0,p=!0,q=!0,x=[],y=!1,A=!0,B=!1,I={size:12,thinning:.5,smoothing:.5,streamline:.5,start:{taper:0,cap:!0},end:{taper:0,cap:!0}},O=!1;this.setClosedPath=function(J){g=J};this.setAutoClose=function(J){k=J};this.setAutoInsert=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "mxDualRuler.prototype.setUnit=function(b){this.vRuler.setUnit(b);this.hRuler.setUnit(b)};mxDualRuler.prototype.setStyle=function(b){this.vRuler.setStyle(b);this.hRuler.setStyle(b)};mxDualRuler.prototype.destroy=function(){this.vRuler.destroy();this.hRuler.destroy();this.ui.refresh=this.editorUiRefresh;mxGuide.prototype.move=this.origGuideMove;mxGuide.prototype.destroy=this.origGuideDestroy;this.ui.getDiagramContainerOffset=this.editorUiGetDiagContOffset};function mxFreehand(b){var e=null!=b.view&&null!=b.view.canvas?b.view.canvas.ownerSVGElement:null;if(null!=b.container&&null!=e){b.addListener(mxEvent.ESCAPE,mxUtils.bind(this,function(){this.stopDrawing()}));var f=mxFreehand.prototype.NORMAL_SMOOTHING,c=null,m=[],n,v=[],d,g=!1,k=!0,l=!0,p=!0,q=!0,x=[],y=!1,A=!0,B=!1,I={size:12,thinning:.5,smoothing:.5,streamline:.5,start:{taper:0,cap:!0},end:{taper:0,cap:!0}},O=!1;this.setClosedPath=function(J){g=J};this.setAutoClose=function(J){k=J};this.setAutoInsert=", "label": 1, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "Graph.prototype.selectUnlockedLayer=function(){if(null==this.defaultParent){var u=this.model.getChildCount(this.model.root),D=0;do var K=this.model.getChildAt(this.model.root,D);while(D++ current) {\n var message = $.sprintf(PMA_messages['strNewerVersion'], data['version'], data['date']);\n if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {\n /* Security update */\n klass = 'error';\n } else {\n klass = 'notice';\n }\n $('#maincontainer').after('
    ' + message + '
    ');\n }\n if (latest == current) {\n version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';\n }\n $('#li_pma_version').append(version_information_message);\n}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " var formatValue = function (name, value) {\n if (name == 'user_host') {\n return value.replace(/(\\[.*?\\])+/g, '');\n }\n return value;\n };", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " formatItem: function(data) {\n var s = data[options.nameKey];\n\n if (options.descKey) {\n s += \" (\" + data[options.descKey] + \")\";\n }\n\n return s;\n },", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": "\t\tisit = function(sel, match, expect) {\n\t\t\tequal( jQuery( sel ).is( match ), expect, \"jQuery( \" + sel + \" ).is( \" + match + \" )\" );\n\t\t};", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " this.switch_task = function(task)\n {\n if (this.task === task && task != 'mail')\n return;\n\n var url = this.get_task_url(task);\n\n if (task == 'mail')\n url += '&_mbox=INBOX';\n else if (task == 'logout' && !this.env.server_error) {\n url += '&_token=' + this.env.request_token;\n this.clear_compose_data();\n }\n\n this.redirect(url);\n };", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _cid: this.contact_list.get_selection().join(',') });\n }\n break;\n\n case 'upload-photo':\n this.upload_contact_photo(props || this.gui_objects.uploadform);\n break;\n\n case 'delete-photo':\n this.replace_contact_photo('-del-');\n break;\n\n // user settings commands\n case 'preferences':\n case 'identities':\n case 'responses':\n case 'folders':\n this.goto_url('settings/' + command);\n break;\n\n case 'undo':\n this.http_request('undo', '', this.display_message('', 'loading'));\n break;\n\n // unified command call (command name == function name)\n default:\n var func = command.replace(/-/g, '_');\n if (this[func] && typeof this[func] === 'function') {\n ret = this[func](props, obj, event);\n }\n break;\n }\n\n if (!aborted && this.triggerEvent('after'+command, props) === false)\n ret = false;\n this.triggerEvent('actionafter', { props:props, action:command, aborted:aborted });\n\n return ret === false ? false : obj ? false : true;\n };", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": "\taddFile:function(name,size,lastModified,loading){\n\t\tvar img=(loading)?OC.imagePath('core', 'loading.gif'):OC.imagePath('core', 'filetypes/file.png');\n\t\tvar html='';\n\t\tif(name.indexOf('.')!=-1){\n\t\t\tvar basename=name.substr(0,name.lastIndexOf('.'));\n\t\t\tvar extension=name.substr(name.lastIndexOf('.'));\n\t\t}else{\n\t\t\tvar basename=name;\n\t\t\tvar extension=false;\n\t\t}\n\t\thtml+='';\n\t\thtml+=''+basename\n\t\tif(extension){\n\t\t\thtml+=''+extension+'';\n\t\t}\n\t\thtml+='';\n\t\tif(size!='Pending'){\n\t\t\tsimpleSize=simpleFileSize(size);\n\t\t}else{\n\t\t\tsimpleSize='Pending';\n\t\t}\n\t\tsizeColor = Math.round(200-size/(1024*1024)*2);\n\t\tlastModifiedTime=Math.round(lastModified.getTime() / 1000);\n\t\tmodifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*14);\n\t\thtml+=''+simpleSize+'';\n\t\thtml+=''+relative_modified_date(lastModified.getTime() / 1000)+'';\n\t\thtml+='';\n\t\tFileList.insertElement(name,'file',$(html).attr('data-file',name));\n\t\tif(loading){\n\t\t\t$('tr').filterAttr('data-file',name).data('loading',true);\n\t\t}else{\n\t\t\t$('tr').filterAttr('data-file',name).find('td.filename').draggable(dragOptions);\n\t\t}\n\t},", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " setViewTitle: function(date, view, data)\n {\n switch (view) {\n case 'day':\n return this.setTitle(date.toString('D'));\n\n case 'week':\n var dates = this.viewDates(date, view);\n return this.setTitle(dates[0].toString(Kronolith.conf.date_format) + ' - ' + dates[1].toString(Kronolith.conf.date_format));\n\n case 'month':\n return this.setTitle(date.toString('MMMM yyyy'));\n\n case 'year':\n return this.setTitle(date.toString('yyyy'));\n\n case 'agenda':\n var dates = this.viewDates(date, view);\n return this.setTitle(Kronolith.text.agenda + ' ' + dates[0].toString(Kronolith.conf.date_format) + ' - ' + dates[1].toString(Kronolith.conf.date_format));\n\n case 'search':\n return this.setTitle(Kronolith.text.searching.interpolate({ term: data }));\n }\n },", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": "\t_addFiles: function(files) {\n\t\tvar self = this, file_html, html = '';\n\n\t\tfile_html = '
  • ' +\n\t\t\t'
    ' +\n\t\t\t\t'
    {ext}
    ' +\n\t\t\t'
    ' +\n\t\t\t'
    ' +\n\t\t\t\t'
    ' +\n\t\t\t\t'{percent} ' +\n\t\t\t'
    ' +\n\t\t\t'
    ' +\n\t\t\t\t'{name} ' +\n\t\t\t'
    ' +\n\t\t\t'
    ' +\n\t\t\t\t'
    ' +\n\t\t\t'
    ' +\n\t\t\t'
    {size}
    ' +\n\t\t\t'
    ' +\n\t\t'
  • ';\n\n\t\tif (plupload.typeOf(files) !== 'array') {\n\t\t\tfiles = [files];\n\t\t}\n\n\t\t$.each(files, function(i, file) {\n\t\t\tvar ext = o.core.utils.Mime.getFileExtension(file.name) || 'none';\n\n\t\t\thtml += file_html.replace(/\\{(\\w+)\\}/g, function($0, $1) {\n\t\t\t\tswitch ($1) {\n\t\t\t\t\tcase 'thumb_width':\n\t\t\t\t\tcase 'thumb_height':\n\t\t\t\t\t\treturn self.options[$1];\n\n\t\t\t\t\tcase 'size':\n\t\t\t\t\t\treturn plupload.formatSize(file.size);\n\n\t\t\t\t\tcase 'ext':\n\t\t\t\t\t\treturn ext;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn file[$1] || '';\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tself.filelist.append(html);\n\t},", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-434", "cwe_name": "Unrestricted Upload of File with Dangerous Type", "description": "The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.", "url": "https://cwe.mitre.org/data/definitions/434.html", "label_name": "vulnerable"} {"code": "return returnValue;}},uploadifyUpload:function(ID){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').startFileUpload(ID,false);});},uploadifyCancel:function(ID){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').cancelFileUpload(ID,true,false);});},uploadifyClearQueue:function(){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').clearFileUploadQueue(false);});}})})(jQuery);", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "return returnValue;}},uploadifyUpload:function(ID){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').startFileUpload(ID,false);});},uploadifyCancel:function(ID){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').cancelFileUpload(ID,true,false);});},uploadifyClearQueue:function(){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').clearFileUploadQueue(false);});}})})(jQuery);", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " function restoreOldNodeModules () {\n if (!movedDestAway) return\n return readdir(path.join(delpath, 'node_modules')).catch(() => []).then((modules) => {\n if (!modules.length) return\n return correctMkdir(path.join(pkg.realpath, 'node_modules')).then(() => Bluebird.map(modules, (file) => {\n const from = path.join(delpath, 'node_modules', file)\n const to = path.join(pkg.realpath, 'node_modules', file)\n return move(from, to, moveOpts)\n }))\n })\n }", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-732", "cwe_name": "Incorrect Permission Assignment for Critical Resource", "description": "The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.", "url": "https://cwe.mitre.org/data/definitions/732.html", "label_name": "vulnerable"} {"code": "\t\thtml: function (token, attrs, content) {\n\t\t\tvar size = $.inArray(attrs.defaultattr, mybbCmd.fsStr) + 1;\n\t\t\tif (!isNaN(attrs.defaultattr)) {\n\t\t\t\tsize = attrs.defaultattr;\n\t\t\t\tif (size > 7)\n\t\t\t\t\tsize = 7;\n\t\t\t\tif (size < 1)\n\t\t\t\t\tsize = 1;\n\t\t\t}\n\t\t\tif (size < 0) {\n\t\t\t\tsize = 0;\n\t\t\t}\n\t\t\treturn '' + content + '';\n\t\t}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": "SendStream.prototype.pipe = function(res){\n var self = this\n , args = arguments\n , root = this._root;\n\n // references\n this.res = res;\n\n // decode the path\n var path = utils.decode(this.path)\n if (path === -1) return this.error(400)\n\n // null byte(s)\n if (~path.indexOf('\\0')) return this.error(400);\n\n var parts\n if (root !== null) {\n // join / normalize from optional root dir\n path = normalize(join(root, path))\n root = normalize(root)\n\n // malicious path\n if (path.substr(0, root.length) !== root) {\n debug('malicious path \"%s\"', path)\n return this.error(403)\n }\n\n // explode path parts\n parts = path.substr(root.length + 1).split(sep)\n } else {\n // \"..\" is malicious without \"root\"\n if (upPathRegexp.test(path)) {\n debug('malicious path \"%s\"', path)\n return this.error(403)\n }\n\n // explode path parts\n parts = normalize(path).split(sep)\n\n // resolve the path\n path = resolve(path)\n }\n\n // dotfile handling\n if (containsDotFile(parts)) {\n var access = this._dotfiles\n\n // legacy support\n if (access === undefined) {\n access = parts[parts.length - 1][0] === '.'\n ? (this._hidden ? 'allow' : 'ignore')\n : 'allow'\n }\n\n debug('%s dotfile \"%s\"', access, path)\n switch (access) {\n case 'allow':\n break\n case 'deny':\n return this.error(403)\n case 'ignore':\n default:\n return this.error(404)\n }\n }\n\n // index file support\n if (this._index.length && this.path[this.path.length - 1] === '/') {\n this.sendIndex(path);\n return res;\n }\n\n this.sendFile(path);\n return res;\n};", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "exports.expressCreateServer = function (hook_name, args, cb) {\n args.app.get('/tests/frontend/specs_list.js', function(req, res){\n\n async.parallel({\n coreSpecs: function(callback){\n exports.getCoreTests(callback);\n },\n pluginSpecs: function(callback){\n exports.getPluginTests(callback);\n }\n },\n function(err, results){\n var files = results.coreSpecs; // push the core specs to a file object\n files = files.concat(results.pluginSpecs); // add the plugin Specs to the core specs\n console.debug(\"Sent browser the following test specs:\", files.sort());\n res.send(\"var specs_list = \" + JSON.stringify(files.sort()) + \";\\n\");\n });\n\n });\n\n var url2FilePath = function(url){\n var subPath = url.substr(\"/tests/frontend\".length);\n if (subPath == \"\"){\n subPath = \"index.html\"\n }\n subPath = subPath.split(\"?\")[0];\n\n var filePath = path.normalize(npm.root + \"/../tests/frontend/\")\n filePath += subPath.replace(\"..\", \"\");\n return filePath;\n }\n\n args.app.get('/tests/frontend/specs/*', function (req, res) {\n var specFilePath = url2FilePath(req.url);\n var specFileName = path.basename(specFilePath);\n\n fs.readFile(specFilePath, function(err, content){\n if(err){ return res.send(500); }\n \n content = \"describe(\" + JSON.stringify(specFileName) + \", function(){ \" + content + \" });\";\n\n res.send(content);\n }); \n });\n\n args.app.get('/tests/frontend/*', function (req, res) {\n var filePath = url2FilePath(req.url);\n res.sendfile(filePath);\n });\n\n args.app.get('/tests/frontend', function (req, res) {\n res.redirect('/tests/frontend/');\n }); \n}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " function complete() {\n if (that.hoverState != 'in') $tip.detach()\n that.$element\n .removeAttr('aria-describedby')\n .trigger('hidden.bs.' + that.type)\n callback && callback()\n }", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t_create: function() {\n\n\t\tif ( this.options.helper === \"original\" ) {\n\t\t\tthis._setPositionRelative();\n\t\t}\n\t\tif (this.options.addClasses){\n\t\t\tthis.element.addClass(\"ui-draggable\");\n\t\t}\n\t\tif (this.options.disabled){\n\t\t\tthis.element.addClass(\"ui-draggable-disabled\");\n\t\t}\n\t\tthis._setHandleClassName();\n\n\t\tthis._mouseInit();\n\t},", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\t\t\tupdate: function(container, p) {\n\n\t\t\t\t\t// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that\n\t\t\t\t\t// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified\n\t\t\t\t\tif(className && !o.forcePlaceholderSize) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item\n\t\t\t\t\tif(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css(\"paddingTop\")||0, 10) - parseInt(that.currentItem.css(\"paddingBottom\")||0, 10)); }\n\t\t\t\t\tif(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css(\"paddingLeft\")||0, 10) - parseInt(that.currentItem.css(\"paddingRight\")||0, 10)); }\n\t\t\t\t}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "function Id(a,b){var c=a.split(\"_\");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function Jd(a,b,c){var d={mm:b?\"\u043c\u0438\u043d\u0443\u0442\u0430_\u043c\u0438\u043d\u0443\u0442\u044b_\u043c\u0438\u043d\u0443\u0442\":\"\u043c\u0438\u043d\u0443\u0442\u0443_\u043c\u0438\u043d\u0443\u0442\u044b_\u043c\u0438\u043d\u0443\u0442\",hh:\"\u0447\u0430\u0441_\u0447\u0430\u0441\u0430_\u0447\u0430\u0441\u043e\u0432\",dd:\"\u0434\u0435\u043d\u044c_\u0434\u043d\u044f_\u0434\u043d\u0435\u0439\",MM:\"\u043c\u0435\u0441\u044f\u0446_\u043c\u0435\u0441\u044f\u0446\u0430_\u043c\u0435\u0441\u044f\u0446\u0435\u0432\",yy:\"\u0433\u043e\u0434_\u0433\u043e\u0434\u0430_\u043b\u0435\u0442\"};return\"m\"===c?b?\"\u043c\u0438\u043d\u0443\u0442\u0430\":\"\u043c\u0438\u043d\u0443\u0442\u0443\":a+\" \"+Id(d[c],+a)}function Kd(a){return a>1&&5>a}function Ld(a,b,c,d){var e=a+\" \";switch(c){case\"s\":return b||d?\"p\u00e1r sek\u00fand\":\"p\u00e1r sekundami\";case\"m\":return b?\"min\u00fata\":d?\"min\u00fatu\":\"min\u00fatou\";case\"mm\":return b||d?e+(Kd(a)?\"min\u00faty\":\"min\u00fat\"):e+\"min\u00fatami\";break;case\"h\":return b?\"hodina\":d?\"hodinu\":\"hodinou\";case\"hh\":return b||d?e+(Kd(a)?\"hodiny\":\"hod\u00edn\"):e+\"hodinami\";break;case\"d\":return b||d?\"de\u0148\":\"d\u0148om\";case\"dd\":return b||d?e+(Kd(a)?\"dni\":\"dn\u00ed\"):e+\"d\u0148ami\";break;case\"M\":return b||d?\"mesiac\":\"mesiacom\";case\"MM\":return b||d?e+(Kd(a)?\"mesiace\":\"mesiacov\"):e+\"mesiacmi\";break;case\"y\":return b||d?\"rok\":\"rokom\";case\"yy\":return b||d?e+(Kd(a)?\"roky\":\"rokov\"):e+\"rokmi\"}}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "function Zc(a,b){var c=a.split(\"_\");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function $c(a,b,c){var d={mm:b?\"\u0445\u0432\u0456\u043b\u0456\u043d\u0430_\u0445\u0432\u0456\u043b\u0456\u043d\u044b_\u0445\u0432\u0456\u043b\u0456\u043d\":\"\u0445\u0432\u0456\u043b\u0456\u043d\u0443_\u0445\u0432\u0456\u043b\u0456\u043d\u044b_\u0445\u0432\u0456\u043b\u0456\u043d\",hh:b?\"\u0433\u0430\u0434\u0437\u0456\u043d\u0430_\u0433\u0430\u0434\u0437\u0456\u043d\u044b_\u0433\u0430\u0434\u0437\u0456\u043d\":\"\u0433\u0430\u0434\u0437\u0456\u043d\u0443_\u0433\u0430\u0434\u0437\u0456\u043d\u044b_\u0433\u0430\u0434\u0437\u0456\u043d\",dd:\"\u0434\u0437\u0435\u043d\u044c_\u0434\u043d\u0456_\u0434\u0437\u0451\u043d\",MM:\"\u043c\u0435\u0441\u044f\u0446_\u043c\u0435\u0441\u044f\u0446\u044b_\u043c\u0435\u0441\u044f\u0446\u0430\u045e\",yy:\"\u0433\u043e\u0434_\u0433\u0430\u0434\u044b_\u0433\u0430\u0434\u043e\u045e\"};return\"m\"===c?b?\"\u0445\u0432\u0456\u043b\u0456\u043d\u0430\":\"\u0445\u0432\u0456\u043b\u0456\u043d\u0443\":\"h\"===c?b?\"\u0433\u0430\u0434\u0437\u0456\u043d\u0430\":\"\u0433\u0430\u0434\u0437\u0456\u043d\u0443\":a+\" \"+Zc(d[c],+a)}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "function jd(a,b,c,d){var e={s:[\"m\u00f5ne sekundi\",\"m\u00f5ni sekund\",\"paar sekundit\"],m:[\"\u00fche minuti\",\"\u00fcks minut\"],mm:[a+\" minuti\",a+\" minutit\"],h:[\"\u00fche tunni\",\"tund aega\",\"\u00fcks tund\"],hh:[a+\" tunni\",a+\" tundi\"],d:[\"\u00fche p\u00e4eva\",\"\u00fcks p\u00e4ev\"],M:[\"kuu aja\",\"kuu aega\",\"\u00fcks kuu\"],MM:[a+\" kuu\",a+\" kuud\"],y:[\"\u00fche aasta\",\"aasta\",\"\u00fcks aasta\"],yy:[a+\" aasta\",a+\" aastat\"]};return b?e[c][2]?e[c][2]:e[c][1]:d?e[c][0]:e[c][1]}function kd(a,b,c,d){var e=\"\";switch(c){case\"s\":return d?\"muutaman sekunnin\":\"muutama sekunti\";case\"m\":return d?\"minuutin\":\"minuutti\";case\"mm\":e=d?\"minuutin\":\"minuuttia\";break;case\"h\":return d?\"tunnin\":\"tunti\";case\"hh\":e=d?\"tunnin\":\"tuntia\";break;case\"d\":return d?\"p\u00e4iv\u00e4n\":\"p\u00e4iv\u00e4\";case\"dd\":e=d?\"p\u00e4iv\u00e4n\":\"p\u00e4iv\u00e4\u00e4\";break;case\"M\":return d?\"kuukauden\":\"kuukausi\";case\"MM\":e=d?\"kuukauden\":\"kuukautta\";break;case\"y\":return d?\"vuoden\":\"vuosi\";case\"yy\":e=d?\"vuoden\":\"vuotta\"}return e=ld(a,d)+\" \"+e}function ld(a,b){return 10>a?b?kg[a]:jg[a]:a}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "function jd(a,b,c,d){var e={s:[\"m\u00f5ne sekundi\",\"m\u00f5ni sekund\",\"paar sekundit\"],m:[\"\u00fche minuti\",\"\u00fcks minut\"],mm:[a+\" minuti\",a+\" minutit\"],h:[\"\u00fche tunni\",\"tund aega\",\"\u00fcks tund\"],hh:[a+\" tunni\",a+\" tundi\"],d:[\"\u00fche p\u00e4eva\",\"\u00fcks p\u00e4ev\"],M:[\"kuu aja\",\"kuu aega\",\"\u00fcks kuu\"],MM:[a+\" kuu\",a+\" kuud\"],y:[\"\u00fche aasta\",\"aasta\",\"\u00fcks aasta\"],yy:[a+\" aasta\",a+\" aastat\"]};return b?e[c][2]?e[c][2]:e[c][1]:d?e[c][0]:e[c][1]}function kd(a,b,c,d){var e=\"\";switch(c){case\"s\":return d?\"muutaman sekunnin\":\"muutama sekunti\";case\"m\":return d?\"minuutin\":\"minuutti\";case\"mm\":e=d?\"minuutin\":\"minuuttia\";break;case\"h\":return d?\"tunnin\":\"tunti\";case\"hh\":e=d?\"tunnin\":\"tuntia\";break;case\"d\":return d?\"p\u00e4iv\u00e4n\":\"p\u00e4iv\u00e4\";case\"dd\":e=d?\"p\u00e4iv\u00e4n\":\"p\u00e4iv\u00e4\u00e4\";break;case\"M\":return d?\"kuukauden\":\"kuukausi\";case\"MM\":e=d?\"kuukauden\":\"kuukautta\";break;case\"y\":return d?\"vuoden\":\"vuosi\";case\"yy\":e=d?\"vuoden\":\"vuotta\"}return e=ld(a,d)+\" \"+e}function ld(a,b){return 10>a?b?kg[a]:jg[a]:a}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "function Md(a,b,c,d){var e=a+\" \";switch(c){case\"s\":return b||d?\"nekaj sekund\":\"nekaj sekundami\";case\"m\":return b?\"ena minuta\":\"eno minuto\";case\"mm\":return e+=1===a?b?\"minuta\":\"minuto\":2===a?b||d?\"minuti\":\"minutama\":5>a?b||d?\"minute\":\"minutami\":b||d?\"minut\":\"minutami\";case\"h\":return b?\"ena ura\":\"eno uro\";case\"hh\":return e+=1===a?b?\"ura\":\"uro\":2===a?b||d?\"uri\":\"urama\":5>a?b||d?\"ure\":\"urami\":b||d?\"ur\":\"urami\";case\"d\":return b||d?\"en dan\":\"enim dnem\";case\"dd\":return e+=1===a?b||d?\"dan\":\"dnem\":2===a?b||d?\"dni\":\"dnevoma\":b||d?\"dni\":\"dnevi\";case\"M\":return b||d?\"en mesec\":\"enim mesecem\";case\"MM\":return e+=1===a?b||d?\"mesec\":\"mesecem\":2===a?b||d?\"meseca\":\"mesecema\":5>a?b||d?\"mesece\":\"meseci\":b||d?\"mesecev\":\"meseci\";case\"y\":return b||d?\"eno leto\":\"enim letom\";case\"yy\":return e+=1===a?b||d?\"leto\":\"letom\":2===a?b||d?\"leti\":\"letoma\":5>a?b||d?\"leta\":\"leti\":b||d?\"let\":\"leti\"}}function Nd(a){var b=a;return b=-1!==a.indexOf(\"jaj\")?b.slice(0,-3)+\"leS\":-1!==a.indexOf(\"jar\")?b.slice(0,-3)+\"waQ\":-1!==a.indexOf(\"DIS\")?b.slice(0,-3)+\"nem\":b+\" pIq\"}function Od(a){var b=a;return b=-1!==a.indexOf(\"jaj\")?b.slice(0,-3)+\"Hu\u2019\":-1!==a.indexOf(\"jar\")?b.slice(0,-3)+\"wen\":-1!==a.indexOf(\"DIS\")?b.slice(0,-3)+\"ben\":b+\" ret\"}function Pd(a,b,c,d){var e=Qd(a);switch(c){case\"mm\":return e+\" tup\";case\"hh\":return e+\" rep\";case\"dd\":return e+\" jaj\";case\"MM\":return e+\" jar\";case\"yy\":return e+\" DIS\"}}function Qd(a){var b=Math.floor(a%1e3/100),c=Math.floor(a%100/10),d=a%10,e=\"\";return b>0&&(e+=Sg[b]+\"vatlh\"),c>0&&(e+=(\"\"!==e?\" \":\"\")+Sg[c]+\"maH\"),d>0&&(e+=(\"\"!==e?\" \":\"\")+Sg[d]),\"\"===e?\"pagh\":e}function Rd(a,b,c,d){var e={s:[\"viensas secunds\",\"'iensas secunds\"],m:[\"'n m\u00edut\",\"'iens m\u00edut\"],mm:[a+\" m\u00eduts\",\"\"+a+\" m\u00eduts\"],h:[\"'n \u00feora\",\"'iensa \u00feora\"],hh:[a+\" \u00feoras\",\"\"+a+\" \u00feoras\"],d:[\"'n ziua\",\"'iensa ziua\"],dd:[a+\" ziuas\",\"\"+a+\" ziuas\"],M:[\"'n mes\",\"'iens mes\"],MM:[a+\" mesen\",\"\"+a+\" mesen\"],y:[\"'n ar\",\"'iens ar\"],yy:[a+\" ars\",\"\"+a+\" ars\"]};return d?e[c][0]:b?e[c][0]:e[c][1]}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "function Id(a,b){var c=a.split(\"_\");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function Jd(a,b,c){var d={mm:b?\"\u043c\u0438\u043d\u0443\u0442\u0430_\u043c\u0438\u043d\u0443\u0442\u044b_\u043c\u0438\u043d\u0443\u0442\":\"\u043c\u0438\u043d\u0443\u0442\u0443_\u043c\u0438\u043d\u0443\u0442\u044b_\u043c\u0438\u043d\u0443\u0442\",hh:\"\u0447\u0430\u0441_\u0447\u0430\u0441\u0430_\u0447\u0430\u0441\u043e\u0432\",dd:\"\u0434\u0435\u043d\u044c_\u0434\u043d\u044f_\u0434\u043d\u0435\u0439\",MM:\"\u043c\u0435\u0441\u044f\u0446_\u043c\u0435\u0441\u044f\u0446\u0430_\u043c\u0435\u0441\u044f\u0446\u0435\u0432\",yy:\"\u0433\u043e\u0434_\u0433\u043e\u0434\u0430_\u043b\u0435\u0442\"};return\"m\"===c?b?\"\u043c\u0438\u043d\u0443\u0442\u0430\":\"\u043c\u0438\u043d\u0443\u0442\u0443\":a+\" \"+Id(d[c],+a)}function Kd(a){return a>1&&5>a}function Ld(a,b,c,d){var e=a+\" \";switch(c){case\"s\":return b||d?\"p\u00e1r sek\u00fand\":\"p\u00e1r sekundami\";case\"m\":return b?\"min\u00fata\":d?\"min\u00fatu\":\"min\u00fatou\";case\"mm\":return b||d?e+(Kd(a)?\"min\u00faty\":\"min\u00fat\"):e+\"min\u00fatami\";break;case\"h\":return b?\"hodina\":d?\"hodinu\":\"hodinou\";case\"hh\":return b||d?e+(Kd(a)?\"hodiny\":\"hod\u00edn\"):e+\"hodinami\";break;case\"d\":return b||d?\"de\u0148\":\"d\u0148om\";case\"dd\":return b||d?e+(Kd(a)?\"dni\":\"dn\u00ed\"):e+\"d\u0148ami\";break;case\"M\":return b||d?\"mesiac\":\"mesiacom\";case\"MM\":return b||d?e+(Kd(a)?\"mesiace\":\"mesiacov\"):e+\"mesiacmi\";break;case\"y\":return b||d?\"rok\":\"rokom\";case\"yy\":return b||d?e+(Kd(a)?\"roky\":\"rokov\"):e+\"rokmi\"}}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "function md(a,b,c){var d=a+\" \";switch(c){case\"m\":return b?\"jedna minuta\":\"jedne minute\";case\"mm\":return d+=1===a?\"minuta\":2===a||3===a||4===a?\"minute\":\"minuta\";case\"h\":return b?\"jedan sat\":\"jednog sata\";case\"hh\":return d+=1===a?\"sat\":2===a||3===a||4===a?\"sata\":\"sati\";case\"dd\":return d+=1===a?\"dan\":\"dana\";case\"MM\":return d+=1===a?\"mjesec\":2===a||3===a||4===a?\"mjeseca\":\"mjeseci\";case\"yy\":return d+=1===a?\"godina\":2===a||3===a||4===a?\"godine\":\"godina\"}}function nd(a,b,c,d){var e=a;switch(c){case\"s\":return d||b?\"n\u00e9h\u00e1ny m\u00e1sodperc\":\"n\u00e9h\u00e1ny m\u00e1sodperce\";case\"m\":return\"egy\"+(d||b?\" perc\":\" perce\");case\"mm\":return e+(d||b?\" perc\":\" perce\");case\"h\":return\"egy\"+(d||b?\" \u00f3ra\":\" \u00f3r\u00e1ja\");case\"hh\":return e+(d||b?\" \u00f3ra\":\" \u00f3r\u00e1ja\");case\"d\":return\"egy\"+(d||b?\" nap\":\" napja\");case\"dd\":return e+(d||b?\" nap\":\" napja\");case\"M\":return\"egy\"+(d||b?\" h\u00f3nap\":\" h\u00f3napja\");case\"MM\":return e+(d||b?\" h\u00f3nap\":\" h\u00f3napja\");case\"y\":return\"egy\"+(d||b?\" \u00e9v\":\" \u00e9ve\");case\"yy\":return e+(d||b?\" \u00e9v\":\" \u00e9ve\")}return\"\"}function od(a){return(a?\"\":\"[m\u00falt] \")+\"[\"+ug[this.day()]+\"] LT[-kor]\"}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "renderer:\"foundation\"});a.ext.renderer.pageButton.foundation=function(b,j,q,r,g,k){var l=new a.Api(b),s=b.oClasses,h=b.oLanguage.oPaginate,t=b.oLanguage.oAria.paginate||{},e,f,p=function(a,m){var i,n,o,c,j=function(a){a.preventDefault();!d(a.currentTarget).hasClass(\"unavailable\")&&l.page()!=a.data.action&&l.page(a.data.action).draw(\"page\")};i=0;for(n=m.length;i\",{\"class\":s.sPageButton+\" \"+f,\"aria-controls\":b.sTableId,\"aria-label\":t[c],tabindex:b.iTabIndex,id:0===q&&\"string\"===typeof c?b.sTableId+\"_\"+c:null}).append(d(\"\",{href:\"#\"}).html(e)).appendTo(a),b.oApi._fnBindAction(o,{action:c},j))}};p(d(j).empty().html('
      ').children(\"ul\"),\nr)};return a});", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "b[c]:\"\"!==c?Q(c)(b):b}function pb(a){var b=a.oClasses,c=a.sTableId,d=a.oLanguage,e=a.oPreviousSearch,f=a.aanFeatures,g='',j=d.sSearch,j=j.match(/_INPUT_/)?j.replace(\"_INPUT_\",g):j+g,b=h(\"
      \",{id:!f.f?c+\"_filter\":null,\"class\":b.sFilter}).append(h(\"');\n\t\t\t// end help\n\t\t},", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\tthis.url = function(hash) {\n\t\tvar file = files[hash];\n\t\t\n\t\tif (!file || !file.read) {\n\t\t\treturn '';\n\t\t}\n\t\t\n\t\tif (file.url == '1') {\n\t\t\tthis.request({\n\t\t\t\tdata : {cmd : 'url', target : hash},\n\t\t\t\tpreventFail : true,\n\t\t\t\toptions: {async: false}\n\t\t\t})\n\t\t\t.done(function(data) {\n\t\t\t\tfile.url = data.url || '';\n\t\t\t})\n\t\t\t.fail(function() {\n\t\t\t\tfile.url = '';\n\t\t\t});\n\t\t}\n\t\t\n\t\tif (file.url) {\n\t\t\treturn file.url;\n\t\t}\n\t\t\n\t\tif (cwdOptions.url && file.hash.indexOf(self.cwd().volumeid) === 0) {\n\t\t\treturn cwdOptions.url + $.map(this.path2array(hash), function(n) { return encodeURIComponent(n); }).slice(1).join('/')\n\t\t}\n\n\t\tvar params = $.extend({}, this.customData, {\n\t\t\tcmd: 'file',\n\t\t\ttarget: file.hash\n\t\t});\n\t\tif (this.oldAPI) {\n\t\t\tparams.cmd = 'open';\n\t\t\tparams.current = file.phash;\n\t\t}\n\t\treturn this.options.url + (this.options.url.indexOf('?') === -1 ? '?' : '&') + $.param(params, true);\n\t}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\tsetcheck = function(perm) {\n\t\t\tvar _perm;\n\t\t\tfor (var i = 0; i < 3; i++){\n\t\t\t\t_perm = parseInt(perm.slice(i, i+1), 8);\n\t\t\t\t$(\"#\"+id+\"-read-\"+level[i]+'-perm').prop(\"checked\", false);\n\t\t\t\t$(\"#\"+id+\"-write-\"+level[i]+'-perm').prop(\"checked\", false);\n\t\t\t\t$(\"#\"+id+\"-execute-\"+level[i]+'-perm').prop(\"checked\", false);\n\t\t\t\tif ((_perm & 4) == 4) {\n\t\t\t\t\t$(\"#\"+id+\"-read-\"+level[i]+'-perm').prop(\"checked\", true);\n\t\t\t\t}\n\t\t\t\tif ((_perm & 2) == 2) {\n\t\t\t\t\t$(\"#\"+id+\"-write-\"+level[i]+'-perm').prop(\"checked\", true);\n\t\t\t\t}\n\t\t\t\tif ((_perm & 1) == 1) {\n\t\t\t\t\t$(\"#\"+id+\"-execute-\"+level[i]+'-perm').prop(\"checked\", true);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsetperm();\n\t\t},", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "elFinder.prototype.commands.home = function() {\n\tthis.title = 'Home';\n\tthis.alwaysEnabled = true;\n\tthis.updateOnSelect = false;\n\tthis.shortcuts = [{\n\t\tpattern : 'ctrl+home ctrl+shift+up',\n\t\tdescription : 'Home'\n\t}];\n\t\n\tthis.getstate = function() {\n\t\tvar root = this.fm.root(),\n\t\t\tcwd = this.fm.cwd().hash;\n\t\t\t\n\t\treturn root && cwd && root != cwd ? 0: -1;\n\t}\n\t\n\tthis.exec = function() {\n\t\treturn this.fm.exec('open', this.fm.root());\n\t}\n\t\n\n}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\t\tcustomColsNameBuild = function() {\n\t\t\t\tvar name = '',\n\t\t\t\tcustomColsName = '',\n\t\t\t\tcolumns = fm.options.uiOptions.cwd.listView.columns,\n\t\t\t\tnames = $.extend({}, msg, fm.options.uiOptions.cwd.listView.columnsCustomName);\n\t\t\t\tfor (var i = 0; i < columns.length; i++) {\n\t\t\t\t\tif (typeof names[columns[i]] !== 'undefined') {\n\t\t\t\t\t\tname = names[columns[i]];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tname = fm.i18n(columns[i]);\n\t\t\t\t\t}\n\t\t\t\t\tcustomColsName +=''+name+'';\n\t\t\t\t}\n\t\t\t\treturn customColsName;\n\t\t\t},", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\t\tfindSibling = function(subtree, dir) {\n\t\t\t\tvar node = subtree.children(':first'),\n\t\t\t\t\tinfo, compare;\n\n\t\t\t\tcompare = fm.naturalCompare;\n\t\t\t\twhile (node.length) {\n\t\t\t\t\tinfo = fm.file(fm.navId2Hash(node.children('[id]').attr('id')));\n\t\t\t\t\t\n\t\t\t\t\tif ((info = fm.file(fm.navId2Hash(node.children('[id]').attr('id')))) \n\t\t\t\t\t&& compare(dir.name, info.name) < 0) {\n\t\t\t\t\t\treturn node;\n\t\t\t\t\t}\n\t\t\t\t\tnode = node.next();\n\t\t\t\t}\n\t\t\t\treturn $('');\n\t\t\t},", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\tthis.destroy = function() {\n\t\tif (node && node[0].elfinder) {\n\t\t\tthis.autoSync('stop');\n\t\t\tthis.trigger('destroy').disable();\n\t\t\tlisteners = {};\n\t\t\tshortcuts = {};\n\t\t\t$(document).add(node).off('.'+this.namespace);\n\t\t\tself.trigger = function() { }\n\t\t\tnode.children().remove();\n\t\t\tnode.append(prevContent.contents()).removeClass(this.cssClass).attr('style', prevStyle);\n\t\t\tnode[0].elfinder = null;\n\t\t}\n\t}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "elFinder.prototype.commands.opendir = function() {\n\tthis.alwaysEnabled = true;\n\t\n\tthis.getstate = function() {\n\t\tvar sel = this.fm.selected(),\n\t\t\tcnt = sel.length,\n\t\t\tcwdWrapper;\n\t\tif (cnt !== 1) {\n\t\t\treturn -1;\n\t\t}\n\t\tcwdWrapper = this.fm.getUI('cwd').parent();\n\t\treturn cwdWrapper.hasClass('elfinder-search-result')? 0 : -1;\n\t}\n\t\n\tthis.exec = function(hashes) {\n\t\tvar fm = this.fm,\n\t\t\tdfrd = $.Deferred(),\n\t\t\tfiles = this.files(hashes),\n\t\t\tcnt = files.length,\n\t\t\thash, pcheck = null;\n\n\t\tif (!cnt || !files[0].phash) {\n\t\t\treturn dfrd.reject();\n\t\t}\n\n\t\thash = files[0].phash;\n\t\tif (!fm.file(hash)) {\n\t\t\t// parents check\n\t\t\tpcheck = fm.request({\n\t\t\t\tdata : {cmd : 'parents', target : hash},\n\t\t\t\tsyncOnFail : false\n\t\t\t});\n\t\t}\n\t\t// open folder\n\t\t$.when(pcheck)\n\t\t.done(function(data){\n\t\t\tfm.trigger('searchend', { noupdate: true });\n\t\t\tfm.request({\n\t\t\t\tdata : {cmd : 'open', target : hash},\n\t\t\t\tnotify : {type : 'open', cnt : 1, hideCnt : true},\n\t\t\t\tsyncOnFail : false\n\t\t\t});\n\t\t});\n\t\t\n\t\treturn dfrd;\n\t}\n\n}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\tthis.getUI = function(ui) {\n\t\treturn this.ui[ui] || node;\n\t}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\t\t\ttitle : this.i18n(opts.title || 'confirmReq'),\n\t\t\t\tbuttons : {},\n\t\t\t\tclose : function() { \n\t\t\t\t\t!complete && opts.cancel.callback();\n\t\t\t\t\t$(this).elfinderdialog('destroy');\n\t\t\t\t}\n\t\t\t},\n\t\t\tapply = this.i18n('apllyAll'),\n\t\t\tlabel, checkbox;\n\n\t\t\n\t\toptions.buttons[this.i18n(opts.accept.label)] = function() {\n\t\t\topts.accept.callback(!!(checkbox && checkbox.prop('checked')))\n\t\t\tcomplete = true;\n\t\t\t$(this).elfinderdialog('close')\n\t\t};\n\t\t\n\t\tif (opts.reject) {\n\t\t\toptions.buttons[this.i18n(opts.reject.label)] = function() {\n\t\t\t\topts.reject.callback(!!(checkbox && checkbox.prop('checked')))\n\t\t\t\tcomplete = true;\n\t\t\t\t$(this).elfinderdialog('close')\n\t\t\t};\n\t\t}\n\t\t\n\t\tif (opts.buttons && opts.buttons.length > 0) {\n\t\t\t$.each(opts.buttons, function(i, v){\n\t\t\t\toptions.buttons[self.i18n(v.label)] = function() {\n\t\t\t\t\tv.callback(!!(checkbox && checkbox.prop('checked')))\n\t\t\t\t\tcomplete = true;\n\t\t\t\t\t$(this).elfinderdialog('close');\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t\t\n\t\toptions.buttons[this.i18n(opts.cancel.label)] = function() {\n\t\t\t$(this).elfinderdialog('close')\n\t\t};\n\t\t\n\t\tif (opts.all) {\n\t\t\toptions.create = function() {\n\t\t\t\tvar base = $('
      ');\n\t\t\t\tcheckbox = $('');\n\t\t\t\t$(this).next().find('.ui-dialog-buttonset')\n\t\t\t\t\t.prepend(base.append($('').prepend(checkbox)));\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn this.dialog('' + this.i18n(opts.text), options);\n\t},", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\t\t\t\t\t\ttop : parseInt(nav.scrollTop())+'px',\n\t\t\t\t\t\t\tleft : ltr ? 'auto' : parseInt(nav.scrollLeft() + offset),\n\t\t\t\t\t\t\tright: ltr ? parseInt(nav.scrollLeft() - offset) * -1 : 'auto'\n\t\t\t\t\t\t});", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\tthis.trigger('resize', {width : node.width(), height : node.height()});\n\t}", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\t\t\t\t\t\t\t\t'targets' : fm.selected(),\n\t\t\t\t\t\t\t\t\t'x' : e.originalEvent.touches[0].pageX,\n\t\t\t\t\t\t\t\t\t'y' : e.originalEvent.touches[0].pageY\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}, 500));", "label": 0, "programming_language": "JavaScript", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "\t\t\t\t\t\tprotocol : $('\");\n } else {\n StringBuffer_append(res->outputbuffer, \"Error opening logfile: %s\", STRERROR);\n }\n } else {\n StringBuffer_append(res->outputbuffer,\n \"Cannot view logfile:
      \");\n if (! (Run.flags & Run_Log))\n StringBuffer_append(res->outputbuffer, \"Monit was started without logging\");\n else\n StringBuffer_append(res->outputbuffer, \"Monit uses syslog\");\n }\n do_foot(res);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "CURLcode Curl_auth_create_plain_message(struct Curl_easy *data,\n const char *userp,\n const char *passwdp,\n char **outptr, size_t *outlen)\n{\n CURLcode result;\n char *plainauth;\n size_t ulen;\n size_t plen;\n size_t plainlen;\n\n *outlen = 0;\n *outptr = NULL;\n ulen = strlen(userp);\n plen = strlen(passwdp);\n\n /* Compute binary message length. Check for overflows. */\n if((ulen > SIZE_T_MAX/4) || (plen > (SIZE_T_MAX/2 - 2)))\n return CURLE_OUT_OF_MEMORY;\n plainlen = 2 * ulen + plen + 2;\n\n plainauth = malloc(plainlen);\n if(!plainauth)\n return CURLE_OUT_OF_MEMORY;\n\n /* Calculate the reply */\n memcpy(plainauth, userp, ulen);\n plainauth[ulen] = '\\0';\n memcpy(plainauth + ulen + 1, userp, ulen);\n plainauth[2 * ulen + 1] = '\\0';\n memcpy(plainauth + 2 * ulen + 2, passwdp, plen);\n\n /* Base64 encode the reply */\n result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen);\n free(plainauth);\n\n return result;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "static void cil_reset_perm(struct cil_perm *perm)\n{\n\tcil_list_destroy(&perm->classperms, CIL_FALSE);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "int cil_build_ast(struct cil_db *db, struct cil_tree_node *parse_tree, struct cil_tree_node *ast)\n{\n\tint rc = SEPOL_ERR;\n\tstruct cil_args_build extra_args;\n\n\tif (db == NULL || parse_tree == NULL || ast == NULL) {\n\t\tgoto exit;\n\t}\n\n\textra_args.ast = ast;\n\textra_args.db = db;\n\textra_args.tunif = NULL;\n\textra_args.in = NULL;\n\textra_args.macro = NULL;\n\textra_args.optional = NULL;\n\textra_args.boolif = NULL;\n\n\trc = cil_tree_walk(parse_tree, __cil_build_ast_node_helper, __cil_build_ast_first_child_helper, __cil_build_ast_last_child_helper, &extra_args);\n\tif (rc != SEPOL_OK) {\n\t\tgoto exit;\n\t}\n\n\treturn SEPOL_OK;\n\nexit:\n\treturn rc;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)\n{\n EVP_CIPHER_CTX *ctx;\n const EVP_MD *digest;\n VALUE vpass, vsalt, viter, vdigest;\n unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;\n int iter;\n\n rb_scan_args(argc, argv, \"13\", &vpass, &vsalt, &viter, &vdigest);\n StringValue(vpass);\n if(!NIL_P(vsalt)){\n\tStringValue(vsalt);\n\tif(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)\n\t ossl_raise(eCipherError, \"salt must be an 8-octet string\");\n\tsalt = (unsigned char *)RSTRING_PTR(vsalt);\n }\n iter = NIL_P(viter) ? 2048 : NUM2INT(viter);\n digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);\n GetCipher(self, ctx);\n EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,\n\t\t (unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);\n if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)\n\tossl_raise(eCipherError, NULL);\n OPENSSL_cleanse(key, sizeof key);\n OPENSSL_cleanse(iv, sizeof iv);\n\n rb_ivar_set(self, id_key_set, Qtrue);\n\n return Qnil;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "safe"} {"code": "static int decode_font(ASS_Track *track)\n{\n unsigned char *p;\n unsigned char *q;\n size_t i;\n size_t size; // original size\n size_t dsize; // decoded size\n unsigned char *buf = 0;\n\n ass_msg(track->library, MSGL_V, \"Font: %d bytes encoded data\",\n track->parser_priv->fontdata_used);\n size = track->parser_priv->fontdata_used;\n if (size % 4 == 1) {\n ass_msg(track->library, MSGL_ERR, \"Bad encoded data size\");\n goto error_decode_font;\n }\n buf = malloc(size / 4 * 3 + FFMAX(size % 4, 1) - 1);\n if (!buf)\n goto error_decode_font;\n q = buf;\n for (i = 0, p = (unsigned char *) track->parser_priv->fontdata;\n i < size / 4; i++, p += 4) {\n q = decode_chars(p, q, 4);\n }\n if (size % 4 == 2) {\n q = decode_chars(p, q, 2);\n } else if (size % 4 == 3) {\n q = decode_chars(p, q, 3);\n }\n dsize = q - buf;\n assert(dsize == size / 4 * 3 + FFMAX(size % 4, 1) - 1);\n\n if (track->library->extract_fonts) {\n ass_add_font(track->library, track->parser_priv->fontname,\n (char *) buf, dsize);\n }\n\nerror_decode_font:\n free(buf);\n reset_embedded_font_parsing(track->parser_priv);\n return 0;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "static inline ut32 r_read_at_le32(const void *src, size_t offset) {\n\tif (!src) {\n\t\treturn UT32_MAX;\n\t}\n\tconst ut8 *s = (const ut8*)src + offset;\n\treturn r_read_le32 (s);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "static inline ut8 r_read_le8(const void *src) {\n\tif (!src) {\n\t\treturn UT8_MAX;\n\t}\n\treturn r_read_ble8 (src);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {\n\tOPCODE_DESC *opcode_desc;\n\tif (len < 2) {\n\t\treturn NULL;\n\t}\n\tut16 ins = (buf[1] << 8) | buf[0];\n\tint fail;\n\tchar *t;\n\n\t// initialize op struct\n\tmemset (op, 0, sizeof (RAnalOp));\n\top->ptr = UT64_MAX;\n\top->val = UT64_MAX;\n\top->jump = UT64_MAX;\n\tr_strbuf_init (&op->esil);\n\n\t// process opcode\n\tfor (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {\n\t\tif ((ins & opcode_desc->mask) == opcode_desc->selector) {\n\t\t\tfail = 0;\n\n\t\t\t// copy default cycles/size values\n\t\t\top->cycles = opcode_desc->cycles;\n\t\t\top->size = opcode_desc->size;\n\t\t\top->type = opcode_desc->type;\n\t\t\top->jump = UT64_MAX;\n\t\t\top->fail = UT64_MAX;\n\t\t\t// op->fail = addr + op->size;\n\t\t\top->addr = addr;\n\n\t\t\t// start void esil expression\n\t\t\tr_strbuf_setf (&op->esil, \"\");\n\n\t\t\t// handle opcode\n\t\t\topcode_desc->handler (anal, op, buf, len, &fail, cpu);\n\t\t\tif (fail) {\n\t\t\t\tgoto INVALID_OP;\n\t\t\t}\n\t\t\tif (op->cycles <= 0) {\n\t\t\t\t// eprintf (\"opcode %s @%\"PFMT64x\" returned 0 cycles.\\n\", opcode_desc->name, op->addr);\n\t\t\t\topcode_desc->cycles = 2;\n\t\t\t}\n\t\t\top->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);\n\n\t\t\t// remove trailing coma (COMETE LA COMA)\n\t\t\tt = r_strbuf_get (&op->esil);\n\t\t\tif (t && strlen (t) > 1) {\n\t\t\t\tt += strlen (t) - 1;\n\t\t\t\tif (*t == ',') {\n\t\t\t\t\t*t = '\\0';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn opcode_desc;\n\t\t}\n\t}\n\n\t// ignore reserved opcodes (if they have not been caught by the previous loop)\n\tif ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {\n\t\tgoto INVALID_OP;\n\t}\n\nINVALID_OP:\n\t// An unknown or invalid option has appeared.\n\t// -- Throw pokeball!\n\top->family = R_ANAL_OP_FAMILY_UNKNOWN;\n\top->type = R_ANAL_OP_TYPE_UNK;\n\top->addr = addr;\n\top->fail = UT64_MAX;\n\top->jump = UT64_MAX;\n\top->ptr = UT64_MAX;\n\top->val = UT64_MAX;\n\top->nopcode = 1;\n\top->cycles = 1;\n\top->size = 2;\n\t// launch esil trap (for communicating upper layers about this weird\n\t// and stinky situation\n\tr_strbuf_set (&op->esil, \"1,$\");\n\n\treturn NULL;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,\n unsigned char **p,\n unsigned char *end )\n{\n int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n size_t len;\n ((void) ssl);\n\n /*\n * PSK parameters:\n *\n * opaque psk_identity_hint<0..2^16-1>;\n */\n if( (*p) > end - 2 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n len = (*p)[0] << 8 | (*p)[1];\n *p += 2;\n\n if( (*p) > end - len )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n\n /*\n * Note: we currently ignore the PKS identity hint, as we only allow one\n * PSK to be provisionned on the client. This could be changed later if\n * someone needs that feature.\n */\n *p += len;\n ret = 0;\n\n return( ret );\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "static int do_session_handshake (lua_State *L, int status, lua_KContext ctx) {\n int rc;\n struct ssh_userdata *sshu = NULL;\n\n assert(lua_gettop(L) == 4);\n sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, \"ssh2\");\n\n while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) {\n luaL_getmetafield(L, 3, \"filter\");\n lua_pushvalue(L, 3);\n\n assert(lua_status(L) == LUA_OK);\n lua_callk(L, 1, 0, 0, do_session_handshake);\n }\n\n if (rc) {\n libssh2_session_free(sshu->session);\n sshu->session = NULL;\n return luaL_error(L, \"Unable to complete libssh2 handshake.\");\n }\n\n // lua_pushvalue(L, 3);\n lua_settop(L, 3);\n\n return 1;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "safe"} {"code": "webSocketsHasDataInBuffer(rfbClientPtr cl)\n{\n ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;\n\n if (wsctx && wsctx->readlen)\n return TRUE;\n\n return (cl->sslctx && rfbssl_pending(cl) > 0);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "hybiRemaining(ws_ctx_t *wsctx)\n{\n return wsctx->nToRead - wsctx->nReadRaw;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "rfbClientIteratorNext(rfbClientIteratorPtr i)\n{\n if (!i)\n return NULL;\n if(i->next == 0) {\n LOCK(rfbClientListMutex);\n i->next = i->screen->clientHead;\n UNLOCK(rfbClientListMutex);\n } else {\n rfbClientPtr cl = i->next;\n i->next = i->next->next;\n rfbDecrClientRef(cl);\n }\n\n#if defined(LIBVNCSERVER_HAVE_LIBPTHREAD) || defined(LIBVNCSERVER_HAVE_WIN32THREADS)\n if(!i->closedToo)\n while(i->next && i->next->sock<0)\n i->next = i->next->next;\n if(i->next)\n rfbIncrClientRef(i->next);\n#endif\n\n return i->next;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "receive_carbon(void **state)\n{\n prof_input(\"/carbons on\");\n\n prof_connect();\n assert_true(stbbr_received(\n \"\"\n ));\n\n stbbr_send(\n \"\"\n \"10\"\n \"On my mobile\"\n \"\"\n );\n assert_true(prof_output_exact(\"Buddy1 (mobile) is online, \\\"On my mobile\\\"\"));\n prof_input(\"/msg Buddy1\");\n assert_true(prof_output_exact(\"unencrypted\"));\n\n stbbr_send(\n \"\"\n \"\"\n \"\"\n \"\"\n \"test carbon from recipient\"\n \"\"\n \"\"\n \"\"\n \"\"\n );\n\n assert_true(prof_output_regex(\"Buddy1/mobile: .+test carbon from recipient\"));\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "static pyc_object *get_array_object_generic(RBuffer *buffer, ut32 size) {\n\tpyc_object *tmp = NULL;\n\tpyc_object *ret = NULL;\n\tut32 i = 0;\n\n\tret = R_NEW0 (pyc_object);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\tret->data = r_list_newf ((RListFree)free_object);\n\tif (!ret->data) {\n\t\tfree (ret);\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < size; i++) {\n\t\ttmp = get_object (buffer);\n\t\tif (!tmp || !r_list_append (ret->data, tmp)) {\n\t\t\tfree_object (tmp);\n\t\t\t((RList*)ret->data)->free = NULL;\n\t\t\tr_list_free (ret->data);\n\t\t\tfree (ret);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\treturn ret;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-825", "cwe_name": "Expired Pointer Dereference", "description": "The program dereferences a pointer that contains a location for memory that was previously valid, but is no longer valid.", "url": "https://cwe.mitre.org/data/definitions/825.html", "label_name": "safe"} {"code": "static pyc_object *get_list_object(RBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 n = get_ut32 (buffer, &error);\n\tif (n > ST32_MAX) {\n\t\teprintf (\"bad marshal data (list size out of range)\\n\");\n\t\treturn NULL;\n\t}\n\tif (error) {\n\t\treturn NULL;\n\t}\n\tret = get_array_object_generic (buffer, n);\n\tif (ret) {\n\t\tret->type = TYPE_LIST;\n\t\treturn ret;\n\t}\n\treturn NULL;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-825", "cwe_name": "Expired Pointer Dereference", "description": "The program dereferences a pointer that contains a location for memory that was previously valid, but is no longer valid.", "url": "https://cwe.mitre.org/data/definitions/825.html", "label_name": "safe"} {"code": "R_API bool r_crbtree_insert(RRBTree *tree, void *data, RRBComparator cmp, void *user) {\n\tr_return_val_if_fail (tree && data && cmp, false);\n\tbool inserted = false;\n\n\tif (!tree->root) {\n\t\ttree->root = _node_new (data, NULL);\n\t\tif (!tree->root) {\n\t\t\treturn false;\n\t\t}\n\t\tinserted = true;\n\t\tgoto out_exit;\n\t}\n\n\tRRBNode head; /* Fake tree root */\n\tmemset (&head, 0, sizeof (RRBNode));\n\tRRBNode *g = NULL, *parent = &head; /* Grandparent & parent */\n\tRRBNode *p = NULL, *q = tree->root; /* Iterator & parent */\n\tint dir = 0, last = 0; /* Directions */\n\n\t_set_link (parent, q, 1);\n\n\tfor (;;) {\n\t\tif (!q) {\n\t\t\t/* Insert a node at first null link(also set its parent link) */\n\t\t\tq = _node_new (data, p);\n\t\t\tif (!q) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tp->link[dir] = q;\n\t\t\tinserted = true;\n\t\t} else if (IS_RED (q->link[0]) && IS_RED (q->link[1])) {\n\t\t\t/* Simple red violation: color flip */\n\t\t\tq->red = 1;\n\t\t\tq->link[0]->red = 0;\n\t\t\tq->link[1]->red = 0;\n\t\t}\n\n\t\tif (IS_RED (q) && IS_RED (p)) {\n#if 0\n\t\t\t// coverity error, parent is never null\n\t\t\t/* Hard red violation: rotate */\n\t\t\tif (!parent) {\n\t\t\t\treturn false;\n\t\t\t}\n#endif\n\t\t\tint dir2 = parent->link[1] == g;\n\t\t\tif (q == p->link[last]) {\n\t\t\t\t_set_link (parent, _rot_once (g, !last), dir2);\n\t\t\t} else {\n\t\t\t\t_set_link (parent, _rot_twice (g, !last), dir2);\n\t\t\t}\n\t\t}\n\n\t\tif (inserted) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlast = dir;\n\t\tdir = cmp (data, q->data, user) >= 0;\n\n\t\tif (g) {\n\t\t\tparent = g;\n\t\t}\n\n\t\tg = p;\n\t\tp = q;\n\t\tq = q->link[dir];\n\t}\n\n\t/* Update root(it may different due to root rotation) */\n\ttree->root = head.link[1];\n\nout_exit:\n\t/* Invariant: root is black */\n\ttree->root->red = 0;\n\ttree->root->parent = NULL;\n\tif (inserted) {\n\t\ttree->size++;\n\t}\n\n\treturn inserted;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "static st64 buf_format(RBuffer *dst, RBuffer *src, const char *fmt, int n) {\n\tst64 res = 0;\n\tint i;\n\tfor (i = 0; i < n; i++) {\n\t\tint j;\n\t\tint m = 1;\n\t\tint tsize = 2;\n\t\tbool bigendian = true;\n\n\t\tfor (j = 0; fmt[j]; j++) {\n\t\t\tswitch (fmt[j]) {\n\t\t\tcase '0':\n\t\t\tcase '1':\n\t\t\tcase '2':\n\t\t\tcase '3':\n\t\t\tcase '4':\n\t\t\tcase '5':\n\t\t\tcase '6':\n\t\t\tcase '7':\n\t\t\tcase '8':\n\t\t\tcase '9':\n\t\t\t\tif (m == 1) {\n\t\t\t\t\tm = r_num_get (NULL, &fmt[j]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\tcase 's': tsize = 2; bigendian = false; break;\n\t\t\tcase 'S': tsize = 2; bigendian = true; break;\n\t\t\tcase 'i': tsize = 4; bigendian = false; break;\n\t\t\tcase 'I': tsize = 4; bigendian = true; break;\n\t\t\tcase 'l': tsize = 8; bigendian = false; break;\n\t\t\tcase 'L': tsize = 8; bigendian = true; break;\n\t\t\tcase 'c': tsize = 1; bigendian = false; break;\n\t\t\tdefault: return -1;\n\t\t\t}\n\n\t\t\tint k;\n\t\t\tfor (k = 0; k < m; k++) {\n\t\t\t\tut8 tmp[sizeof (ut64)];\n\t\t\t\tut8 d1;\n\t\t\t\tut16 d2;\n\t\t\t\tut32 d3;\n\t\t\t\tut64 d4;\n\t\t\t\tst64 r = r_buf_read (src, tmp, tsize);\n\t\t\t\tif (r != tsize) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tswitch (tsize) {\n\t\t\t\tcase 1:\n\t\t\t\t\td1 = r_read_ble8 (tmp);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d1, 1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\td2 = r_read_ble16 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d2, 2);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\td3 = r_read_ble32 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d3, 4);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\td4 = r_read_ble64 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d4, 8);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (r < 0) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tres += r;\n\t\t\t}\n\t\t\tm = 1;\n\t\t}\n\t}\n\treturn res;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": "ut32 armass_assemble(const char *str, ut64 off, int thumb) {\n\tint i, j;\n\tchar buf[128];\n\tArmOpcode aop = {.off = off};\n\tfor (i = j = 0; i < sizeof (buf) - 1 && str[j]; i++, j++) {\n\t\tif (str[j] == '#') {\n\t\t\ti--; continue;\n\t\t}\n\t\tbuf[i] = tolower ((const ut8)str[j]);\n\t}\n\tbuf[i] = 0;\n\tarm_opcode_parse (&aop, buf);\n\taop.off = off;\n\tif (thumb < 0 || thumb > 1) {\n\t\treturn -1;\n\t}\n\tif (!assemble[thumb] (&aop, off, buf)) {\n\t\t//eprintf (\"armass: Unknown opcode (%s)\\n\", buf);\n\t\treturn -1;\n\t}\n\treturn aop.o;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "static char *__filterShell(const char *arg) {\n\tr_return_val_if_fail (arg, NULL);\n\tchar *a = malloc (strlen (arg) + 1);\n\tif (!a) {\n\t\treturn NULL;\n\t}\n\tchar *b = a;\n\twhile (*arg) {\n\t\tchar ch = *arg;\n\t\tswitch (ch) {\n\t\tcase '@':\n\t\tcase '`':\n\t\tcase '|':\n\t\tcase ';':\n\t\tcase '=':\n\t\tcase '\\n':\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t*b++ = ch;\n\t\t\tbreak;\n\t\t}\n\t\targ++;\n\t}\n\t*b = 0;\n\treturn a;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "R_API void r_core_fini(RCore *c) {\n\tif (!c) {\n\t\treturn;\n\t}\n\tr_core_task_break_all (&c->tasks);\n\tr_core_task_join (&c->tasks, NULL, -1);\n\tr_core_wait (c);\n\t/* TODO: it leaks as shit */\n\t//update_sdb (c);\n\t// avoid double free\n\tr_list_free (c->ropchain);\n\tr_event_free (c->ev);\n\tfree (c->cmdlog);\n\tfree (c->lastsearch);\n\tR_FREE (c->cons->pager);\n\tfree (c->cmdqueue);\n\tfree (c->lastcmd);\n\tfree (c->stkcmd);\n\tr_list_free (c->visual.tabs);\n\tfree (c->block);\n\tr_core_autocomplete_free (c->autocomplete);\n\n\tr_list_free (c->gadgets);\n\tr_list_free (c->undos);\n\tr_num_free (c->num);\n\t// TODO: sync or not? sdb_sync (c->sdb);\n\t// TODO: sync all dbs?\n\t//r_core_file_free (c->file);\n\t//c->file = NULL;\n\tR_FREE (c->table_query);\n\tr_list_free (c->files);\n\tr_list_free (c->watchers);\n\tr_list_free (c->scriptstack);\n\tr_core_task_scheduler_fini (&c->tasks);\n\tc->rcmd = r_cmd_free (c->rcmd);\n\tr_list_free (c->cmd_descriptors);\n\tc->anal = r_anal_free (c->anal);\n\tr_asm_free (c->assembler);\n\tc->assembler = NULL;\n\tc->print = r_print_free (c->print);\n\tc->bin = (r_bin_free (c->bin), NULL);\n\tc->lang = (r_lang_free (c->lang), NULL);\n\tc->dbg = (r_debug_free (c->dbg), NULL);\n\tr_io_free (c->io);\n\tr_config_free (c->config);\n\t/* after r_config_free, the value of I.teefile is trashed */\n\t/* rconfig doesnt knows how to deinitialize vars, so we\n\tshould probably need to add a r_config_free_payload callback */\n\tr_cons_free ();\n\tr_cons_singleton ()->teefile = NULL; // HACK\n\tr_search_free (c->search);\n\tr_flag_free (c->flags);\n\tr_fs_free (c->fs);\n\tr_egg_free (c->egg);\n\tr_lib_free (c->lib);\n\tr_buf_free (c->yank_buf);\n\tr_agraph_free (c->graph);\n\tfree (c->asmqjmps);\n\tsdb_free (c->sdb);\n\tr_core_log_free (c->log);\n\tr_parse_free (c->parser);\n\tfree (c->times);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "safe"} {"code": "int main(int argc, char *argv[])\n{\n int ret_value = 0;\n libettercap_init();\n ef_globals_alloc();\n select_text_interface();\n libettercap_ui_init();\n /* etterfilter copyright */\n fprintf(stdout, \"\\n\" EC_COLOR_BOLD \"%s %s\" EC_COLOR_END \" copyright %s %s\\n\\n\", \n PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS);\n \n /* initialize the line number */\n EF_GBL->lineno = 1;\n \n /* getopt related parsing... */\n parse_options(argc, argv);\n\n /* set the input for source file */\n if (EF_GBL_OPTIONS->source_file) {\n yyin = fopen(EF_GBL_OPTIONS->source_file, \"r\");\n if (yyin == NULL)\n FATAL_ERROR(\"Input file not found !\");\n } else {\n FATAL_ERROR(\"No source file.\");\n }\n\n /* no buffering */\n setbuf(yyin, NULL);\n setbuf(stdout, NULL);\n setbuf(stderr, NULL);\n\n \n /* load the tables in etterfilter.tbl */\n load_tables();\n /* load the constants in etterfilter.cnt */\n load_constants();\n\n /* print the message */\n fprintf(stdout, \"\\n Parsing source file \\'%s\\' \", EF_GBL_OPTIONS->source_file);\n fflush(stdout);\n\n ef_debug(1, \"\\n\");\n\n /* begin the parsing */\n if (yyparse() == 0)\n fprintf(stdout, \" done.\\n\\n\");\n else\n fprintf(stdout, \"\\n\\nThe script contains errors...\\n\\n\");\n \n /* write to file */\n ret_value = write_output();\n if (ret_value == -E_NOTHANDLED)\n FATAL_ERROR(\"Cannot write output file (%s): the filter is not correctly handled.\", EF_GBL_OPTIONS->output_file);\n else if (ret_value == -E_INVALID)\n FATAL_ERROR(\"Cannot write output file (%s): the filter format is not correct. \", EF_GBL_OPTIONS->output_file);\n\n ef_globals_free();\n return 0;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "void *Sys_LoadDll(const char *name, qboolean useSystemLib)\n{\n\tvoid *dllhandle;\n\n\t// Don't load any DLLs that end with the pk3 extension\n\tif (COM_CompareExtension(name, \".pk3\"))\n\t{\n\t\tCom_Printf(\"Rejecting DLL named \\\"%s\\\"\", name);\n\t\treturn NULL;\n\t}\n\t\n\tif(useSystemLib)\n\t\tCom_Printf(\"Trying to load \\\"%s\\\"...\\n\", name);\n\t\n\tif(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))\n\t{\n\t\tconst char *topDir;\n\t\tchar libPath[MAX_OSPATH];\n\n\t\ttopDir = Sys_BinaryPath();\n\n\t\tif(!*topDir)\n\t\t\ttopDir = \".\";\n\n\t\tCom_Printf(\"Trying to load \\\"%s\\\" from \\\"%s\\\"...\\n\", name, topDir);\n\t\tCom_sprintf(libPath, sizeof(libPath), \"%s%c%s\", topDir, PATH_SEP, name);\n\n\t\tif(!(dllhandle = Sys_LoadLibrary(libPath)))\n\t\t{\n\t\t\tconst char *basePath = Cvar_VariableString(\"fs_basepath\");\n\t\t\t\n\t\t\tif(!basePath || !*basePath)\n\t\t\t\tbasePath = \".\";\n\t\t\t\n\t\t\tif(FS_FilenameCompare(topDir, basePath))\n\t\t\t{\n\t\t\t\tCom_Printf(\"Trying to load \\\"%s\\\" from \\\"%s\\\"...\\n\", name, basePath);\n\t\t\t\tCom_sprintf(libPath, sizeof(libPath), \"%s%c%s\", basePath, PATH_SEP, name);\n\t\t\t\tdllhandle = Sys_LoadLibrary(libPath);\n\t\t\t}\n\t\t\t\n\t\t\tif(!dllhandle)\n\t\t\t\tCom_Printf(\"Loading \\\"%s\\\" failed\\n\", name);\n\t\t}\n\t}\n\t\n\treturn dllhandle;\n}", "label": 1, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "DefragVlanTest(void)\n{\n Packet *p1 = NULL, *p2 = NULL, *r = NULL;\n int ret = 0;\n\n DefragInit();\n\n p1 = BuildTestPacket(IPPROTO_ICMP, 1, 0, 1, 'A', 8);\n if (p1 == NULL)\n goto end;\n p2 = BuildTestPacket(IPPROTO_ICMP, 1, 1, 0, 'B', 8);\n if (p2 == NULL)\n goto end;\n\n /* With no VLAN IDs set, packets should re-assemble. */\n if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)\n goto end;\n if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)\n goto end;\n SCFree(r);\n\n /* With mismatched VLANs, packets should not re-assemble. */\n p1->vlan_id[0] = 1;\n p2->vlan_id[0] = 2;\n if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)\n goto end;\n if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)\n goto end;\n\n /* Pass. */\n ret = 1;\n\nend:\n if (p1 != NULL)\n SCFree(p1);\n if (p2 != NULL)\n SCFree(p2);\n DefragDestroy();\n\n return ret;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-358", "cwe_name": "Improperly Implemented Security Check for Standard", "description": "The software does not implement or incorrectly implements one or more security-relevant checks as specified by the design of a standardized algorithm, protocol, or technique.", "url": "https://cwe.mitre.org/data/definitions/358.html", "label_name": "safe"} {"code": "static int hashKey(DIGEST_CTX hash, const struct pgpPkt *pkt, int exptag)\n{\n int rc = -1;\n if (pkt->tag == exptag) {\n\tuint8_t head[] = {\n\t 0x99,\n\t (pkt->blen >> 8),\n\t (pkt->blen ),\n\t};\n\n\trpmDigestUpdate(hash, head, 3);\n\trpmDigestUpdate(hash, pkt->body, pkt->blen);\n\trc = 0;\n }\n return rc;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "safe"} {"code": "static int pgpVerifySelf(pgpDigParams key, pgpDigParams selfsig,\n\t\t\tconst struct pgpPkt *all, int i)\n{\n int rc = -1;\n DIGEST_CTX hash = NULL;\n\n switch (selfsig->sigtype) {\n case PGPSIGTYPE_SUBKEY_BINDING:\n\thash = rpmDigestInit(selfsig->hash_algo, 0);\n\tif (hash) {\n\t rc = hashKey(hash, &all[0], PGPTAG_PUBLIC_KEY);\n\t if (!rc)\n\t\trc = hashKey(hash, &all[i-1], PGPTAG_PUBLIC_SUBKEY);\n\t}\n\tbreak;\n default:\n\t/* ignore types we can't handle */\n\trc = 0;\n\tbreak;\n }\n\n if (hash && rc == 0)\n\trc = pgpVerifySignature(key, selfsig, hash);\n\n rpmDigestFinal(hash, NULL, NULL, 0);\n\n return rc;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "safe"} {"code": "char *enl_ipc_get(const char *msg_data)\n{\n\n\tstatic char *message = NULL;\n\tstatic size_t len = 0;\n\tchar buff[13], *ret_msg = NULL;\n\tregister unsigned char i;\n\tunsigned char blen;\n\n\tif (msg_data == IPC_TIMEOUT) {\n\t\treturn(IPC_TIMEOUT);\n\t}\n\tfor (i = 0; i < 12; i++) {\n\t\tbuff[i] = msg_data[i];\n\t}\n\tbuff[12] = 0;\n\tblen = strlen(buff);\n\tif (message != NULL) {\n\t\tlen += blen;\n\t\tmessage = (char *) erealloc(message, len + 1);\n\t\tstrcat(message, buff);\n\t} else {\n\t\tlen = blen;\n\t\tmessage = (char *) emalloc(len + 1);\n\t\tstrcpy(message, buff);\n\t}\n\tif (blen < 12) {\n\t\tret_msg = message;\n\t\tmessage = NULL;\n\t\tD((\"Received complete reply: \\\"%s\\\"\\n\", ret_msg));\n\t}\n\treturn(ret_msg);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,\n\t\tconst iw_byte *d, size_t d_len)\n{\n\tstruct iw_exif_state e;\n\tiw_uint32 ifd;\n\n\tif(d_len<8) return;\n\n\tiw_zeromem(&e,sizeof(struct iw_exif_state));\n\te.d = d;\n\te.d_len = d_len;\n\n\te.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;\n\n\tifd = get_exif_ui32(&e, 4);\n\n\tiwjpeg_scan_exif_ifd(rctx,&e,ifd);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "static unsigned int get_exif_ui16(struct iw_exif_state *e, unsigned int pos)\n{\n\tif(e->d_len<2 || pos>e->d_len-2) return 0;\n\treturn iw_get_ui16_e(&e->d[pos], e->endian);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,\n OnigCompileInfo* ci, OnigErrorInfo* einfo)\n{\n int r;\n UChar *cpat, *cpat_end;\n\n if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;\n\n if (ci->pattern_enc != ci->target_enc) {\n return ONIGERR_NOT_SUPPORTED_ENCODING_COMBINATION;\n }\n else {\n cpat = (UChar* )pattern;\n cpat_end = (UChar* )pattern_end;\n }\n\n *reg = (regex_t* )xmalloc(sizeof(regex_t));\n if (IS_NULL(*reg)) {\n r = ONIGERR_MEMORY;\n goto err2;\n }\n\n r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,\n ci->syntax);\n if (r != 0) goto err;\n\n r = onig_compile(*reg, cpat, cpat_end, einfo);\n if (r != 0) {\n err:\n onig_free(*reg);\n *reg = NULL;\n }\n\n err2:\n if (cpat != pattern) xfree(cpat);\n\n return r;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "mrb_proc_init_copy(mrb_state *mrb, mrb_value self)\n{\n mrb_value proc = mrb_get_arg1(mrb);\n\n if (!mrb_proc_p(proc)) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"not a proc\");\n }\n mrb_proc_copy(mrb, mrb_proc_ptr(self), mrb_proc_ptr(proc));\n return self;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "mrb_obj_clone(mrb_state *mrb, mrb_value self)\n{\n struct RObject *p;\n mrb_value clone;\n\n if (mrb_immediate_p(self)) {\n mrb_raisef(mrb, E_TYPE_ERROR, \"can't clone %S\", self);\n }\n if (mrb_type(self) == MRB_TT_SCLASS) {\n mrb_raise(mrb, E_TYPE_ERROR, \"can't clone singleton class\");\n }\n p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));\n p->c = mrb_singleton_class_clone(mrb, self);\n mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);\n clone = mrb_obj_value(p);\n init_copy(mrb, clone, self);\n p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN;\n\n return clone;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "read_packet(int fd, gss_buffer_t buf, int timeout, int first)\n{\n\tint\t ret;\n\n\tstatic uint32_t\t\tlen = 0;\n\tstatic char\t\tlen_buf[4];\n\tstatic int\t\tlen_buf_pos = 0;\n\tstatic char *\t\ttmpbuf = 0;\n\tstatic int\t\ttmpbuf_pos = 0;\n\n\tif (first) {\n\t\tlen_buf_pos = 0;\n\t\treturn -2;\n\t}\n\n\tif (len_buf_pos < 4) {\n\t\tret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos,\n\t\t timeout);\n\n\t\tif (ret == -1) {\n\t\t\tif (errno == EINTR || errno == EAGAIN)\n\t\t\t\treturn -2;\n\n\t\t\tLOG(LOG_ERR, (\"%s\", strerror(errno)));\n\t\t\tgoto bail;\n\t\t}\n\n\t\tif (ret == 0) {\t\t/* EOF */\n\t\t\t/* Failure to read ANY length just means we're done */\n\t\t\tif (len_buf_pos == 0)\n\t\t\t\treturn 0;\n\n\t\t\t/*\n\t\t\t * Otherwise, we got EOF mid-length, and that's\n\t\t\t * a protocol error.\n\t\t\t */\n\t\t\tLOG(LOG_INFO, (\"EOF reading packet len\"));\n\t\t\tgoto bail;\n\t\t}\n\n\t\tlen_buf_pos += ret;\n\t}\n\n\t/* Not done reading the length? */\n\tif (len_buf_pos != 4)\n\t\treturn -2;\n\n\t/* We have the complete length */\n\tlen = ntohl(*(uint32_t *)len_buf);\n\n\t/*\n\t * We make sure recvd length is reasonable, allowing for some\n\t * slop in enc overhead, beyond the actual maximum number of\n\t * bytes of decrypted payload.\n\t */\n\tif (len > GSTD_MAXPACKETCONTENTS + 512) {\n\t\tLOG(LOG_ERR, (\"ridiculous length, %ld\", len));\n\t\tgoto bail;\n\t}\n\n\tif (!tmpbuf) {\n\t\tif ((tmpbuf = malloc(len)) == NULL) {\n\t\t\tLOG(LOG_CRIT, (\"malloc failure, %ld bytes\", len));\n\t\t\tgoto bail;\n\t\t}\n\t}\n\n\tret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout);\n\tif (ret == -1) {\n\n\t\tif (errno == EINTR || errno == EAGAIN)\n\t\t\treturn -2;\n\n\t\tLOG(LOG_ERR, (\"%s\", strerror(errno)));\n\t\tgoto bail;\n\t}\n\n\tif (ret == 0) {\n\t\tLOG(LOG_ERR, (\"EOF while reading packet (len=%d)\", len));\n\t\tgoto bail;\n\t}\n\n\ttmpbuf_pos += ret;\n\n\tif (tmpbuf_pos == len) {\n\t\tbuf->length = len;\n\t\tbuf->value = tmpbuf;\n\t\tlen = len_buf_pos = tmpbuf_pos = 0;\n\t\ttmpbuf = NULL;\n\n\t\tLOG(LOG_DEBUG, (\"read packet of length %d\", buf->length));\n\t\treturn 1;\n\t}\n\n\treturn -2;\n\nbail:\n\tfree(tmpbuf);\n\ttmpbuf = NULL;\n\n\treturn -1;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": "LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff)\n{\n\tconst char* str;\n\tchar buf[32];\n\tif(!file) return 0;\n\tstr = openmpt_module_get_instrument_name(file->mod,qual-1);\n\tmemset(buf,0,32);\n\tif(str){\n\t\tstrncpy(buf,str,31);\n\t\topenmpt_free_string(str);\n\t}\n\tif(buff){\n\t\tstrncpy(buff,buf,32);\n\t}\n\treturn (unsigned int)strlen(buf);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "safe"} {"code": "int fp_invmod_mont_ct(fp_int *a, fp_int *b, fp_int *c, fp_digit mp)\n{\n int i, j;\n#ifndef WOLFSSL_SMALL_STACK\n fp_int t[1], e[1];\n fp_int pre[CT_INV_MOD_PRE_CNT];\n#else\n fp_int* t;\n fp_int* e;\n fp_int* pre;\n#endif\n\n#ifdef WOLFSSL_SMALL_STACK\n t = (fp_int*)XMALLOC(sizeof(fp_int) * (2 + CT_INV_MOD_PRE_CNT), NULL,\n DYNAMIC_TYPE_BIGINT);\n if (t == NULL)\n return FP_MEM;\n e = t + 1;\n pre = t + 2;\n#endif\n\n fp_init(t);\n fp_init(e);\n\n fp_init(&pre[0]);\n fp_copy(a, &pre[0]);\n for (i = 1; i < CT_INV_MOD_PRE_CNT; i++) {\n fp_init(&pre[i]);\n fp_sqr(&pre[i-1], &pre[i]);\n fp_montgomery_reduce(&pre[i], b, mp);\n fp_mul(&pre[i], a, &pre[i]);\n fp_montgomery_reduce(&pre[i], b, mp);\n }\n\n fp_sub_d(b, 2, e);\n /* Highest bit is always set. */\n for (i = fp_count_bits(e)-2, j = 1; i >= 0; i--, j++) {\n if (!fp_is_bit_set(e, i) || j == CT_INV_MOD_PRE_CNT)\n break;\n }\n fp_copy(&pre[j-1], t);\n for (j = 0; i >= 0; i--) {\n int set = fp_is_bit_set(e, i);\n\n if ((j == CT_INV_MOD_PRE_CNT) || (!set && j > 0)) {\n fp_mul(t, &pre[j-1], t);\n fp_montgomery_reduce(t, b, mp);\n j = 0;\n }\n fp_sqr(t, t);\n fp_montgomery_reduce(t, b, mp);\n j += set;\n }\n if (j > 0) {\n fp_mul(t, &pre[j-1], c);\n fp_montgomery_reduce(c, b, mp);\n }\n else \n fp_copy(t, c);\n\n#ifdef WOLFSSL_SMALL_STACK\n XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);\n#endif\n return FP_OKAY;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-203", "cwe_name": "Observable Discrepancy", "description": "The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.", "url": "https://cwe.mitre.org/data/definitions/203.html", "label_name": "safe"} {"code": "GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)\n{\n\tCATEnum cat_enum;\n\tchar *sep;\n\n\tcat_enum.dest = dest;\n\tcat_enum.import_flags = import_flags;\n\tcat_enum.force_fps = force_fps;\n\tcat_enum.frames_per_sample = frames_per_sample;\n\tcat_enum.tmp_dir = tmp_dir;\n\tcat_enum.force_cat = force_cat;\n\tcat_enum.align_timelines = align_timelines;\n\tcat_enum.allow_add_in_command = allow_add_in_command;\n\n\tif (strlen(fileName) >= sizeof(cat_enum.szPath)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"File name %s is too long.\\n\", fileName));\n\t\treturn GF_NOT_SUPPORTED;\n\t}\n\tstrcpy(cat_enum.szPath, fileName);\n\tsep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR);\n\tif (!sep) sep = strrchr(cat_enum.szPath, '/');\n\tif (!sep) {\n\t\tstrcpy(cat_enum.szPath, \".\");\n\t\tif (strlen(fileName) >= sizeof(cat_enum.szRad1)) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"File name %s is too long.\\n\", fileName));\n\t\t\treturn GF_NOT_SUPPORTED;\n\t\t}\n\t\tstrcpy(cat_enum.szRad1, fileName);\n\t} else {\n\t\tif (strlen(sep + 1) >= sizeof(cat_enum.szRad1)) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"File name %s is too long.\\n\", (sep + 1)));\n\t\t\treturn GF_NOT_SUPPORTED;\n\t\t}\n\t\tstrcpy(cat_enum.szRad1, sep+1);\n\t\tsep[0] = 0;\n\t}\n\tsep = strchr(cat_enum.szRad1, '*');\n\tif (strlen(sep + 1) >= sizeof(cat_enum.szRad2)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"File name %s is too long.\\n\", (sep + 1)));\n\t\treturn GF_NOT_SUPPORTED;\n\t}\n\tstrcpy(cat_enum.szRad2, sep+1);\n\tsep[0] = 0;\n\tsep = strchr(cat_enum.szRad2, '%');\n\tif (!sep) sep = strchr(cat_enum.szRad2, '#');\n\tif (!sep) sep = strchr(cat_enum.szRad2, ':');\n\tstrcpy(cat_enum.szOpt, \"\");\n\tif (sep) {\n\t\tif (strlen(sep) >= sizeof(cat_enum.szOpt)) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Invalid option: %s.\\n\", sep));\n\t\t\treturn GF_NOT_SUPPORTED;\n\t\t}\n\t\tstrcpy(cat_enum.szOpt, sep);\n\t\tsep[0] = 0;\n\t}\n\treturn gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "GF_Err text_box_size(GF_Box *s)\n{\n\tGF_TextSampleEntryBox *ptr = (GF_TextSampleEntryBox*)s;\n\n\ts->size += 8;\n\t/*base + this + string length*/\n\ts->size += 43 + 1;\n\tif (ptr->textName)\n\t\ts->size += strlen(ptr->textName);\n\treturn GF_OK;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "}\n\nvoid print_udta(GF_ISOFile *file, u32 track_number, Bool has_itags)\n{\n\tu32 i, count;\n\n\tcount = gf_isom_get_udta_count(file, track_number);\n\tif (!count) return;\n\n\tif (has_itags) {\n\t\tfor (i=0; i=32) {\n\t\t\t//gf_bs_read_int keeps returning 0 on EOS, so if no more bits available, rbsp was truncated otherwise code is broken in rbsp)\n\t\t\t//we only test once nb_lead>=32 to avoid testing at each bit read\n\t\t\tif (!gf_bs_available(bs)) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[Core] exp-golomb read failed, not enough bits in bitstream !\\n\"));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[Core] corrupted exp-golomb code, %d leading zeros, max 31 allowed !\\n\", nb_lead));\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\tcode = gf_bs_read_int(bs, 1);\n\t\tbits++;\n\t}\n\n\tif (nb_lead) {\n\t\tu32 leads=1;\n\t\tval = gf_bs_read_int(bs, nb_lead);\n\t\tleads <<= nb_lead;\n\t\tleads -= 1;\n\t\tval += leads;\n//\t\tval += (1 << nb_lead) - 1;\n\t\tbits += nb_lead;\n\t}\n\n\tif (fname) {\n\t\tgf_bs_log_idx(bs, bits, fname, val, idx1, idx2, idx3);\n\t}\n\treturn val;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "static int msg_cache_check (const char *id, body_cache_t *bcache, void *data)\n{\n CONTEXT *ctx;\n POP_DATA *pop_data;\n int i;\n\n if (!(ctx = (CONTEXT *)data))\n return -1;\n if (!(pop_data = (POP_DATA *)ctx->data))\n return -1;\n\n#ifdef USE_HCACHE\n /* keep hcache file if hcache == bcache */\n if (strcmp (HC_FNAME \".\" HC_FEXT, id) == 0)\n return 0;\n#endif\n\n for (i = 0; i < ctx->msgcount; i++)\n /* if the id we get is known for a header: done (i.e. keep in cache) */\n if (ctx->hdrs[i]->data && mutt_strcmp (ctx->hdrs[i]->data, id) == 0)\n return 0;\n\n /* message not found in context -> remove it from cache\n * return the result of bcache, so we stop upon its first error\n */\n return mutt_bcache_del (bcache, cache_id (id));\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "static int msg_parse_fetch (IMAP_HEADER *h, char *s)\n{\n char tmp[SHORT_STRING];\n char *ptmp;\n size_t dlen;\n\n if (!s)\n return -1;\n\n while (*s)\n {\n SKIPWS (s);\n\n if (ascii_strncasecmp (\"FLAGS\", s, 5) == 0)\n {\n if ((s = msg_parse_flags (h, s)) == NULL)\n return -1;\n }\n else if (ascii_strncasecmp (\"UID\", s, 3) == 0)\n {\n s += 3;\n SKIPWS (s);\n if (mutt_atoui (s, &h->data->uid) < 0)\n return -1;\n\n s = imap_next_word (s);\n }\n else if (ascii_strncasecmp (\"INTERNALDATE\", s, 12) == 0)\n {\n s += 12;\n SKIPWS (s);\n if (*s != '\\\"')\n {\n dprint (1, (debugfile, \"msg_parse_fetch(): bogus INTERNALDATE entry: %s\\n\", s));\n return -1;\n }\n s++;\n ptmp = tmp;\n dlen = sizeof(tmp) - 1;\n while (*s && *s != '\\\"' && dlen)\n {\n *ptmp++ = *s++;\n dlen--;\n }\n if (*s != '\\\"')\n return -1;\n s++; /* skip past the trailing \" */\n *ptmp = 0;\n h->received = imap_parse_date (tmp);\n }\n else if (ascii_strncasecmp (\"RFC822.SIZE\", s, 11) == 0)\n {\n s += 11;\n SKIPWS (s);\n ptmp = tmp;\n dlen = sizeof(tmp) - 1;\n while (isdigit ((unsigned char) *s) && dlen)\n {\n *ptmp++ = *s++;\n dlen--;\n }\n *ptmp = 0;\n if (mutt_atol (tmp, &h->content_length) < 0)\n return -1;\n }\n else if (!ascii_strncasecmp (\"BODY\", s, 4) ||\n !ascii_strncasecmp (\"RFC822.HEADER\", s, 13))\n {\n /* handle above, in msg_fetch_header */\n return -2;\n }\n else if (*s == ')')\n s++; /* end of request */\n else if (*s)\n {\n /* got something i don't understand */\n imap_error (\"msg_parse_fetch\", s);\n return -1;\n }\n }\n\n return 0;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "int imap_exec(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)\n{\n int rc;\n\n if (flags & IMAP_CMD_SINGLE)\n {\n // Process any existing commands\n if (adata->nextcmd != adata->lastcmd)\n imap_exec(adata, NULL, IMAP_CMD_POLL);\n }\n\n rc = cmd_start(adata, cmdstr, flags);\n if (rc < 0)\n {\n cmd_handle_fatal(adata);\n return IMAP_EXEC_FATAL;\n }\n\n if (flags & IMAP_CMD_QUEUE)\n return IMAP_EXEC_SUCCESS;\n\n if ((flags & IMAP_CMD_POLL) && (C_ImapPollTimeout > 0) &&\n ((mutt_socket_poll(adata->conn, C_ImapPollTimeout)) == 0))\n {\n mutt_error(_(\"Connection to %s timed out\"), adata->conn->account.host);\n cmd_handle_fatal(adata);\n return IMAP_EXEC_FATAL;\n }\n\n /* Allow interruptions, particularly useful if there are network problems. */\n mutt_sig_allow_interrupt(true);\n do\n {\n rc = imap_cmd_step(adata);\n // The queue is empty, so the single command has been processed\n if ((flags & IMAP_CMD_SINGLE) && (adata->nextcmd == adata->lastcmd))\n break;\n } while (rc == IMAP_RES_CONTINUE);\n mutt_sig_allow_interrupt(false);\n\n if (rc == IMAP_RES_NO)\n return IMAP_EXEC_ERROR;\n if (rc != IMAP_RES_OK)\n {\n if (adata->status != IMAP_FATAL)\n return IMAP_EXEC_ERROR;\n\n mutt_debug(LL_DEBUG1, \"command failed: %s\\n\", adata->buf);\n return IMAP_EXEC_FATAL;\n }\n\n return IMAP_EXEC_SUCCESS;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "static inline int memcmp_P(const void *a1, const void *b1, size_t len) {\n const uint8_t* a = (const uint8_t*)(a1);\n uint8_t* b = (uint8_t*)(b1);\n for (size_t i=0; ictx, SC_LOG_DEBUG_NORMAL);\n if (card->serialnr.len) {\n *serial = card->serialnr;\n SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n }\n\tif (priv->cac_id_len) {\n\t\tserial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);\n\t\tmemcpy(serial->value, priv->cac_id, serial->len);\n\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n{\n\tmuscle_private_t* priv = MUSCLE_DATA(card);\n\tmscfs_t *fs = priv->fs;\n\tint x;\n\tint count = 0;\n\n\tmscfs_check_cache(priv->fs);\n\n\tfor(x = 0; x < fs->cache.size; x++) {\n\t\tu8* oid = fs->cache.array[x].objectId.id;\n\t\tif (bufLen < 2)\n\t\t\tbreak;\n\t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n\t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n\t\t\toid[0],oid[1],oid[2],oid[3]);\n\t\tif(0 == memcmp(fs->currentPath, oid, 2)) {\n\t\t\tbuf[0] = oid[2];\n\t\t\tbuf[1] = oid[3];\n\t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n\t\t\tbuf += 2;\n\t\t\tcount += 2;\n\t\t\tbufLen -= 2;\n\t\t}\n\t}\n\treturn count;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n{\n\tmuscle_private_t* priv = MUSCLE_DATA(card);\n\tmscfs_t *fs = priv->fs;\n\tint x;\n\tint count = 0;\n\n\tmscfs_check_cache(priv->fs);\n\n\tfor(x = 0; x < fs->cache.size; x++) {\n\t\tu8* oid = fs->cache.array[x].objectId.id;\n\t\tif (bufLen < 2)\n\t\t\tbreak;\n\t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n\t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n\t\t\toid[0],oid[1],oid[2],oid[3]);\n\t\tif(0 == memcmp(fs->currentPath, oid, 2)) {\n\t\t\tbuf[0] = oid[2];\n\t\t\tbuf[1] = oid[3];\n\t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n\t\t\tbuf += 2;\n\t\t\tcount += 2;\n\t\t\tbufLen -= 2;\n\t\t}\n\t}\n\treturn count;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "safe"} {"code": "int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,\n\t\t\t size_t sec_attr_len)\n{\n\tu8 *tmp;\n\tif (!sc_file_valid(file)) {\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\t}\n\n\tif (sec_attr == NULL || sec_attr_len) {\n\t\tif (file->sec_attr != NULL)\n\t\t\tfree(file->sec_attr);\n\t\tfile->sec_attr = NULL;\n\t\tfile->sec_attr_len = 0;\n\t\treturn 0;\n\t }\n\ttmp = (u8 *) realloc(file->sec_attr, sec_attr_len);\n\tif (!tmp) {\n\t\tif (file->sec_attr)\n\t\t\tfree(file->sec_attr);\n\t\tfile->sec_attr = NULL;\n\t\tfile->sec_attr_len = 0;\n\t\treturn SC_ERROR_OUT_OF_MEMORY;\n\t}\n\tfile->sec_attr = tmp;\n\tmemcpy(file->sec_attr, sec_attr, sec_attr_len);\n\tfile->sec_attr_len = sec_attr_len;\n\n\treturn 0;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,\n\t\t\t size_t sec_attr_len)\n{\n\tu8 *tmp;\n\tif (!sc_file_valid(file)) {\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\t}\n\n\tif (sec_attr == NULL || sec_attr_len) {\n\t\tif (file->sec_attr != NULL)\n\t\t\tfree(file->sec_attr);\n\t\tfile->sec_attr = NULL;\n\t\tfile->sec_attr_len = 0;\n\t\treturn 0;\n\t }\n\ttmp = (u8 *) realloc(file->sec_attr, sec_attr_len);\n\tif (!tmp) {\n\t\tif (file->sec_attr)\n\t\t\tfree(file->sec_attr);\n\t\tfile->sec_attr = NULL;\n\t\tfile->sec_attr_len = 0;\n\t\treturn SC_ERROR_OUT_OF_MEMORY;\n\t}\n\tfile->sec_attr = tmp;\n\tmemcpy(file->sec_attr, sec_attr, sec_attr_len);\n\tfile->sec_attr_len = sec_attr_len;\n\n\treturn 0;\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "static int read_public_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\n\tu8 buf[2048], *p = buf;\n\tsize_t bufsize, keysize;\n\n\tr = select_app_df();\n\tif (r)\n\t\treturn 1;\n\tsc_format_path(\"I1012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select public key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = MIN(file->size, sizeof buf);\n\tsc_file_free(file);\n\tr = sc_read_binary(card, 0, buf, bufsize, 0);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Unable to read public key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = r;\n\tdo {\n\t\tif (bufsize < 4)\n\t\t\treturn 3;\n\t\tkeysize = (p[0] << 8) | p[1];\n\t\tif (keysize == 0)\n\t\t\tbreak;\n\t\tif (keysize < 3)\n\t\t\treturn 3;\n\t\tif (p[2] == opt_key_num)\n\t\t\tbreak;\n\t\tp += keysize;\n\t\tbufsize -= keysize;\n\t} while (1);\n\tif (keysize == 0) {\n\t\tprintf(\"Key number %d not found.\\n\", opt_key_num);\n\t\treturn 2;\n\t}\n\treturn parse_public_key(p, keysize, rsa);\n}", "label": 1, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "kg_seal_iov(OM_uint32 *minor_status,\n gss_ctx_id_t context_handle,\n int conf_req_flag,\n gss_qop_t qop_req,\n int *conf_state,\n gss_iov_buffer_desc *iov,\n int iov_count,\n int toktype)\n{\n krb5_gss_ctx_id_rec *ctx;\n krb5_error_code code;\n krb5_context context;\n\n if (qop_req != 0) {\n *minor_status = (OM_uint32)G_UNKNOWN_QOP;\n return GSS_S_FAILURE;\n }\n\n ctx = (krb5_gss_ctx_id_rec *)context_handle;\n if (!ctx->established) {\n *minor_status = KG_CTX_INCOMPLETE;\n return GSS_S_NO_CONTEXT;\n }\n\n if (conf_req_flag && kg_integ_only_iov(iov, iov_count)) {\n /* may be more sensible to return an error here */\n conf_req_flag = FALSE;\n }\n\n context = ctx->k5_context;\n switch (ctx->proto) {\n case 0:\n code = make_seal_token_v1_iov(context, ctx, conf_req_flag,\n conf_state, iov, iov_count, toktype);\n break;\n case 1:\n code = gss_krb5int_make_seal_token_v3_iov(context, ctx, conf_req_flag,\n conf_state, iov, iov_count, toktype);\n break;\n default:\n code = G_UNKNOWN_QOP;\n break;\n }\n\n if (code != 0) {\n *minor_status = code;\n save_error_info(*minor_status, context);\n return GSS_S_FAILURE;\n }\n\n *minor_status = 0;\n\n return GSS_S_COMPLETE;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "kg_unseal_iov(OM_uint32 *minor_status,\n gss_ctx_id_t context_handle,\n int *conf_state,\n gss_qop_t *qop_state,\n gss_iov_buffer_desc *iov,\n int iov_count,\n int toktype)\n{\n krb5_gss_ctx_id_rec *ctx;\n OM_uint32 code;\n\n ctx = (krb5_gss_ctx_id_rec *)context_handle;\n if (!ctx->established) {\n *minor_status = KG_CTX_INCOMPLETE;\n return GSS_S_NO_CONTEXT;\n }\n\n if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) {\n code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state,\n iov, iov_count, toktype);\n } else {\n code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state,\n iov, iov_count, toktype);\n }\n\n return code;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "krb5_gss_process_context_token(minor_status, context_handle,\n token_buffer)\n OM_uint32 *minor_status;\n gss_ctx_id_t context_handle;\n gss_buffer_t token_buffer;\n{\n krb5_gss_ctx_id_rec *ctx;\n OM_uint32 majerr;\n\n ctx = (krb5_gss_ctx_id_t) context_handle;\n\n if (! ctx->established) {\n *minor_status = KG_CTX_INCOMPLETE;\n return(GSS_S_NO_CONTEXT);\n }\n\n /* \"unseal\" the token */\n\n if (GSS_ERROR(majerr = kg_unseal(minor_status, context_handle,\n token_buffer,\n GSS_C_NO_BUFFER, NULL, NULL,\n KG_TOK_DEL_CTX)))\n return(majerr);\n\n /* that's it. delete the context */\n\n return(krb5_gss_delete_sec_context(minor_status, &context_handle,\n GSS_C_NO_BUFFER));\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "spnego_gss_set_sec_context_option(\n\t\tOM_uint32 *minor_status,\n\t\tgss_ctx_id_t *context_handle,\n\t\tconst gss_OID desired_object,\n\t\tconst gss_buffer_t value)\n{\n\tOM_uint32 ret;\n\tret = gss_set_sec_context_option(minor_status,\n\t\t\t context_handle,\n\t\t\t desired_object,\n\t\t\t value);\n\treturn (ret);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-763", "cwe_name": "Release of Invalid Pointer or Reference", "description": "The application attempts to return a memory resource to the system, but calls the wrong release function or calls the appropriate release function incorrectly.", "url": "https://cwe.mitre.org/data/definitions/763.html", "label_name": "vulnerable"} {"code": "iakerb_alloc_context(iakerb_ctx_id_t *pctx)\n{\n iakerb_ctx_id_t ctx;\n krb5_error_code code;\n\n *pctx = NULL;\n\n ctx = k5alloc(sizeof(*ctx), &code);\n if (ctx == NULL)\n goto cleanup;\n ctx->defcred = GSS_C_NO_CREDENTIAL;\n ctx->magic = KG_IAKERB_CONTEXT;\n ctx->state = IAKERB_AS_REQ;\n ctx->count = 0;\n\n code = krb5_gss_init_context(&ctx->k5c);\n if (code != 0)\n goto cleanup;\n\n *pctx = ctx;\n\ncleanup:\n if (code != 0)\n iakerb_release_context(ctx);\n\n return code;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-18", "cwe_name": "DEPRECATED: Source Code", "description": "This entry has been deprecated. It was originally used for organizing the Development View (CWE-699) and some other views, but it introduced unnecessary complexity and depth to the resulting tree.", "url": "https://cwe.mitre.org/data/definitions/18.html", "label_name": "vulnerable"} {"code": "set_string_2_svc(sstring_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n const char *errmsg = NULL;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n ret.api_version = handle->api_version;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {\n ret.code = KADM5_BAD_PRINCIPAL;\n goto exit_func;\n }\n\n if (CHANGEPW_SERVICE(rqstp)\n || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,\n arg->princ, NULL)) {\n ret.code = KADM5_AUTH_MODIFY;\n log_unauth(\"kadm5_mod_strings\", prime_arg,\n &client_name, &service_name, rqstp);\n } else {\n ret.code = kadm5_set_string((void *)handle, arg->princ, arg->key,\n arg->value);\n if (ret.code != 0)\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n log_done(\"kadm5_mod_strings\", prime_arg, errmsg,\n &client_name, &service_name, rqstp);\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n }\n free(prime_arg);\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-772", "cwe_name": "Missing Release of Resource after Effective Lifetime", "description": "The software does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.", "url": "https://cwe.mitre.org/data/definitions/772.html", "label_name": "vulnerable"} {"code": "generic_ret *init_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n gss_buffer_desc client_name,\n service_name;\n kadm5_server_handle_t handle;\n OM_uint32 minor_stat;\n const char *errmsg = NULL;\n size_t clen, slen;\n char *cdots, *sdots;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(*arg, rqstp, &handle)))\n goto exit_func;\n if (! (ret.code = check_handle((void *)handle))) {\n ret.api_version = handle->api_version;\n }\n\n free_server_handle(handle);\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n\n if (ret.code != 0)\n errmsg = krb5_get_error_message(NULL, ret.code);\n\n clen = client_name.length;\n trunc_name(&clen, &cdots);\n slen = service_name.length;\n trunc_name(&slen, &sdots);\n /* okay to cast lengths to int because trunc_name limits max value */\n krb5_klog_syslog(LOG_NOTICE, _(\"Request: kadm5_init, %.*s%s, %s, \"\n \"client=%.*s%s, service=%.*s%s, addr=%s, \"\n \"vers=%d, flavor=%d\"),\n (int)clen, (char *)client_name.value, cdots,\n errmsg ? errmsg : _(\"success\"),\n (int)clen, (char *)client_name.value, cdots,\n (int)slen, (char *)service_name.value, sdots,\n client_addr(rqstp->rq_xprt),\n ret.api_version & ~(KADM5_API_VERSION_MASK),\n rqstp->rq_cred.oa_flavor);\n if (errmsg != NULL)\n krb5_free_error_message(NULL, errmsg);\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\n\nexit_func:\n return(&ret);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-772", "cwe_name": "Missing Release of Resource after Effective Lifetime", "description": "The software does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.", "url": "https://cwe.mitre.org/data/definitions/772.html", "label_name": "vulnerable"} {"code": "modify_policy_2_svc(mpol_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n const char *errmsg = NULL;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n ret.api_version = handle->api_version;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n prime_arg = arg->rec.policy;\n\n if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,\n rqst2name(rqstp),\n ACL_MODIFY, NULL, NULL)) {\n log_unauth(\"kadm5_modify_policy\", prime_arg,\n &client_name, &service_name, rqstp);\n ret.code = KADM5_AUTH_MODIFY;\n } else {\n ret.code = kadm5_modify_policy((void *)handle, &arg->rec,\n arg->mask);\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n log_done(\"kadm5_modify_policy\",\n ((prime_arg == NULL) ? \"(null)\" : prime_arg), errmsg,\n &client_name, &service_name, rqstp);\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n }\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-772", "cwe_name": "Missing Release of Resource after Effective Lifetime", "description": "The software does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.", "url": "https://cwe.mitre.org/data/definitions/772.html", "label_name": "vulnerable"} {"code": "gss_delete_sec_context (minor_status,\n context_handle,\n output_token)\n\nOM_uint32 *\t\tminor_status;\ngss_ctx_id_t *\t\tcontext_handle;\ngss_buffer_t\t\toutput_token;\n\n{\n OM_uint32\t\tstatus;\n gss_union_ctx_id_t\tctx;\n\n status = val_del_sec_ctx_args(minor_status, context_handle, output_token);\n if (status != GSS_S_COMPLETE)\n\treturn (status);\n\n /*\n * select the approprate underlying mechanism routine and\n * call it.\n */\n\n ctx = (gss_union_ctx_id_t) *context_handle;\n if (GSSINT_CHK_LOOP(ctx))\n\treturn (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);\n\n status = gssint_delete_internal_sec_context(minor_status,\n\t\t\t\t\t\tctx->mech_type,\n\t\t\t\t\t\t&ctx->internal_ctx_id,\n\t\t\t\t\t\toutput_token);\n if (status)\n\treturn status;\n\n /* now free up the space for the union context structure */\n free(ctx->mech_type->elements);\n free(ctx->mech_type);\n free(*context_handle);\n *context_handle = GSS_C_NO_CONTEXT;\n\n return (GSS_S_COMPLETE);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "midi_synth_load_patch(int dev, int format, const char __user *addr,\n\t\t int offs, int count, int pmgr_flag)\n{\n\tint orig_dev = synth_devs[dev]->midi_dev;\n\n\tstruct sysex_info sysex;\n\tint i;\n\tunsigned long left, src_offs, eox_seen = 0;\n\tint first_byte = 1;\n\tint hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex;\n\n\tleave_sysex(dev);\n\n\tif (!prefix_cmd(orig_dev, 0xf0))\n\t\treturn 0;\n\n\tif (format != SYSEX_PATCH)\n\t{\n/*\t\t printk(\"MIDI Error: Invalid patch format (key) 0x%x\\n\", format);*/\n\t\t return -EINVAL;\n\t}\n\tif (count < hdr_size)\n\t{\n/*\t\tprintk(\"MIDI Error: Patch header too short\\n\");*/\n\t\treturn -EINVAL;\n\t}\n\tcount -= hdr_size;\n\n\t/*\n\t * Copy the header from user space but ignore the first bytes which have\n\t * been transferred already.\n\t */\n\n\tif(copy_from_user(&((char *) &sysex)[offs], &(addr)[offs], hdr_size - offs))\n\t\treturn -EFAULT;\n \n \tif (count < sysex.len)\n\t{\n/*\t\tprintk(KERN_WARNING \"MIDI Warning: Sysex record too short (%d<%d)\\n\", count, (int) sysex.len);*/\n\t\tsysex.len = count;\n\t}\n \tleft = sysex.len;\n \tsrc_offs = 0;\n\n\tfor (i = 0; i < left && !signal_pending(current); i++)\n\t{\n\t\tunsigned char data;\n\n\t\tif (get_user(data,\n\t\t (unsigned char __user *)(addr + hdr_size + i)))\n\t\t\treturn -EFAULT;\n\n\t\teox_seen = (i > 0 && data & 0x80);\t/* End of sysex */\n\n\t\tif (eox_seen && data != 0xf7)\n\t\t\tdata = 0xf7;\n\n\t\tif (i == 0)\n\t\t{\n\t\t\tif (data != 0xf0)\n\t\t\t{\n\t\t\t\tprintk(KERN_WARNING \"midi_synth: Sysex start missing\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\t\twhile (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) &&\n\t\t\t!signal_pending(current))\n\t\t\tschedule();\n\n\t\tif (!first_byte && data & 0x80)\n\t\t\treturn 0;\n\t\tfirst_byte = 0;\n\t}\n\n\tif (!eox_seen)\n\t\tmidi_outc(orig_dev, 0xf7);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-189", "cwe_name": "Numeric Errors", "description": "Weaknesses in this category are related to improper calculation or conversion of numbers.", "url": "https://cwe.mitre.org/data/definitions/189.html", "label_name": "vulnerable"} {"code": "static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len)\n{\n\tunsigned char *pt;\n\tunsigned char l, lg, n = 0;\n\tint fac_national_digis_received = 0;\n\n\tdo {\n\t\tswitch (*p & 0xC0) {\n\t\tcase 0x00:\n\t\t\tp += 2;\n\t\t\tn += 2;\n\t\t\tlen -= 2;\n\t\t\tbreak;\n\n\t\tcase 0x40:\n\t\t\tif (*p == FAC_NATIONAL_RAND)\n\t\t\t\tfacilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF);\n\t\t\tp += 3;\n\t\t\tn += 3;\n\t\t\tlen -= 3;\n\t\t\tbreak;\n\n\t\tcase 0x80:\n\t\t\tp += 4;\n\t\t\tn += 4;\n\t\t\tlen -= 4;\n\t\t\tbreak;\n\n\t\tcase 0xC0:\n\t\t\tl = p[1];\n\t\t\tif (*p == FAC_NATIONAL_DEST_DIGI) {\n\t\t\t\tif (!fac_national_digis_received) {\n\t\t\t\t\tmemcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN);\n\t\t\t\t\tfacilities->source_ndigis = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (*p == FAC_NATIONAL_SRC_DIGI) {\n\t\t\t\tif (!fac_national_digis_received) {\n\t\t\t\t\tmemcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN);\n\t\t\t\t\tfacilities->dest_ndigis = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (*p == FAC_NATIONAL_FAIL_CALL) {\n\t\t\t\tmemcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN);\n\t\t\t}\n\t\t\telse if (*p == FAC_NATIONAL_FAIL_ADD) {\n\t\t\t\tmemcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN);\n\t\t\t}\n\t\t\telse if (*p == FAC_NATIONAL_DIGIS) {\n\t\t\t\tfac_national_digis_received = 1;\n\t\t\t\tfacilities->source_ndigis = 0;\n\t\t\t\tfacilities->dest_ndigis = 0;\n\t\t\t\tfor (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) {\n\t\t\t\t\tif (pt[6] & AX25_HBIT)\n\t\t\t\t\t\tmemcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN);\n\t\t\t\t\telse\n\t\t\t\t\t\tmemcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN);\n\t\t\t\t}\n\t\t\t}\n\t\t\tp += l + 2;\n\t\t\tn += l + 2;\n\t\t\tlen -= l + 2;\n\t\t\tbreak;\n\t\t}\n\t} while (*p != 0x00 && len > 0);\n\n\treturn n;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "int cipso_v4_req_setattr(struct request_sock *req,\n\t\t\t const struct cipso_v4_doi *doi_def,\n\t\t\t const struct netlbl_lsm_secattr *secattr)\n{\n\tint ret_val = -EPERM;\n\tunsigned char *buf = NULL;\n\tu32 buf_len;\n\tu32 opt_len;\n\tstruct ip_options *opt = NULL;\n\tstruct inet_request_sock *req_inet;\n\n\t/* We allocate the maximum CIPSO option size here so we are probably\n\t * being a little wasteful, but it makes our life _much_ easier later\n\t * on and after all we are only talking about 40 bytes. */\n\tbuf_len = CIPSO_V4_OPT_LEN_MAX;\n\tbuf = kmalloc(buf_len, GFP_ATOMIC);\n\tif (buf == NULL) {\n\t\tret_val = -ENOMEM;\n\t\tgoto req_setattr_failure;\n\t}\n\n\tret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);\n\tif (ret_val < 0)\n\t\tgoto req_setattr_failure;\n\tbuf_len = ret_val;\n\n\t/* We can't use ip_options_get() directly because it makes a call to\n\t * ip_options_get_alloc() which allocates memory with GFP_KERNEL and\n\t * we won't always have CAP_NET_RAW even though we _always_ want to\n\t * set the IPOPT_CIPSO option. */\n\topt_len = (buf_len + 3) & ~3;\n\topt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);\n\tif (opt == NULL) {\n\t\tret_val = -ENOMEM;\n\t\tgoto req_setattr_failure;\n\t}\n\tmemcpy(opt->__data, buf, buf_len);\n\topt->optlen = opt_len;\n\topt->cipso = sizeof(struct iphdr);\n\tkfree(buf);\n\tbuf = NULL;\n\n\treq_inet = inet_rsk(req);\n\topt = xchg(&req_inet->opt, opt);\n\tkfree(opt);\n\n\treturn 0;\n\nreq_setattr_failure:\n\tkfree(buf);\n\tkfree(opt);\n\treturn ret_val;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)\n{\n\tstruct ip_options *opt;\n\n\topt = inet_sk(sk)->opt;\n\tif (opt == NULL || opt->cipso == 0)\n\t\treturn -ENOMSG;\n\n\treturn cipso_v4_getattr(opt->__data + opt->cipso - sizeof(struct iphdr),\n\t\t\t\tsecattr);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "int ip_options_get(struct net *net, struct ip_options **optp,\n\t\t unsigned char *data, int optlen)\n{\n\tstruct ip_options *opt = ip_options_get_alloc(optlen);\n\n\tif (!opt)\n\t\treturn -ENOMEM;\n\tif (optlen)\n\t\tmemcpy(opt->__data, data, optlen);\n\treturn ip_options_get_finish(net, optp, opt, optlen);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "void ip_options_build(struct sk_buff * skb, struct ip_options * opt,\n\t\t\t __be32 daddr, struct rtable *rt, int is_frag)\n{\n\tunsigned char *iph = skb_network_header(skb);\n\n\tmemcpy(&(IPCB(skb)->opt), opt, sizeof(struct ip_options));\n\tmemcpy(iph+sizeof(struct iphdr), opt->__data, opt->optlen);\n\topt = &(IPCB(skb)->opt);\n\n\tif (opt->srr)\n\t\tmemcpy(iph+opt->srr+iph[opt->srr+1]-4, &daddr, 4);\n\n\tif (!is_frag) {\n\t\tif (opt->rr_needaddr)\n\t\t\tip_rt_get_source(iph+opt->rr+iph[opt->rr+2]-5, rt);\n\t\tif (opt->ts_needaddr)\n\t\t\tip_rt_get_source(iph+opt->ts+iph[opt->ts+2]-9, rt);\n\t\tif (opt->ts_needtime) {\n\t\t\tstruct timespec tv;\n\t\t\t__be32 midtime;\n\t\t\tgetnstimeofday(&tv);\n\t\t\tmidtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC);\n\t\t\tmemcpy(iph+opt->ts+iph[opt->ts+2]-5, &midtime, 4);\n\t\t}\n\t\treturn;\n\t}\n\tif (opt->rr) {\n\t\tmemset(iph+opt->rr, IPOPT_NOP, iph[opt->rr+1]);\n\t\topt->rr = 0;\n\t\topt->rr_needaddr = 0;\n\t}\n\tif (opt->ts) {\n\t\tmemset(iph+opt->ts, IPOPT_NOP, iph[opt->ts+1]);\n\t\topt->ts = 0;\n\t\topt->ts_needaddr = opt->ts_needtime = 0;\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "int ip_build_and_send_pkt(struct sk_buff *skb, struct sock *sk,\n\t\t\t __be32 saddr, __be32 daddr, struct ip_options *opt)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct rtable *rt = skb_rtable(skb);\n\tstruct iphdr *iph;\n\n\t/* Build the IP header. */\n\tskb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen : 0));\n\tskb_reset_network_header(skb);\n\tiph = ip_hdr(skb);\n\tiph->version = 4;\n\tiph->ihl = 5;\n\tiph->tos = inet->tos;\n\tif (ip_dont_fragment(sk, &rt->dst))\n\t\tiph->frag_off = htons(IP_DF);\n\telse\n\t\tiph->frag_off = 0;\n\tiph->ttl = ip_select_ttl(inet, &rt->dst);\n\tiph->daddr = rt->rt_dst;\n\tiph->saddr = rt->rt_src;\n\tiph->protocol = sk->sk_protocol;\n\tip_select_ident(iph, &rt->dst, sk);\n\n\tif (opt && opt->optlen) {\n\t\tiph->ihl += opt->optlen>>2;\n\t\tip_options_build(skb, opt, daddr, rt, 0);\n\t}\n\n\tskb->priority = sk->sk_priority;\n\tskb->mark = sk->sk_mark;\n\n\t/* Send it out. */\n\treturn ip_local_out(skb);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "static int ip_setup_cork(struct sock *sk, struct inet_cork *cork,\n\t\t\t struct ipcm_cookie *ipc, struct rtable **rtp)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct ip_options *opt;\n\tstruct rtable *rt;\n\n\t/*\n\t * setup for corking.\n\t */\n\topt = ipc->opt;\n\tif (opt) {\n\t\tif (cork->opt == NULL) {\n\t\t\tcork->opt = kmalloc(sizeof(struct ip_options) + 40,\n\t\t\t\t\t sk->sk_allocation);\n\t\t\tif (unlikely(cork->opt == NULL))\n\t\t\t\treturn -ENOBUFS;\n\t\t}\n\t\tmemcpy(cork->opt, opt, sizeof(struct ip_options) + opt->optlen);\n\t\tcork->flags |= IPCORK_OPT;\n\t\tcork->addr = ipc->addr;\n\t}\n\trt = *rtp;\n\tif (unlikely(!rt))\n\t\treturn -EFAULT;\n\t/*\n\t * We steal reference to this route, caller should not release it\n\t */\n\t*rtp = NULL;\n\tcork->fragsize = inet->pmtudisc == IP_PMTUDISC_PROBE ?\n\t\t\t rt->dst.dev->mtu : dst_mtu(rt->dst.path);\n\tcork->dst = &rt->dst;\n\tcork->length = 0;\n\tcork->tx_flags = ipc->tx_flags;\n\tcork->page = NULL;\n\tcork->off = 0;\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "void __init acpi_debugfs_init(void)\n{\n\tacpi_debugfs_dir = debugfs_create_dir(\"acpi\", NULL);\n\n\tacpi_custom_method_init();\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "static void nlmclnt_unlock_callback(struct rpc_task *task, void *data)\n{\n\tstruct nlm_rqst\t*req = data;\n\tu32 status = ntohl(req->a_res.status);\n\n\tif (RPC_ASSASSINATED(task))\n\t\tgoto die;\n\n\tif (task->tk_status < 0) {\n\t\tdprintk(\"lockd: unlock failed (err = %d)\\n\", -task->tk_status);\n\t\tgoto retry_rebind;\n\t}\n\tif (status == NLM_LCK_DENIED_GRACE_PERIOD) {\n\t\trpc_delay(task, NLMCLNT_GRACE_WAIT);\n\t\tgoto retry_unlock;\n\t}\n\tif (status != NLM_LCK_GRANTED)\n\t\tprintk(KERN_WARNING \"lockd: unexpected unlock status: %d\\n\", status);\ndie:\n\treturn;\n retry_rebind:\n\tnlm_rebind_host(req->a_host);\n retry_unlock:\n\trpc_restart_call(task);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "static void alpha_perf_event_irq_handler(unsigned long la_ptr,\n\t\t\t\t\tstruct pt_regs *regs)\n{\n\tstruct cpu_hw_events *cpuc;\n\tstruct perf_sample_data data;\n\tstruct perf_event *event;\n\tstruct hw_perf_event *hwc;\n\tint idx, j;\n\n\t__get_cpu_var(irq_pmi_count)++;\n\tcpuc = &__get_cpu_var(cpu_hw_events);\n\n\t/* Completely counting through the PMC's period to trigger a new PMC\n\t * overflow interrupt while in this interrupt routine is utterly\n\t * disastrous! The EV6 and EV67 counters are sufficiently large to\n\t * prevent this but to be really sure disable the PMCs.\n\t */\n\twrperfmon(PERFMON_CMD_DISABLE, cpuc->idx_mask);\n\n\t/* la_ptr is the counter that overflowed. */\n\tif (unlikely(la_ptr >= alpha_pmu->num_pmcs)) {\n\t\t/* This should never occur! */\n\t\tirq_err_count++;\n\t\tpr_warning(\"PMI: silly index %ld\\n\", la_ptr);\n\t\twrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);\n\t\treturn;\n\t}\n\n\tidx = la_ptr;\n\n\tperf_sample_data_init(&data, 0);\n\tfor (j = 0; j < cpuc->n_events; j++) {\n\t\tif (cpuc->current_idx[j] == idx)\n\t\t\tbreak;\n\t}\n\n\tif (unlikely(j == cpuc->n_events)) {\n\t\t/* This can occur if the event is disabled right on a PMC overflow. */\n\t\twrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);\n\t\treturn;\n\t}\n\n\tevent = cpuc->event[j];\n\n\tif (unlikely(!event)) {\n\t\t/* This should never occur! */\n\t\tirq_err_count++;\n\t\tpr_warning(\"PMI: No event at index %d!\\n\", idx);\n\t\twrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);\n\t\treturn;\n\t}\n\n\thwc = &event->hw;\n\talpha_perf_event_update(event, hwc, idx, alpha_pmu->pmc_max_period[idx]+1);\n\tdata.period = event->hw.last_period;\n\n\tif (alpha_perf_event_set_period(event, hwc, idx)) {\n\t\tif (perf_event_overflow(event, 1, &data, regs)) {\n\t\t\t/* Interrupts coming too quickly; \"throttle\" the\n\t\t\t * counter, i.e., disable it for a little while.\n\t\t\t */\n\t\t\talpha_pmu_stop(event, 0);\n\t\t}\n\t}\n\twrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);\n\n\treturn;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "xscale2pmu_handle_irq(int irq_num, void *dev)\n{\n\tunsigned long pmnc, of_flags;\n\tstruct perf_sample_data data;\n\tstruct cpu_hw_events *cpuc;\n\tstruct pt_regs *regs;\n\tint idx;\n\n\t/* Disable the PMU. */\n\tpmnc = xscale2pmu_read_pmnc();\n\txscale2pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE);\n\n\t/* Check the overflow flag register. */\n\tof_flags = xscale2pmu_read_overflow_flags();\n\tif (!(of_flags & XSCALE2_OVERFLOWED_MASK))\n\t\treturn IRQ_NONE;\n\n\t/* Clear the overflow bits. */\n\txscale2pmu_write_overflow_flags(of_flags);\n\n\tregs = get_irq_regs();\n\n\tperf_sample_data_init(&data, 0);\n\n\tcpuc = &__get_cpu_var(cpu_hw_events);\n\tfor (idx = 0; idx <= armpmu->num_events; ++idx) {\n\t\tstruct perf_event *event = cpuc->events[idx];\n\t\tstruct hw_perf_event *hwc;\n\n\t\tif (!test_bit(idx, cpuc->active_mask))\n\t\t\tcontinue;\n\n\t\tif (!xscale2_pmnc_counter_has_overflowed(pmnc, idx))\n\t\t\tcontinue;\n\n\t\thwc = &event->hw;\n\t\tarmpmu_event_update(event, hwc, idx, 1);\n\t\tdata.period = event->hw.last_period;\n\t\tif (!armpmu_event_set_period(event, hwc, idx))\n\t\t\tcontinue;\n\n\t\tif (perf_event_overflow(event, 0, &data, regs))\n\t\t\tarmpmu->disable(hwc, idx);\n\t}\n\n\tirq_work_run();\n\n\t/*\n\t * Re-enable the PMU.\n\t */\n\tpmnc = xscale2pmu_read_pmnc() | XSCALE_PMU_ENABLE;\n\txscale2pmu_write_pmnc(pmnc);\n\n\treturn IRQ_HANDLED;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "static int simulate_llsc(struct pt_regs *regs, unsigned int opcode)\n{\n\tif ((opcode & OPCODE) == LL) {\n\t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n\t\t\t\t1, 0, regs, 0);\n\t\treturn simulate_ll(regs, opcode);\n\t}\n\tif ((opcode & OPCODE) == SC) {\n\t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n\t\t\t\t1, 0, regs, 0);\n\t\treturn simulate_sc(regs, opcode);\n\t}\n\n\treturn -1;\t\t\t/* Must be something else ... */\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "static void perf_event_interrupt(struct pt_regs *regs)\n{\n\tint i;\n\tstruct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);\n\tstruct perf_event *event;\n\tunsigned long val;\n\tint found = 0;\n\tint nmi;\n\n\tif (cpuhw->n_limited)\n\t\tfreeze_limited_counters(cpuhw, mfspr(SPRN_PMC5),\n\t\t\t\t\tmfspr(SPRN_PMC6));\n\n\tperf_read_regs(regs);\n\n\tnmi = perf_intr_is_nmi(regs);\n\tif (nmi)\n\t\tnmi_enter();\n\telse\n\t\tirq_enter();\n\n\tfor (i = 0; i < cpuhw->n_events; ++i) {\n\t\tevent = cpuhw->event[i];\n\t\tif (!event->hw.idx || is_limited_pmc(event->hw.idx))\n\t\t\tcontinue;\n\t\tval = read_pmc(event->hw.idx);\n\t\tif ((int)val < 0) {\n\t\t\t/* event has overflowed */\n\t\t\tfound = 1;\n\t\t\trecord_and_restart(event, val, regs, nmi);\n\t\t}\n\t}\n\n\t/*\n\t * In case we didn't find and reset the event that caused\n\t * the interrupt, scan all events and reset any that are\n\t * negative, to avoid getting continual interrupts.\n\t * Any that we processed in the previous loop will not be negative.\n\t */\n\tif (!found) {\n\t\tfor (i = 0; i < ppmu->n_counter; ++i) {\n\t\t\tif (is_limited_pmc(i + 1))\n\t\t\t\tcontinue;\n\t\t\tval = read_pmc(i + 1);\n\t\t\tif (pmc_overflow(val))\n\t\t\t\twrite_pmc(i + 1, 0);\n\t\t}\n\t}\n\n\t/*\n\t * Reset MMCR0 to its normal value. This will set PMXE and\n\t * clear FC (freeze counters) and PMAO (perf mon alert occurred)\n\t * and thus allow interrupts to occur again.\n\t * XXX might want to use MSR.PM to keep the events frozen until\n\t * we get back out of this interrupt.\n\t */\n\twrite_mmcr0(cpuhw, cpuhw->mmcr[0]);\n\n\tif (nmi)\n\t\tnmi_exit();\n\telse\n\t\tirq_exit();\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "int handle_popc(u32 insn, struct pt_regs *regs)\n{\n\tu64 value;\n\tint ret, i, rd = ((insn >> 25) & 0x1f);\n\tint from_kernel = (regs->tstate & TSTATE_PRIV) != 0;\n\t \n\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);\n\tif (insn & 0x2000) {\n\t\tmaybe_flush_windows(0, 0, rd, from_kernel);\n\t\tvalue = sign_extend_imm13(insn);\n\t} else {\n\t\tmaybe_flush_windows(0, insn & 0x1f, rd, from_kernel);\n\t\tvalue = fetch_reg(insn & 0x1f, regs);\n\t}\n\tfor (ret = 0, i = 0; i < 16; i++) {\n\t\tret += popc_helper[value & 0xf];\n\t\tvalue >>= 4;\n\t}\n\tif (rd < 16) {\n\t\tif (rd)\n\t\t\tregs->u_regs[rd] = ret;\n\t} else {\n\t\tif (test_thread_flag(TIF_32BIT)) {\n\t\t\tstruct reg_window32 __user *win32;\n\t\t\twin32 = (struct reg_window32 __user *)((unsigned long)((u32)regs->u_regs[UREG_FP]));\n\t\t\tput_user(ret, &win32->locals[rd - 16]);\n\t\t} else {\n\t\t\tstruct reg_window __user *win;\n\t\t\twin = (struct reg_window __user *)(regs->u_regs[UREG_FP] + STACK_BIAS);\n\t\t\tput_user(ret, &win->locals[rd - 16]);\n\t\t}\n\t}\n\tadvance(regs);\n\treturn 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "void handle_stdfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr)\n{\n\tunsigned long pc = regs->tpc;\n\tunsigned long tstate = regs->tstate;\n\tu32 insn;\n\tu64 value;\n\tu8 freg;\n\tint flag;\n\tstruct fpustate *f = FPUSTATE;\n\n\tif (tstate & TSTATE_PRIV)\n\t\tdie_if_kernel(\"stdfmna from kernel\", regs);\n\tperf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, sfar);\n\tif (test_thread_flag(TIF_32BIT))\n\t\tpc = (u32)pc;\n\tif (get_user(insn, (u32 __user *) pc) != -EFAULT) {\n\t\tint asi = decode_asi(insn, regs);\n\t\tfreg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);\n\t\tvalue = 0;\n\t\tflag = (freg < 32) ? FPRS_DL : FPRS_DU;\n\t\tif ((asi > ASI_SNFL) ||\n\t\t (asi < ASI_P))\n\t\t\tgoto daex;\n\t\tsave_and_clear_fpu();\n\t\tif (current_thread_info()->fpsaved[0] & flag)\n\t\t\tvalue = *(u64 *)&f->regs[freg];\n\t\tswitch (asi) {\n\t\tcase ASI_P:\n\t\tcase ASI_S: break;\n\t\tcase ASI_PL:\n\t\tcase ASI_SL: \n\t\t\tvalue = __swab64p(&value); break;\n\t\tdefault: goto daex;\n\t\t}\n\t\tif (put_user (value >> 32, (u32 __user *) sfar) ||\n\t\t __put_user ((u32)value, (u32 __user *)(sfar + 4)))\n\t\t\tgoto daex;\n\t} else {\ndaex:\n\t\tif (tlb_type == hypervisor)\n\t\t\tsun4v_data_access_exception(regs, sfar, sfsr);\n\t\telse\n\t\t\tspitfire_data_access_exception(regs, sfsr, sfar);\n\t\treturn;\n\t}\n\tadvance(regs);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "void perf_bp_event(struct perf_event *bp, void *data)\n{\n\tstruct perf_sample_data sample;\n\tstruct pt_regs *regs = data;\n\n\tperf_sample_data_init(&sample, bp->attr.bp_addr);\n\n\tif (!bp->hw.state && !perf_exclude_event(bp, regs))\n\t\tperf_swevent_event(bp, 1, 1, &sample, regs);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "static void watchdog_overflow_callback(struct perf_event *event, int nmi,\n\t\t struct perf_sample_data *data,\n\t\t struct pt_regs *regs)\n{\n\t/* Ensure the watchdog never gets throttled */\n\tevent->hw.interrupts = 0;\n\n\tif (__this_cpu_read(watchdog_nmi_touch) == true) {\n\t\t__this_cpu_write(watchdog_nmi_touch, false);\n\t\treturn;\n\t}\n\n\t/* check for a hardlockup\n\t * This is done by making sure our timer interrupt\n\t * is incrementing. The timer interrupt should have\n\t * fired multiple times before we overflow'd. If it hasn't\n\t * then this is a good indication the cpu is stuck\n\t */\n\tif (is_hardlockup()) {\n\t\tint this_cpu = smp_processor_id();\n\n\t\t/* only print hardlockups once */\n\t\tif (__this_cpu_read(hard_watchdog_warn) == true)\n\t\t\treturn;\n\n\t\tif (hardlockup_panic)\n\t\t\tpanic(\"Watchdog detected hard LOCKUP on cpu %d\", this_cpu);\n\t\telse\n\t\t\tWARN(1, \"Watchdog detected hard LOCKUP on cpu %d\", this_cpu);\n\n\t\t__this_cpu_write(hard_watchdog_warn, true);\n\t\treturn;\n\t}\n\n\t__this_cpu_write(hard_watchdog_warn, false);\n\treturn;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "static inline __u16\tinet_getid(struct inet_peer *p, int more)\n{\n\tmore++;\n\tinet_peer_refcheck(p);\n\treturn atomic_add_return(more, &p->ip_id_count) - more;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static inline int ip6_ufo_append_data(struct sock *sk,\n\t\t\tint getfrag(void *from, char *to, int offset, int len,\n\t\t\tint odd, struct sk_buff *skb),\n\t\t\tvoid *from, int length, int hh_len, int fragheaderlen,\n\t\t\tint transhdrlen, int mtu,unsigned int flags)\n\n{\n\tstruct sk_buff *skb;\n\tint err;\n\n\t/* There is support for UDP large send offload by network\n\t * device, so create one single skb packet containing complete\n\t * udp datagram\n\t */\n\tif ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {\n\t\tskb = sock_alloc_send_skb(sk,\n\t\t\thh_len + fragheaderlen + transhdrlen + 20,\n\t\t\t(flags & MSG_DONTWAIT), &err);\n\t\tif (skb == NULL)\n\t\t\treturn -ENOMEM;\n\n\t\t/* reserve space for Hardware header */\n\t\tskb_reserve(skb, hh_len);\n\n\t\t/* create space for UDP/IP header */\n\t\tskb_put(skb,fragheaderlen + transhdrlen);\n\n\t\t/* initialize network header pointer */\n\t\tskb_reset_network_header(skb);\n\n\t\t/* initialize protocol header pointer */\n\t\tskb->transport_header = skb->network_header + fragheaderlen;\n\n\t\tskb->ip_summed = CHECKSUM_PARTIAL;\n\t\tskb->csum = 0;\n\t}\n\n\terr = skb_append_datato_frags(sk,skb, getfrag, from,\n\t\t\t\t (length - transhdrlen));\n\tif (!err) {\n\t\tstruct frag_hdr fhdr;\n\n\t\t/* Specify the length of each IPv6 datagram fragment.\n\t\t * It has to be a multiple of 8.\n\t\t */\n\t\tskb_shinfo(skb)->gso_size = (mtu - fragheaderlen -\n\t\t\t\t\t sizeof(struct frag_hdr)) & ~7;\n\t\tskb_shinfo(skb)->gso_type = SKB_GSO_UDP;\n\t\tipv6_select_ident(&fhdr);\n\t\tskb_shinfo(skb)->ip6_frag_id = fhdr.identification;\n\t\t__skb_queue_tail(&sk->sk_write_queue, skb);\n\n\t\treturn 0;\n\t}\n\t/* There is not enough support do UPD LSO,\n\t * so follow normal path\n\t */\n\tkfree_skb(skb);\n\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "void macvlan_common_setup(struct net_device *dev)\n{\n\tether_setup(dev);\n\n\tdev->priv_flags\t &= ~IFF_XMIT_DST_RELEASE;\n\tdev->netdev_ops\t\t= &macvlan_netdev_ops;\n\tdev->destructor\t\t= free_netdev;\n\tdev->header_ops\t\t= &macvlan_hard_header_ops,\n\tdev->ethtool_ops\t= &macvlan_ethtool_ops;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "__u32 secure_ip_id(__be32 daddr)\n{\n\tstruct keydata *keyptr;\n\t__u32 hash[4];\n\n\tkeyptr = get_keyptr();\n\n\t/*\n\t * Pick a unique starting offset for each IP destination.\n\t * The dest ip address is placed in the starting vector,\n\t * which is then hashed with random data.\n\t */\n\thash[0] = (__force __u32)daddr;\n\thash[1] = keyptr->secret[9];\n\thash[2] = keyptr->secret[10];\n\thash[3] = keyptr->secret[11];\n\n\treturn half_md4_transform(hash, keyptr->secret);\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)\n{\n\tstruct page *pages[NFS4ACL_MAXPAGES];\n\tstruct nfs_getaclargs args = {\n\t\t.fh = NFS_FH(inode),\n\t\t.acl_pages = pages,\n\t\t.acl_len = buflen,\n\t};\n\tstruct nfs_getaclres res = {\n\t\t.acl_len = buflen,\n\t};\n\tvoid *resp_buf;\n\tstruct rpc_message msg = {\n\t\t.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],\n\t\t.rpc_argp = &args,\n\t\t.rpc_resp = &res,\n\t};\n\tstruct page *localpage = NULL;\n\tint ret;\n\n\tif (buflen < PAGE_SIZE) {\n\t\t/* As long as we're doing a round trip to the server anyway,\n\t\t * let's be prepared for a page of acl data. */\n\t\tlocalpage = alloc_page(GFP_KERNEL);\n\t\tresp_buf = page_address(localpage);\n\t\tif (localpage == NULL)\n\t\t\treturn -ENOMEM;\n\t\targs.acl_pages[0] = localpage;\n\t\targs.acl_pgbase = 0;\n\t\targs.acl_len = PAGE_SIZE;\n\t} else {\n\t\tresp_buf = buf;\n\t\tbuf_to_pages(buf, buflen, args.acl_pages, &args.acl_pgbase);\n\t}\n\tret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0);\n\tif (ret)\n\t\tgoto out_free;\n\tif (res.acl_len > args.acl_len)\n\t\tnfs4_write_cached_acl(inode, NULL, res.acl_len);\n\telse\n\t\tnfs4_write_cached_acl(inode, resp_buf, res.acl_len);\n\tif (buf) {\n\t\tret = -ERANGE;\n\t\tif (res.acl_len > buflen)\n\t\t\tgoto out_free;\n\t\tif (localpage)\n\t\t\tmemcpy(buf, resp_buf, res.acl_len);\n\t}\n\tret = res.acl_len;\nout_free:\n\tif (localpage)\n\t\t__free_page(localpage);\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-189", "cwe_name": "Numeric Errors", "description": "Weaknesses in this category are related to improper calculation or conversion of numbers.", "url": "https://cwe.mitre.org/data/definitions/189.html", "label_name": "vulnerable"} {"code": "static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr,\n\t\t\t int *uaddrlen, int peer)\n{\n\tstruct sockaddr_llc sllc;\n\tstruct sock *sk = sock->sk;\n\tstruct llc_sock *llc = llc_sk(sk);\n\tint rc = 0;\n\n\tmemset(&sllc, 0, sizeof(sllc));\n\tlock_sock(sk);\n\tif (sock_flag(sk, SOCK_ZAPPED))\n\t\tgoto out;\n\t*uaddrlen = sizeof(sllc);\n\tmemset(uaddr, 0, *uaddrlen);\n\tif (peer) {\n\t\trc = -ENOTCONN;\n\t\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\t\tgoto out;\n\t\tif(llc->dev)\n\t\t\tsllc.sllc_arphrd = llc->dev->type;\n\t\tsllc.sllc_sap = llc->daddr.lsap;\n\t\tmemcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN);\n\t} else {\n\t\trc = -EINVAL;\n\t\tif (!llc->sap)\n\t\t\tgoto out;\n\t\tsllc.sllc_sap = llc->sap->laddr.lsap;\n\n\t\tif (llc->dev) {\n\t\t\tsllc.sllc_arphrd = llc->dev->type;\n\t\t\tmemcpy(&sllc.sllc_mac, llc->dev->dev_addr,\n\t\t\t IFHWADDRLEN);\n\t\t}\n\t}\n\trc = 0;\n\tsllc.sllc_family = AF_LLC;\n\tmemcpy(uaddr, &sllc, sizeof(sllc));\nout:\n\trelease_sock(sk);\n\treturn rc;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "static inline int ccid_hc_rx_getsockopt(struct ccid *ccid, struct sock *sk,\n\t\t\t\t\tconst int optname, int len,\n\t\t\t\t\tu32 __user *optval, int __user *optlen)\n{\n\tint rc = -ENOPROTOOPT;\n\tif (ccid->ccid_ops->ccid_hc_rx_getsockopt != NULL)\n\t\trc = ccid->ccid_ops->ccid_hc_rx_getsockopt(sk, optname, len,\n\t\t\t\t\t\t optval, optlen);\n\treturn rc;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len)\n{\n\tstruct sock_iocb *siocb = kiocb_to_siocb(kiocb);\n\tstruct sock *sk = sock->sk;\n\tstruct netlink_sock *nlk = nlk_sk(sk);\n\tstruct sockaddr_nl *addr = msg->msg_name;\n\tu32 dst_pid;\n\tu32 dst_group;\n\tstruct sk_buff *skb;\n\tint err;\n\tstruct scm_cookie scm;\n\n\tif (msg->msg_flags&MSG_OOB)\n\t\treturn -EOPNOTSUPP;\n\n\tif (NULL == siocb->scm)\n\t\tsiocb->scm = &scm;\n\n\terr = scm_send(sock, msg, siocb->scm);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (msg->msg_namelen) {\n\t\terr = -EINVAL;\n\t\tif (addr->nl_family != AF_NETLINK)\n\t\t\tgoto out;\n\t\tdst_pid = addr->nl_pid;\n\t\tdst_group = ffs(addr->nl_groups);\n\t\terr = -EPERM;\n\t\tif (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))\n\t\t\tgoto out;\n\t} else {\n\t\tdst_pid = nlk->dst_pid;\n\t\tdst_group = nlk->dst_group;\n\t}\n\n\tif (!nlk->pid) {\n\t\terr = netlink_autobind(sock);\n\t\tif (err)\n\t\t\tgoto out;\n\t}\n\n\terr = -EMSGSIZE;\n\tif (len > sk->sk_sndbuf - 32)\n\t\tgoto out;\n\terr = -ENOBUFS;\n\tskb = alloc_skb(len, GFP_KERNEL);\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tNETLINK_CB(skb).pid\t= nlk->pid;\n\tNETLINK_CB(skb).dst_group = dst_group;\n\tmemcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));\n\n\terr = -EFAULT;\n\tif (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {\n\t\tkfree_skb(skb);\n\t\tgoto out;\n\t}\n\n\terr = security_netlink_send(sk, skb);\n\tif (err) {\n\t\tkfree_skb(skb);\n\t\tgoto out;\n\t}\n\n\tif (dst_group) {\n\t\tatomic_inc(&skb->users);\n\t\tnetlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);\n\t}\n\terr = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);\n\nout:\n\tscm_destroy(siocb->scm);\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": "static int ptrace_check_attach(struct task_struct *child, bool ignore_state)\n{\n\tint ret = -ESRCH;\n\n\t/*\n\t * We take the read lock around doing both checks to close a\n\t * possible race where someone else was tracing our child and\n\t * detached between these two checks. After this locked check,\n\t * we are sure that this is our traced child and that can only\n\t * be changed by us so it's not changing right after this.\n\t */\n\tread_lock(&tasklist_lock);\n\tif ((child->ptrace & PT_PTRACED) && child->parent == current) {\n\t\t/*\n\t\t * child->sighand can't be NULL, release_task()\n\t\t * does ptrace_unlink() before __exit_signal().\n\t\t */\n\t\tspin_lock_irq(&child->sighand->siglock);\n\t\tWARN_ON_ONCE(task_is_stopped(child));\n\t\tif (ignore_state || (task_is_traced(child) &&\n\t\t\t\t !(child->jobctl & JOBCTL_LISTENING)))\n\t\t\tret = 0;\n\t\tspin_unlock_irq(&child->sighand->siglock);\n\t}\n\tread_unlock(&tasklist_lock);\n\n\tif (!ret && !ignore_state)\n\t\tret = wait_task_inactive(child, TASK_TRACED) ? 0 : -ESRCH;\n\n\t/* All systems go.. */\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)\n{\n\tstruct xenvif *vif;\n\tstruct pending_tx_info *pending_tx_info;\n\tpending_ring_idx_t index;\n\n\t/* Already complete? */\n\tif (netbk->mmap_pages[pending_idx] == NULL)\n\t\treturn;\n\n\tpending_tx_info = &netbk->pending_tx_info[pending_idx];\n\n\tvif = pending_tx_info->vif;\n\n\tmake_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY);\n\n\tindex = pending_index(netbk->pending_prod++);\n\tnetbk->pending_ring[index] = pending_idx;\n\n\txenvif_put(vif);\n\n\tnetbk->mmap_pages[pending_idx]->mapping = 0;\n\tput_page(netbk->mmap_pages[pending_idx]);\n\tnetbk->mmap_pages[pending_idx] = NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_aead raead;\n\tstruct aead_alg *aead = &alg->cra_aead;\n\n\tsnprintf(raead.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"nivaead\");\n\tsnprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, \"%s\", aead->geniv);\n\n\traead.blocksize = alg->cra_blocksize;\n\traead.maxauthsize = aead->maxauthsize;\n\traead.ivsize = aead->ivsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_AEAD,\n\t\t sizeof(struct crypto_report_aead), &raead))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": "static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_hash rhash;\n\n\tsnprintf(rhash.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"ahash\");\n\n\trhash.blocksize = alg->cra_blocksize;\n\trhash.digestsize = __crypto_hash_alg_common(alg)->digestsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_HASH,\n\t\t sizeof(struct crypto_report_hash), &rhash))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": "static int crypto_report_one(struct crypto_alg *alg,\n\t\t\t struct crypto_user_alg *ualg, struct sk_buff *skb)\n{\n\tmemcpy(&ualg->cru_name, &alg->cra_name, sizeof(ualg->cru_name));\n\tmemcpy(&ualg->cru_driver_name, &alg->cra_driver_name,\n\t sizeof(ualg->cru_driver_name));\n\tmemcpy(&ualg->cru_module_name, module_name(alg->cra_module),\n\t CRYPTO_MAX_ALG_NAME);\n\n\tualg->cru_flags = alg->cra_flags;\n\tualg->cru_refcnt = atomic_read(&alg->cra_refcnt);\n\n\tif (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority))\n\t\tgoto nla_put_failure;\n\tif (alg->cra_flags & CRYPTO_ALG_LARVAL) {\n\t\tstruct crypto_report_larval rl;\n\n\t\tsnprintf(rl.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"larval\");\n\n\t\tif (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL,\n\t\t\t sizeof(struct crypto_report_larval), &rl))\n\t\t\tgoto nla_put_failure;\n\t\tgoto out;\n\t}\n\n\tif (alg->cra_type && alg->cra_type->report) {\n\t\tif (alg->cra_type->report(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tgoto out;\n\t}\n\n\tswitch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) {\n\tcase CRYPTO_ALG_TYPE_CIPHER:\n\t\tif (crypto_report_cipher(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tbreak;\n\tcase CRYPTO_ALG_TYPE_COMPRESS:\n\t\tif (crypto_report_comp(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tbreak;\n\t}\n\nout:\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": "static int crypto_report_one(struct crypto_alg *alg,\n\t\t\t struct crypto_user_alg *ualg, struct sk_buff *skb)\n{\n\tmemcpy(&ualg->cru_name, &alg->cra_name, sizeof(ualg->cru_name));\n\tmemcpy(&ualg->cru_driver_name, &alg->cra_driver_name,\n\t sizeof(ualg->cru_driver_name));\n\tmemcpy(&ualg->cru_module_name, module_name(alg->cra_module),\n\t CRYPTO_MAX_ALG_NAME);\n\n\tualg->cru_flags = alg->cra_flags;\n\tualg->cru_refcnt = atomic_read(&alg->cra_refcnt);\n\n\tif (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority))\n\t\tgoto nla_put_failure;\n\tif (alg->cra_flags & CRYPTO_ALG_LARVAL) {\n\t\tstruct crypto_report_larval rl;\n\n\t\tsnprintf(rl.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"larval\");\n\n\t\tif (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL,\n\t\t\t sizeof(struct crypto_report_larval), &rl))\n\t\t\tgoto nla_put_failure;\n\t\tgoto out;\n\t}\n\n\tif (alg->cra_type && alg->cra_type->report) {\n\t\tif (alg->cra_type->report(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tgoto out;\n\t}\n\n\tswitch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) {\n\tcase CRYPTO_ALG_TYPE_CIPHER:\n\t\tif (crypto_report_cipher(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tbreak;\n\tcase CRYPTO_ALG_TYPE_COMPRESS:\n\t\tif (crypto_report_comp(skb, alg))\n\t\t\tgoto nla_put_failure;\n\n\t\tbreak;\n\t}\n\nout:\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": "static void kvmclock_reset(struct kvm_vcpu *vcpu)\n{\n\tif (vcpu->arch.time_page) {\n\t\tkvm_release_page_dirty(vcpu->arch.time_page);\n\t\tvcpu->arch.time_page = NULL;\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "static int do_tkill(pid_t tgid, pid_t pid, int sig)\n{\n\tstruct siginfo info;\n\n\tinfo.si_signo = sig;\n\tinfo.si_errno = 0;\n\tinfo.si_code = SI_TKILL;\n\tinfo.si_pid = task_tgid_vnr(current);\n\tinfo.si_uid = from_kuid_munged(current_user_ns(), current_uid());\n\n\treturn do_send_specific(tgid, pid, sig, &info);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "void migrate_page_copy(struct page *newpage, struct page *page)\n{\n\tint cpupid;\n\n\tif (PageHuge(page) || PageTransHuge(page))\n\t\tcopy_huge_page(newpage, page);\n\telse\n\t\tcopy_highpage(newpage, page);\n\n\tif (PageError(page))\n\t\tSetPageError(newpage);\n\tif (PageReferenced(page))\n\t\tSetPageReferenced(newpage);\n\tif (PageUptodate(page))\n\t\tSetPageUptodate(newpage);\n\tif (TestClearPageActive(page)) {\n\t\tVM_BUG_ON_PAGE(PageUnevictable(page), page);\n\t\tSetPageActive(newpage);\n\t} else if (TestClearPageUnevictable(page))\n\t\tSetPageUnevictable(newpage);\n\tif (PageChecked(page))\n\t\tSetPageChecked(newpage);\n\tif (PageMappedToDisk(page))\n\t\tSetPageMappedToDisk(newpage);\n\n\tif (PageDirty(page)) {\n\t\tclear_page_dirty_for_io(page);\n\t\t/*\n\t\t * Want to mark the page and the radix tree as dirty, and\n\t\t * redo the accounting that clear_page_dirty_for_io undid,\n\t\t * but we can't use set_page_dirty because that function\n\t\t * is actually a signal that all of the page has become dirty.\n\t\t * Whereas only part of our page may be dirty.\n\t\t */\n\t\tif (PageSwapBacked(page))\n\t\t\tSetPageDirty(newpage);\n\t\telse\n\t\t\t__set_page_dirty_nobuffers(newpage);\n \t}\n\n\tif (page_is_young(page))\n\t\tset_page_young(newpage);\n\tif (page_is_idle(page))\n\t\tset_page_idle(newpage);\n\n\t/*\n\t * Copy NUMA information to the new page, to prevent over-eager\n\t * future migrations of this same page.\n\t */\n\tcpupid = page_cpupid_xchg_last(page, -1);\n\tpage_cpupid_xchg_last(newpage, cpupid);\n\n\tksm_migrate_page(newpage, page);\n\t/*\n\t * Please do not reorder this without considering how mm/ksm.c's\n\t * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().\n\t */\n\tif (PageSwapCache(page))\n\t\tClearPageSwapCache(page);\n\tClearPagePrivate(page);\n\tset_page_private(page, 0);\n\n\t/*\n\t * If any waiters have accumulated on the new page then\n\t * wake them up.\n\t */\n\tif (PageWriteback(newpage))\n\t\tend_page_writeback(newpage);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static int trusted_update(struct key *key, struct key_preparsed_payload *prep)\n{\n\tstruct trusted_key_payload *p = key->payload.data[0];\n\tstruct trusted_key_payload *new_p;\n\tstruct trusted_key_options *new_o;\n\tsize_t datalen = prep->datalen;\n\tchar *datablob;\n\tint ret = 0;\n\n\tif (!p->migratable)\n\t\treturn -EPERM;\n\tif (datalen <= 0 || datalen > 32767 || !prep->data)\n\t\treturn -EINVAL;\n\n\tdatablob = kmalloc(datalen + 1, GFP_KERNEL);\n\tif (!datablob)\n\t\treturn -ENOMEM;\n\tnew_o = trusted_options_alloc();\n\tif (!new_o) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tnew_p = trusted_payload_alloc(key);\n\tif (!new_p) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tmemcpy(datablob, prep->data, datalen);\n\tdatablob[datalen] = '\\0';\n\tret = datablob_parse(datablob, new_p, new_o);\n\tif (ret != Opt_update) {\n\t\tret = -EINVAL;\n\t\tkfree(new_p);\n\t\tgoto out;\n\t}\n\n\tif (!new_o->keyhandle) {\n\t\tret = -EINVAL;\n\t\tkfree(new_p);\n\t\tgoto out;\n\t}\n\n\t/* copy old key values, and reseal with new pcrs */\n\tnew_p->migratable = p->migratable;\n\tnew_p->key_len = p->key_len;\n\tmemcpy(new_p->key, p->key, p->key_len);\n\tdump_payload(p);\n\tdump_payload(new_p);\n\n\tret = key_seal(new_p, new_o);\n\tif (ret < 0) {\n\t\tpr_info(\"trusted_key: key_seal failed (%d)\\n\", ret);\n\t\tkfree(new_p);\n\t\tgoto out;\n\t}\n\tif (new_o->pcrlock) {\n\t\tret = pcrlock(new_o->pcrlock);\n\t\tif (ret < 0) {\n\t\t\tpr_info(\"trusted_key: pcrlock failed (%d)\\n\", ret);\n\t\t\tkfree(new_p);\n\t\t\tgoto out;\n\t\t}\n\t}\n\trcu_assign_keypointer(key, new_p);\n\tcall_rcu(&p->rcu, trusted_rcu_free);\nout:\n\tkfree(datablob);\n\tkfree(new_o);\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-269", "cwe_name": "Improper Privilege Management", "description": "The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.", "url": "https://cwe.mitre.org/data/definitions/269.html", "label_name": "vulnerable"} {"code": "void inet6_destroy_sock(struct sock *sk)\n{\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct sk_buff *skb;\n\tstruct ipv6_txoptions *opt;\n\n\t/* Release rx options */\n\n\tskb = xchg(&np->pktoptions, NULL);\n\tif (skb)\n\t\tkfree_skb(skb);\n\n\tskb = xchg(&np->rxpmtu, NULL);\n\tif (skb)\n\t\tkfree_skb(skb);\n\n\t/* Free flowlabels */\n\tfl6_free_socklist(sk);\n\n\t/* Free tx options */\n\n\topt = xchg(&np->opt, NULL);\n\tif (opt)\n\t\tsock_kfree_s(sk, opt, opt->tot_len);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "int inet6_sk_rebuild_header(struct sock *sk)\n{\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct dst_entry *dst;\n\n\tdst = __sk_dst_check(sk, np->dst_cookie);\n\n\tif (!dst) {\n\t\tstruct inet_sock *inet = inet_sk(sk);\n\t\tstruct in6_addr *final_p, final;\n\t\tstruct flowi6 fl6;\n\n\t\tmemset(&fl6, 0, sizeof(fl6));\n\t\tfl6.flowi6_proto = sk->sk_protocol;\n\t\tfl6.daddr = sk->sk_v6_daddr;\n\t\tfl6.saddr = np->saddr;\n\t\tfl6.flowlabel = np->flow_label;\n\t\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\t\tfl6.flowi6_mark = sk->sk_mark;\n\t\tfl6.fl6_dport = inet->inet_dport;\n\t\tfl6.fl6_sport = inet->inet_sport;\n\t\tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n\n\t\tfinal_p = fl6_update_dst(&fl6, np->opt, &final);\n\n\t\tdst = ip6_dst_lookup_flow(sk, &fl6, final_p);\n\t\tif (IS_ERR(dst)) {\n\t\t\tsk->sk_route_caps = 0;\n\t\t\tsk->sk_err_soft = -PTR_ERR(dst);\n\t\t\treturn PTR_ERR(dst);\n\t\t}\n\n\t\t__ip6_dst_store(sk, dst, NULL, NULL);\n\t}\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl_unused)\n{\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct flowi6 fl6;\n\tstruct dst_entry *dst;\n\tint res;\n\n\tdst = inet6_csk_route_socket(sk, &fl6);\n\tif (IS_ERR(dst)) {\n\t\tsk->sk_err_soft = -PTR_ERR(dst);\n\t\tsk->sk_route_caps = 0;\n\t\tkfree_skb(skb);\n\t\treturn PTR_ERR(dst);\n\t}\n\n\trcu_read_lock();\n\tskb_dst_set_noref(skb, dst);\n\n\t/* Restore final destination back after routing done */\n\tfl6.daddr = sk->sk_v6_daddr;\n\n\tres = ip6_xmit(sk, skb, &fl6, np->opt, np->tclass);\n\trcu_read_unlock();\n\treturn res;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)\n{\n\tmutex_lock(&kvm->arch.vpit->pit_state.lock);\n\tmemcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));\n\tkvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);\n\tmutex_unlock(&kvm->arch.vpit->pit_state.lock);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-369", "cwe_name": "Divide By Zero", "description": "The product divides a value by zero.", "url": "https://cwe.mitre.org/data/definitions/369.html", "label_name": "vulnerable"} {"code": "int iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb)\n{\n\tint\terror = 0;\n\tstruct cxio_rdev *rdev;\n\n\trdev = (struct cxio_rdev *)tdev->ulp;\n\tif (cxio_fatal_error(rdev)) {\n\t\tkfree_skb(skb);\n\t\treturn -EIO;\n\t}\n\terror = cxgb3_ofld_send(tdev, skb);\n\tif (error < 0)\n\t\tkfree_skb(skb);\n\treturn error;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd,\n\t\t\t\t unsigned long arg)\n{\n\tstruct oabi_flock64 user;\n\tstruct flock64 kernel;\n\tmm_segment_t fs = USER_DS; /* initialized to kill a warning */\n\tunsigned long local_arg = arg;\n\tint ret;\n\n\tswitch (cmd) {\n\tcase F_OFD_GETLK:\n\tcase F_OFD_SETLK:\n\tcase F_OFD_SETLKW:\n\tcase F_GETLK64:\n\tcase F_SETLK64:\n\tcase F_SETLKW64:\n\t\tif (copy_from_user(&user, (struct oabi_flock64 __user *)arg,\n\t\t\t\t sizeof(user)))\n\t\t\treturn -EFAULT;\n\t\tkernel.l_type\t= user.l_type;\n\t\tkernel.l_whence\t= user.l_whence;\n\t\tkernel.l_start\t= user.l_start;\n\t\tkernel.l_len\t= user.l_len;\n\t\tkernel.l_pid\t= user.l_pid;\n\t\tlocal_arg = (unsigned long)&kernel;\n\t\tfs = get_fs();\n\t\tset_fs(KERNEL_DS);\n\t}\n\n\tret = sys_fcntl64(fd, cmd, local_arg);\n\n\tswitch (cmd) {\n\tcase F_GETLK64:\n\t\tif (!ret) {\n\t\t\tuser.l_type\t= kernel.l_type;\n\t\t\tuser.l_whence\t= kernel.l_whence;\n\t\t\tuser.l_start\t= kernel.l_start;\n\t\t\tuser.l_len\t= kernel.l_len;\n\t\t\tuser.l_pid\t= kernel.l_pid;\n\t\t\tif (copy_to_user((struct oabi_flock64 __user *)arg,\n\t\t\t\t\t &user, sizeof(user)))\n\t\t\t\tret = -EFAULT;\n\t\t}\n\tcase F_SETLK64:\n\tcase F_SETLKW64:\n\t\tset_fs(fs);\n\t}\n\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "void unix_notinflight(struct file *fp)\n{\n\tstruct sock *s = unix_get_socket(fp);\n\n\tif (s) {\n\t\tstruct unix_sock *u = unix_sk(s);\n\n\t\tspin_lock(&unix_gc_lock);\n\t\tBUG_ON(list_empty(&u->link));\n\n\t\tif (atomic_long_dec_and_test(&u->inflight))\n\t\t\tlist_del_init(&u->link);\n\t\tunix_tot_inflight--;\n\t\tspin_unlock(&unix_gc_lock);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "ext4_xattr_create_cache(char *name)\n{\n\treturn mb_cache_create(name, HASH_BUCKET_BITS);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-19", "cwe_name": "Data Processing Errors", "description": "Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information.", "url": "https://cwe.mitre.org/data/definitions/19.html", "label_name": "vulnerable"} {"code": "static inline void arch_dup_mmap(struct mm_struct *oldmm,\n\t\t\t\t struct mm_struct *mm)\n{\n\tif (oldmm->context.asce_limit < mm->context.asce_limit)\n\t\tcrst_table_downgrade(mm, oldmm->context.asce_limit);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "void arch_pick_mmap_layout(struct mm_struct *mm)\n{\n\tunsigned long random_factor = 0UL;\n\n\tif (current->flags & PF_RANDOMIZE)\n\t\trandom_factor = arch_mmap_rnd();\n\n\tmm->mmap_legacy_base = mmap_legacy_base(random_factor);\n\n\tif (mmap_is_legacy()) {\n\t\tmm->mmap_base = mm->mmap_legacy_base;\n\t\tmm->get_unmapped_area = arch_get_unmapped_area;\n\t} else {\n\t\tmm->mmap_base = mmap_base(random_factor);\n\t\tmm->get_unmapped_area = arch_get_unmapped_area_topdown;\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-254", "cwe_name": "7PK - Security Features", "description": "Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.", "url": "https://cwe.mitre.org/data/definitions/254.html", "label_name": "vulnerable"} {"code": "void ion_free(struct ion_client *client, struct ion_handle *handle)\n{\n\tbool valid_handle;\n\n\tBUG_ON(client != handle->client);\n\n\tmutex_lock(&client->lock);\n\tvalid_handle = ion_handle_validate(client, handle);\n\n\tif (!valid_handle) {\n\t\tWARN(1, \"%s: invalid handle passed to free.\\n\", __func__);\n\t\tmutex_unlock(&client->lock);\n\t\treturn;\n\t}\n\tmutex_unlock(&client->lock);\n\tion_handle_put(handle);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static inline bool unconditional(const struct arpt_arp *arp)\n{\n\tstatic const struct arpt_arp uncond;\n\n\treturn memcmp(arp, &uncond, sizeof(uncond)) == 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static bool check_underflow(const struct ipt_entry *e)\n{\n\tconst struct xt_entry_target *t;\n\tunsigned int verdict;\n\n\tif (!unconditional(&e->ip))\n\t\treturn false;\n\tt = ipt_get_target_c(e);\n\tif (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)\n\t\treturn false;\n\tverdict = ((struct xt_standard_target *)t)->verdict;\n\tverdict = -verdict - 1;\n\treturn verdict == NF_DROP || verdict == NF_ACCEPT;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e,\n\t\t const char *hookname, const char **chainname,\n\t\t const char **comment, unsigned int *rulenum)\n{\n\tconst struct xt_standard_target *t = (void *)ipt_get_target_c(s);\n\n\tif (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {\n\t\t/* Head of user chain: ERROR target with chainname */\n\t\t*chainname = t->target.data;\n\t\t(*rulenum) = 0;\n\t} else if (s == e) {\n\t\t(*rulenum)++;\n\n\t\tif (s->target_offset == sizeof(struct ipt_entry) &&\n\t\t strcmp(t->target.u.kernel.target->name,\n\t\t\t XT_STANDARD_TARGET) == 0 &&\n\t\t t->verdict < 0 &&\n\t\t unconditional(&s->ip)) {\n\t\t\t/* Tail of chains: STANDARD target (return/policy) */\n\t\t\t*comment = *chainname == hookname\n\t\t\t\t? comments[NF_IP_TRACE_COMMENT_POLICY]\n\t\t\t\t: comments[NF_IP_TRACE_COMMENT_RETURN];\n\t\t}\n\t\treturn 1;\n\t} else\n\t\t(*rulenum)++;\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static bool check_underflow(const struct ip6t_entry *e)\n{\n\tconst struct xt_entry_target *t;\n\tunsigned int verdict;\n\n\tif (!unconditional(&e->ipv6))\n\t\treturn false;\n\tt = ip6t_get_target_c(e);\n\tif (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)\n\t\treturn false;\n\tverdict = ((struct xt_standard_target *)t)->verdict;\n\tverdict = -verdict - 1;\n\treturn verdict == NF_DROP || verdict == NF_ACCEPT;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)\n{\n\tstruct snd_pcm_runtime *runtime;\n\tunsigned long flags;\n\n\tif (PCM_RUNTIME_CHECK(substream))\n\t\treturn;\n\truntime = substream->runtime;\n\n\tsnd_pcm_stream_lock_irqsave(substream, flags);\n\tif (!snd_pcm_running(substream) ||\n\t snd_pcm_update_hw_ptr0(substream, 1) < 0)\n\t\tgoto _end;\n\n#ifdef CONFIG_SND_PCM_TIMER\n\tif (substream->timer_running)\n\t\tsnd_timer_interrupt(substream->timer, 1);\n#endif\n _end:\n\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n\tkill_fasync(&runtime->fasync, SIGIO, POLL_IN);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "int vfs_open(const struct path *path, struct file *file,\n\t const struct cred *cred)\n{\n\tstruct dentry *dentry = path->dentry;\n\tstruct inode *inode = dentry->d_inode;\n\n\tfile->f_path = *path;\n\tif (dentry->d_flags & DCACHE_OP_SELECT_INODE) {\n\t\tinode = dentry->d_op->d_select_inode(dentry, file->f_flags);\n\t\tif (IS_ERR(inode))\n\t\t\treturn PTR_ERR(inode);\n\t}\n\n\treturn do_dentry_open(file, inode, NULL, cred);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-284", "cwe_name": "Improper Access Control", "description": "The software does not restrict or incorrectly restricts access to a resource from an unauthorized actor.", "url": "https://cwe.mitre.org/data/definitions/284.html", "label_name": "vulnerable"} {"code": "static int __init big_key_crypto_init(void)\n{\n\tint ret = -EINVAL;\n\n\t/* init RNG */\n\tbig_key_rng = crypto_alloc_rng(big_key_rng_name, 0, 0);\n\tif (IS_ERR(big_key_rng)) {\n\t\tbig_key_rng = NULL;\n\t\treturn -EFAULT;\n\t}\n\n\t/* seed RNG */\n\tret = crypto_rng_reset(big_key_rng, NULL, crypto_rng_seedsize(big_key_rng));\n\tif (ret)\n\t\tgoto error;\n\n\t/* init block cipher */\n\tbig_key_skcipher = crypto_alloc_skcipher(big_key_alg_name,\n\t\t\t\t\t\t 0, CRYPTO_ALG_ASYNC);\n\tif (IS_ERR(big_key_skcipher)) {\n\t\tbig_key_skcipher = NULL;\n\t\tret = -EFAULT;\n\t\tgoto error;\n\t}\n\n\treturn 0;\n\nerror:\n\tcrypto_free_rng(big_key_rng);\n\tbig_key_rng = NULL;\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static void fwnet_receive_broadcast(struct fw_iso_context *context,\n\t\tu32 cycle, size_t header_length, void *header, void *data)\n{\n\tstruct fwnet_device *dev;\n\tstruct fw_iso_packet packet;\n\t__be16 *hdr_ptr;\n\t__be32 *buf_ptr;\n\tint retval;\n\tu32 length;\n\tu16 source_node_id;\n\tu32 specifier_id;\n\tu32 ver;\n\tunsigned long offset;\n\tunsigned long flags;\n\n\tdev = data;\n\thdr_ptr = header;\n\tlength = be16_to_cpup(hdr_ptr);\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\n\toffset = dev->rcv_buffer_size * dev->broadcast_rcv_next_ptr;\n\tbuf_ptr = dev->broadcast_rcv_buffer_ptrs[dev->broadcast_rcv_next_ptr++];\n\tif (dev->broadcast_rcv_next_ptr == dev->num_broadcast_rcv_ptrs)\n\t\tdev->broadcast_rcv_next_ptr = 0;\n\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\n\tspecifier_id = (be32_to_cpu(buf_ptr[0]) & 0xffff) << 8\n\t\t\t| (be32_to_cpu(buf_ptr[1]) & 0xff000000) >> 24;\n\tver = be32_to_cpu(buf_ptr[1]) & 0xffffff;\n\tsource_node_id = be32_to_cpu(buf_ptr[0]) >> 16;\n\n\tif (specifier_id == IANA_SPECIFIER_ID &&\n\t (ver == RFC2734_SW_VERSION\n#if IS_ENABLED(CONFIG_IPV6)\n\t || ver == RFC3146_SW_VERSION\n#endif\n\t )) {\n\t\tbuf_ptr += 2;\n\t\tlength -= IEEE1394_GASP_HDR_SIZE;\n\t\tfwnet_incoming_packet(dev, buf_ptr, length, source_node_id,\n\t\t\t\t context->card->generation, true);\n\t}\n\n\tpacket.payload_length = dev->rcv_buffer_size;\n\tpacket.interrupt = 1;\n\tpacket.skip = 0;\n\tpacket.tag = 3;\n\tpacket.sy = 0;\n\tpacket.header_length = IEEE1394_GASP_HDR_SIZE;\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\n\tretval = fw_iso_context_queue(dev->broadcast_rcv_context, &packet,\n\t\t\t\t &dev->broadcast_rcv_buffer, offset);\n\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\n\tif (retval >= 0)\n\t\tfw_iso_context_queue_flush(dev->broadcast_rcv_context);\n\telse\n\t\tdev_err(&dev->netdev->dev, \"requeue failed\\n\");\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np)\n{\n\tstruct platform_device *pdev = cqspi->pdev;\n\tstruct device *dev = &pdev->dev;\n\tstruct cqspi_flash_pdata *f_pdata;\n\tstruct spi_nor *nor;\n\tstruct mtd_info *mtd;\n\tunsigned int cs;\n\tint i, ret;\n\n\t/* Get flash device data */\n\tfor_each_available_child_of_node(dev->of_node, np) {\n\t\tif (of_property_read_u32(np, \"reg\", &cs)) {\n\t\t\tdev_err(dev, \"Couldn't determine chip select.\\n\");\n\t\t\tgoto err;\n\t\t}\n\n\t\tif (cs > CQSPI_MAX_CHIPSELECT) {\n\t\t\tdev_err(dev, \"Chip select %d out of range.\\n\", cs);\n\t\t\tgoto err;\n\t\t}\n\n\t\tf_pdata = &cqspi->f_pdata[cs];\n\t\tf_pdata->cqspi = cqspi;\n\t\tf_pdata->cs = cs;\n\n\t\tret = cqspi_of_get_flash_pdata(pdev, f_pdata, np);\n\t\tif (ret)\n\t\t\tgoto err;\n\n\t\tnor = &f_pdata->nor;\n\t\tmtd = &nor->mtd;\n\n\t\tmtd->priv = nor;\n\n\t\tnor->dev = dev;\n\t\tspi_nor_set_flash_node(nor, np);\n\t\tnor->priv = f_pdata;\n\n\t\tnor->read_reg = cqspi_read_reg;\n\t\tnor->write_reg = cqspi_write_reg;\n\t\tnor->read = cqspi_read;\n\t\tnor->write = cqspi_write;\n\t\tnor->erase = cqspi_erase;\n\t\tnor->prepare = cqspi_prep;\n\t\tnor->unprepare = cqspi_unprep;\n\n\t\tmtd->name = devm_kasprintf(dev, GFP_KERNEL, \"%s.%d\",\n\t\t\t\t\t dev_name(dev), cs);\n\t\tif (!mtd->name) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto err;\n\t\t}\n\n\t\tret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD);\n\t\tif (ret)\n\t\t\tgoto err;\n\n\t\tret = mtd_device_register(mtd, NULL, 0);\n\t\tif (ret)\n\t\t\tgoto err;\n\n\t\tf_pdata->registered = true;\n\t}\n\n\treturn 0;\n\nerr:\n\tfor (i = 0; i < CQSPI_MAX_CHIPSELECT; i++)\n\t\tif (cqspi->f_pdata[i].registered)\n\t\t\tmtd_device_unregister(&cqspi->f_pdata[i].nor.mtd);\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)\n{\n\tint rc = 0;\n\tstruct cifs_ses *ses = sess_data->ses;\n\n\tmutex_lock(&ses->server->srv_mutex);\n\tif (ses->server->sign && ses->server->ops->generate_signingkey) {\n\t\trc = ses->server->ops->generate_signingkey(ses);\n\t\tkfree(ses->auth_key.response);\n\t\tses->auth_key.response = NULL;\n\t\tif (rc) {\n\t\t\tcifs_dbg(FYI,\n\t\t\t\t\"SMB3 session key generation failed\\n\");\n\t\t\tmutex_unlock(&ses->server->srv_mutex);\n\t\t\tgoto keygen_exit;\n\t\t}\n\t}\n\tif (!ses->server->session_estab) {\n\t\tses->server->sequence_number = 0x2;\n\t\tses->server->session_estab = true;\n\t}\n\tmutex_unlock(&ses->server->srv_mutex);\n\n\tcifs_dbg(FYI, \"SMB2/3 session established successfully\\n\");\n\tspin_lock(&GlobalMid_Lock);\n\tses->status = CifsGood;\n\tses->need_reconnect = false;\n\tspin_unlock(&GlobalMid_Lock);\n\nkeygen_exit:\n\tif (!ses->server->sign) {\n\t\tkfree(ses->auth_key.response);\n\t\tses->auth_key.response = NULL;\n\t}\n\treturn rc;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data)\n{\n\tint ret;\n\n\tret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0),\n\t\t\t PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0,\n\t\t\t indx, data, size, 100);\n\tif (ret < 0)\n\t\tnetif_dbg(pegasus, drv, pegasus->net,\n\t\t\t \"%s returned %d\\n\", __func__, ret);\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)\n{\n\treturn usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),\n\t\t\t RTL8150_REQ_GET_REGS, RTL8150_REQT_READ,\n\t\t\t indx, 0, data, size, 500);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void timerfd_remove_cancel(struct timerfd_ctx *ctx)\n{\n\tif (ctx->might_cancel) {\n\t\tctx->might_cancel = false;\n\t\tspin_lock(&cancel_lock);\n\t\tlist_del_rcu(&ctx->clist);\n\t\tspin_unlock(&cancel_lock);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static int su3000_frontend_attach(struct dvb_usb_adapter *d)\n{\n\tu8 obuf[3] = { 0xe, 0x80, 0 };\n\tu8 ibuf[] = { 0 };\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x0e transfer failed.\");\n\n\tobuf[0] = 0xe;\n\tobuf[1] = 0x02;\n\tobuf[2] = 1;\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x0e transfer failed.\");\n\tmsleep(300);\n\n\tobuf[0] = 0xe;\n\tobuf[1] = 0x83;\n\tobuf[2] = 0;\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x0e transfer failed.\");\n\n\tobuf[0] = 0xe;\n\tobuf[1] = 0x83;\n\tobuf[2] = 1;\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x0e transfer failed.\");\n\n\tobuf[0] = 0x51;\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x51 transfer failed.\");\n\n\td->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config,\n\t\t\t\t\t&d->dev->i2c_adap);\n\tif (d->fe_adap[0].fe == NULL)\n\t\treturn -EIO;\n\n\tif (dvb_attach(ts2020_attach, d->fe_adap[0].fe,\n\t\t\t\t&dw2104_ts2020_config,\n\t\t\t\t&d->dev->i2c_adap)) {\n\t\tinfo(\"Attached DS3000/TS2020!\");\n\t\treturn 0;\n\t}\n\n\tinfo(\"Failed to attach DS3000/TS2020!\");\n\treturn -EIO;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "int usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type)\n{\n\tstruct hexline *hx;\n\tu8 reset;\n\tint ret,pos=0;\n\n\thx = kmalloc(sizeof(*hx), GFP_KERNEL);\n\tif (!hx)\n\t\treturn -ENOMEM;\n\n\t/* stop the CPU */\n\treset = 1;\n\tif ((ret = usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1)) != 1)\n\t\terr(\"could not stop the USB controller CPU.\");\n\n\twhile ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) {\n\t\tdeb_fw(\"writing to address 0x%04x (buffer: 0x%02x %02x)\\n\", hx->addr, hx->len, hx->chk);\n\t\tret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len);\n\n\t\tif (ret != hx->len) {\n\t\t\terr(\"error while transferring firmware (transferred size: %d, block size: %d)\",\n\t\t\t\tret, hx->len);\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (ret < 0) {\n\t\terr(\"firmware download failed at %d with %d\",pos,ret);\n\t\tkfree(hx);\n\t\treturn ret;\n\t}\n\n\tif (ret == 0) {\n\t\t/* restart the CPU */\n\t\treset = 0;\n\t\tif (ret || usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1) != 1) {\n\t\t\terr(\"could not restart the USB controller CPU.\");\n\t\t\tret = -EINVAL;\n\t\t}\n\t} else\n\t\tret = -EIO;\n\n\tkfree(hx);\n\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "\nvoid skb_complete_tx_timestamp(struct sk_buff *skb,\n\t\t\t struct skb_shared_hwtstamps *hwtstamps)\n{\n\tstruct sock *sk = skb->sk;\n\n\tif (!skb_may_tx_timestamp(sk, false))\n\t\treturn;\n\n\t/* Take a reference to prevent skb_orphan() from freeing the socket,\n\t * but only if the socket refcount is not zero.\n\t */\n\tif (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {\n\t\t*skb_hwtstamps(skb) = *hwtstamps;\n\t\t__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);\n\t\tsock_put(sk);\n\t}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "\nstatic void __skb_complete_tx_timestamp(struct sk_buff *skb,\n\t\t\t\t\tstruct sock *sk,\n\t\t\t\t\tint tstype)\n{\n\tstruct sock_exterr_skb *serr;\n\tint err;\n\n\tserr = SKB_EXT_ERR(skb);\n\tmemset(serr, 0, sizeof(*serr));\n\tserr->ee.ee_errno = ENOMSG;\n\tserr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;\n\tserr->ee.ee_info = tstype;\n\tif (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {\n\t\tserr->ee.ee_data = skb_shinfo(skb)->tskey;\n\t\tif (sk->sk_protocol == IPPROTO_TCP &&\n\t\t sk->sk_type == SOCK_STREAM)\n\t\t\tserr->ee.ee_data -= sk->sk_tskey;\n\t}\n\n\terr = sock_queue_err_skb(sk, skb);\n\n\tif (err)\n\t\tkfree_skb(skb);", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "void ping_unhash(struct sock *sk)\n{\n\tstruct inet_sock *isk = inet_sk(sk);\n\tpr_debug(\"ping_unhash(isk=%p,isk->num=%u)\\n\", isk, isk->inet_num);\n\tif (sk_hashed(sk)) {\n\t\twrite_lock_bh(&ping_table.lock);\n\t\thlist_nulls_del(&sk->sk_nulls_node);\n\t\tsk_nulls_node_init(&sk->sk_nulls_node);\n\t\tsock_put(sk);\n\t\tisk->inet_num = 0;\n\t\tisk->inet_sport = 0;\n\t\tsock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);\n\t\twrite_unlock_bh(&ping_table.lock);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "static void i8042_stop(struct serio *serio)\n{\n\tstruct i8042_port *port = serio->port_data;\n\n\tport->exists = false;\n\n\t/*\n\t * We synchronize with both AUX and KBD IRQs because there is\n\t * a (very unlikely) chance that AUX IRQ is raised for KBD port\n\t * and vice versa.\n\t */\n\tsynchronize_irq(I8042_AUX_IRQ);\n\tsynchronize_irq(I8042_KBD_IRQ);\n\tport->serio = NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)\n{\n\tu16 offset = sizeof(struct ipv6hdr);\n\tunsigned int packet_len = skb_tail_pointer(skb) -\n\t\tskb_network_header(skb);\n\tint found_rhdr = 0;\n\t*nexthdr = &ipv6_hdr(skb)->nexthdr;\n\n\twhile (offset <= packet_len) {\n\t\tstruct ipv6_opt_hdr *exthdr;\n\n\t\tswitch (**nexthdr) {\n\n\t\tcase NEXTHDR_HOP:\n\t\t\tbreak;\n\t\tcase NEXTHDR_ROUTING:\n\t\t\tfound_rhdr = 1;\n\t\t\tbreak;\n\t\tcase NEXTHDR_DEST:\n#if IS_ENABLED(CONFIG_IPV6_MIP6)\n\t\t\tif (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)\n\t\t\t\tbreak;\n#endif\n\t\t\tif (found_rhdr)\n\t\t\t\treturn offset;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn offset;\n\t\t}\n\n\t\tif (offset + sizeof(struct ipv6_opt_hdr) > packet_len)\n\t\t\treturn -EINVAL;\n\n\t\texthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +\n\t\t\t\t\t\t offset);\n\t\toffset += ipv6_optlen(exthdr);\n\t\t*nexthdr = &exthdr->nexthdr;\n\t}\n\n\treturn -EINVAL;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)\n{\n\t__u64 start = F2FS_BYTES_TO_BLK(range->start);\n\t__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;\n\tunsigned int start_segno, end_segno;\n\tstruct cp_control cpc;\n\tint err = 0;\n\n\tif (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)\n\t\treturn -EINVAL;\n\n\tcpc.trimmed = 0;\n\tif (end <= MAIN_BLKADDR(sbi))\n\t\tgoto out;\n\n\tif (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {\n\t\tf2fs_msg(sbi->sb, KERN_WARNING,\n\t\t\t\"Found FS corruption, run fsck to fix.\");\n\t\tgoto out;\n\t}\n\n\t/* start/end segment number in main_area */\n\tstart_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);\n\tend_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :\n\t\t\t\t\t\tGET_SEGNO(sbi, end);\n\tcpc.reason = CP_DISCARD;\n\tcpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));\n\n\t/* do checkpoint to issue discard commands safely */\n\tfor (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {\n\t\tcpc.trim_start = start_segno;\n\n\t\tif (sbi->discard_blks == 0)\n\t\t\tbreak;\n\t\telse if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))\n\t\t\tcpc.trim_end = end_segno;\n\t\telse\n\t\t\tcpc.trim_end = min_t(unsigned int,\n\t\t\t\trounddown(start_segno +\n\t\t\t\tBATCHED_TRIM_SEGMENTS(sbi),\n\t\t\t\tsbi->segs_per_sec) - 1, end_segno);\n\n\t\tmutex_lock(&sbi->gc_mutex);\n\t\terr = write_checkpoint(sbi, &cpc);\n\t\tmutex_unlock(&sbi->gc_mutex);\n\t\tif (err)\n\t\t\tbreak;\n\n\t\tschedule();\n\t}\n\t/* It's time to issue all the filed discards */\n\tmark_discard_range_all(sbi);\n\tf2fs_wait_discard_bios(sbi);\nout:\n\trange->len = F2FS_BLK_TO_BYTES(cpc.trimmed);\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static const struct usb_cdc_union_desc *\nims_pcu_get_cdc_union_desc(struct usb_interface *intf)\n{\n\tconst void *buf = intf->altsetting->extra;\n\tsize_t buflen = intf->altsetting->extralen;\n\tstruct usb_cdc_union_desc *union_desc;\n\n\tif (!buf) {\n\t\tdev_err(&intf->dev, \"Missing descriptor data\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (!buflen) {\n\t\tdev_err(&intf->dev, \"Zero length descriptor\\n\");\n\t\treturn NULL;\n\t}\n\n\twhile (buflen > 0) {\n\t\tunion_desc = (struct usb_cdc_union_desc *)buf;\n\n\t\tif (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&\n\t\t union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {\n\t\t\tdev_dbg(&intf->dev, \"Found union header\\n\");\n\t\t\treturn union_desc;\n\t\t}\n\n\t\tbuflen -= union_desc->bLength;\n\t\tbuf += union_desc->bLength;\n\t}\n\n\tdev_err(&intf->dev, \"Missing CDC union descriptor\\n\");\n\treturn NULL;", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)\n{\n\tstruct net *net = sock_net(skb->sk);\n\tstruct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];\n\tstruct xfrm_dump_info info;\n\n\tBUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >\n\t\t sizeof(cb->args) - sizeof(cb->args[0]));\n\n\tinfo.in_skb = cb->skb;\n\tinfo.out_skb = skb;\n\tinfo.nlmsg_seq = cb->nlh->nlmsg_seq;\n\tinfo.nlmsg_flags = NLM_F_MULTI;\n\n\tif (!cb->args[0]) {\n\t\tcb->args[0] = 1;\n\t\txfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);\n\t}\n\n\t(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);\n\n\treturn skb->len;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static struct pid *good_sigevent(sigevent_t * event)\n{\n\tstruct task_struct *rtn = current->group_leader;\n\n\tif ((event->sigev_notify & SIGEV_THREAD_ID ) &&\n\t\t(!(rtn = find_task_by_vpid(event->sigev_notify_thread_id)) ||\n\t\t !same_thread_group(rtn, current) ||\n\t\t (event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_SIGNAL))\n\t\treturn NULL;\n\n\tif (((event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE) &&\n\t ((event->sigev_signo <= 0) || (event->sigev_signo > SIGRTMAX)))\n\t\treturn NULL;\n\n\treturn task_pid(rtn);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "evtchn_port_t evtchn_from_irq(unsigned irq)\n{\n\tif (WARN(irq >= nr_irqs, \"Invalid irq %d!\\n\", irq))\n\t\treturn 0;\n\n\treturn info_for_irq(irq)->evtchn;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "unsigned long perf_instruction_pointer(struct pt_regs *regs)\n{\n\tbool use_siar = regs_use_siar(regs);\n\tunsigned long siar = mfspr(SPRN_SIAR);\n\n\tif (ppmu->flags & PPMU_P10_DD1) {\n\t\tif (siar)\n\t\t\treturn siar;\n\t\telse\n\t\t\treturn regs->nip;\n\t} else if (use_siar && siar_valid(regs))\n\t\treturn mfspr(SPRN_SIAR) + perf_ip_adjust(regs);\n\telse if (use_siar)\n\t\treturn 0;\t\t// no valid instruction pointer\n\telse\n\t\treturn regs->nip;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static struct port_buffer *get_inbuf(struct port *port)\n{\n\tstruct port_buffer *buf;\n\tunsigned int len;\n\n\tif (port->inbuf)\n\t\treturn port->inbuf;\n\n\tbuf = virtqueue_get_buf(port->in_vq, &len);\n\tif (buf) {\n\t\tbuf->len = len;\n\t\tbuf->offset = 0;\n\t\tport->stats.bytes_received += len;\n\t}\n\treturn buf;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "nfs4_file_open(struct inode *inode, struct file *filp)\n{\n\tstruct nfs_open_context *ctx;\n\tstruct dentry *dentry = file_dentry(filp);\n\tstruct dentry *parent = NULL;\n\tstruct inode *dir;\n\tunsigned openflags = filp->f_flags;\n\tstruct iattr attr;\n\tint err;\n\n\t/*\n\t * If no cached dentry exists or if it's negative, NFSv4 handled the\n\t * opens in ->lookup() or ->create().\n\t *\n\t * We only get this far for a cached positive dentry. We skipped\n\t * revalidation, so handle it here by dropping the dentry and returning\n\t * -EOPENSTALE. The VFS will retry the lookup/create/open.\n\t */\n\n\tdprintk(\"NFS: open file(%pd2)\\n\", dentry);\n\n\terr = nfs_check_flags(openflags);\n\tif (err)\n\t\treturn err;\n\n\tif ((openflags & O_ACCMODE) == 3)\n\t\treturn nfs_open(inode, filp);\n\n\t/* We can't create new files here */\n\topenflags &= ~(O_CREAT|O_EXCL);\n\n\tparent = dget_parent(dentry);\n\tdir = d_inode(parent);\n\n\tctx = alloc_nfs_open_context(file_dentry(filp), filp->f_mode, filp);\n\terr = PTR_ERR(ctx);\n\tif (IS_ERR(ctx))\n\t\tgoto out;\n\n\tattr.ia_valid = ATTR_OPEN;\n\tif (openflags & O_TRUNC) {\n\t\tattr.ia_valid |= ATTR_SIZE;\n\t\tattr.ia_size = 0;\n\t\tfilemap_write_and_wait(inode->i_mapping);\n\t}\n\n\tinode = NFS_PROTO(dir)->open_context(dir, ctx, openflags, &attr, NULL);\n\tif (IS_ERR(inode)) {\n\t\terr = PTR_ERR(inode);\n\t\tswitch (err) {\n\t\tdefault:\n\t\t\tgoto out_put_ctx;\n\t\tcase -ENOENT:\n\t\tcase -ESTALE:\n\t\tcase -EISDIR:\n\t\tcase -ENOTDIR:\n\t\tcase -ELOOP:\n\t\t\tgoto out_drop;\n\t\t}\n\t}\n\tif (inode != d_inode(dentry))\n\t\tgoto out_drop;\n\n\tnfs_file_set_open_context(filp, ctx);\n\tnfs_fscache_open_file(inode, filp);\n\terr = 0;\n\nout_put_ctx:\n\tput_nfs_open_context(ctx);\nout:\n\tdput(parent);\n\treturn err;\n\nout_drop:\n\td_drop(dentry);\n\terr = -EOPENSTALE;\n\tgoto out_put_ctx;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-909", "cwe_name": "Missing Initialization of Resource", "description": "The software does not initialize a critical resource.", "url": "https://cwe.mitre.org/data/definitions/909.html", "label_name": "vulnerable"} {"code": "void rose_stop_timer(struct sock *sk)\n{\n\tdel_timer(&rose_sk(sk)->timer);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "void rose_stop_idletimer(struct sock *sk)\n{\n\tdel_timer(&rose_sk(sk)->idletimer);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "void jiffies_to_timeval(const unsigned long jiffies, struct timeval *value)\n{\n\t/*\n\t * Convert jiffies to nanoseconds and separate with\n\t * one divide.\n\t */\n\tu64 nsec = (u64)jiffies * TICK_NSEC;\n\tlong tv_usec;\n\n\tvalue->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tv_usec);\n\ttv_usec /= NSEC_PER_USEC;\n\tvalue->tv_usec = tv_usec;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-189", "cwe_name": "Numeric Errors", "description": "Weaknesses in this category are related to improper calculation or conversion of numbers.", "url": "https://cwe.mitre.org/data/definitions/189.html", "label_name": "vulnerable"} {"code": "static struct nfs4_opendata *nfs4_opendata_alloc(struct path *path,\n\t\tstruct nfs4_state_owner *sp, int flags,\n\t\tconst struct iattr *attrs)\n{\n\tstruct dentry *parent = dget_parent(path->dentry);\n\tstruct inode *dir = parent->d_inode;\n\tstruct nfs_server *server = NFS_SERVER(dir);\n\tstruct nfs4_opendata *p;\n\n\tp = kzalloc(sizeof(*p), GFP_KERNEL);\n\tif (p == NULL)\n\t\tgoto err;\n\tp->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid);\n\tif (p->o_arg.seqid == NULL)\n\t\tgoto err_free;\n\tp->path.mnt = mntget(path->mnt);\n\tp->path.dentry = dget(path->dentry);\n\tp->dir = parent;\n\tp->owner = sp;\n\tatomic_inc(&sp->so_count);\n\tp->o_arg.fh = NFS_FH(dir);\n\tp->o_arg.open_flags = flags,\n\tp->o_arg.clientid = server->nfs_client->cl_clientid;\n\tp->o_arg.id = sp->so_owner_id.id;\n\tp->o_arg.name = &p->path.dentry->d_name;\n\tp->o_arg.server = server;\n\tp->o_arg.bitmask = server->attr_bitmask;\n\tp->o_arg.claim = NFS4_OPEN_CLAIM_NULL;\n\tif (flags & O_EXCL) {\n\t\tu32 *s = (u32 *) p->o_arg.u.verifier.data;\n\t\ts[0] = jiffies;\n\t\ts[1] = current->pid;\n\t} else if (flags & O_CREAT) {\n\t\tp->o_arg.u.attrs = &p->attrs;\n\t\tmemcpy(&p->attrs, attrs, sizeof(p->attrs));\n\t}\n\tp->c_arg.fh = &p->o_res.fh;\n\tp->c_arg.stateid = &p->o_res.stateid;\n\tp->c_arg.seqid = p->o_arg.seqid;\n\tnfs4_init_opendata_res(p);\n\tkref_init(&p->kref);\n\treturn p;\nerr_free:\n\tkfree(p);\nerr:\n\tdput(parent);\n\treturn NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "static void nfs4_return_incompatible_delegation(struct inode *inode, mode_t open_flags)\n{\n\tstruct nfs_delegation *delegation;\n\n\trcu_read_lock();\n\tdelegation = rcu_dereference(NFS_I(inode)->delegation);\n\tif (delegation == NULL || (delegation->type & open_flags) == open_flags) {\n\t\trcu_read_unlock();\n\t\treturn;\n\t}\n\trcu_read_unlock();\n\tnfs_inode_return_delegation(inode);\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)\n{\n\tstruct nfs_delegation *delegation;\n\tstruct nfs4_opendata *opendata;\n\tint delegation_type = 0;\n\tint status;\n\n\topendata = nfs4_open_recoverdata_alloc(ctx, state);\n\tif (IS_ERR(opendata))\n\t\treturn PTR_ERR(opendata);\n\topendata->o_arg.claim = NFS4_OPEN_CLAIM_PREVIOUS;\n\topendata->o_arg.fh = NFS_FH(state->inode);\n\trcu_read_lock();\n\tdelegation = rcu_dereference(NFS_I(state->inode)->delegation);\n\tif (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0)\n\t\tdelegation_type = delegation->type;\n\trcu_read_unlock();\n\topendata->o_arg.u.delegation_type = delegation_type;\n\tstatus = nfs4_open_recover(opendata, state);\n\tnfs4_opendata_put(opendata);\n\treturn status;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg)\n{\n\t__be32 *p;\n\n\tRESERVE_SPACE(4+NFS4_STATEID_SIZE+4);\n\tWRITE32(OP_OPEN_DOWNGRADE);\n\tWRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE);\n\tWRITE32(arg->seqid->sequence->counter);\n\tencode_share_access(xdr, arg->open_flags);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data)\n{\n\tstruct l2cap_conf_rsp *rsp = (struct l2cap_conf_rsp *)data;\n\tu16 scid, flags, result;\n\tstruct sock *sk;\n\n\tscid = __le16_to_cpu(rsp->scid);\n\tflags = __le16_to_cpu(rsp->flags);\n\tresult = __le16_to_cpu(rsp->result);\n\n\tBT_DBG(\"scid 0x%4.4x flags 0x%2.2x result 0x%2.2x\",\n\t\t\tscid, flags, result);\n\n\tsk = l2cap_get_chan_by_scid(&conn->chan_list, scid);\n\tif (!sk)\n\t\treturn 0;\n\n\tswitch (result) {\n\tcase L2CAP_CONF_SUCCESS:\n\t\tbreak;\n\n\tcase L2CAP_CONF_UNACCEPT:\n\t\tif (++l2cap_pi(sk)->conf_retry < L2CAP_CONF_MAX_RETRIES) {\n\t\t\tchar req[128];\n\t\t\t/* It does not make sense to adjust L2CAP parameters\n\t\t\t * that are currently defined in the spec. We simply\n\t\t\t * resend config request that we sent earlier. It is\n\t\t\t * stupid, but it helps qualification testing which\n\t\t\t * expects at least some response from us. */\n\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n\t\t\t\t\t\tl2cap_build_conf_req(sk, req), req);\n\t\t\tgoto done;\n\t\t}\n\n\tdefault:\n\t\tsk->sk_state = BT_DISCONN;\n\t\tsk->sk_err = ECONNRESET;\n\t\tl2cap_sock_set_timer(sk, HZ * 5);\n\t\t{\n\t\t\tstruct l2cap_disconn_req req;\n\t\t\treq.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);\n\t\t\treq.scid = cpu_to_le16(l2cap_pi(sk)->scid);\n\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n\t\t\t\t\tL2CAP_DISCONN_REQ, sizeof(req), &req);\n\t\t}\n\t\tgoto done;\n\t}\n\n\tif (flags & 0x01)\n\t\tgoto done;\n\n\tl2cap_pi(sk)->conf_state |= L2CAP_CONF_INPUT_DONE;\n\n\tif (l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE) {\n\t\tsk->sk_state = BT_CONNECTED;\n\t\tl2cap_chan_ready(sk);\n\t}\n\ndone:\n\tbh_unlock_sock(sk);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "static void __exit ipgre_fini(void)\n{\n\trtnl_link_unregister(&ipgre_tap_ops);\n\trtnl_link_unregister(&ipgre_link_ops);\n\tunregister_pernet_device(&ipgre_net_ops);\n\tif (inet_del_protocol(&ipgre_protocol, IPPROTO_GRE) < 0)\n\t\tprintk(KERN_INFO \"ipgre close: can't remove protocol\\n\");\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,\n\t\t\t ssize_t size, void *private)\n{\n ext4_io_end_t *io_end = iocb->private;\n\tstruct workqueue_struct *wq;\n\n\t/* if not async direct IO or dio with 0 bytes write, just return */\n\tif (!io_end || !size)\n\t\treturn;\n\n\text_debug(\"ext4_end_io_dio(): io_end 0x%p\"\n\t\t \"for inode %lu, iocb 0x%p, offset %llu, size %llu\\n\",\n \t\t iocb->private, io_end->inode->i_ino, iocb, offset,\n\t\t size);\n\n\t/* if not aio dio with unwritten extents, just free io and return */\n\tif (io_end->flag != EXT4_IO_UNWRITTEN){\n\t\text4_free_io_end(io_end);\n\t\tiocb->private = NULL;\n\t\treturn;\n\t}\n\n\tio_end->offset = offset;\n\tio_end->size = size;\n\twq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;\n\n\t/* queue the work to convert unwritten extents to written */\n\tqueue_work(wq, &io_end->work);\n\n\t/* Add the io_end to per-inode completed aio dio list*/\n\tlist_add_tail(&io_end->list,\n\t\t &EXT4_I(io_end->inode)->i_completed_io_list);\n\tiocb->private = NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,\n\t\tunsigned long arg)\n{\n\tstruct sem_undo *un;\n\tstruct sem_array *sma;\n\tstruct sem* curr;\n\tint err;\n\tint nsems;\n\tstruct list_head tasks;\n\tint val;\n#if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)\n\t/* big-endian 64bit */\n\tval = arg >> 32;\n#else\n\t/* 32bit or little-endian 64bit */\n\tval = arg;\n#endif\n\n\tsma = sem_lock_check(ns, semid);\n\tif (IS_ERR(sma))\n\t\treturn PTR_ERR(sma);\n\n\tINIT_LIST_HEAD(&tasks);\n\tnsems = sma->sem_nsems;\n\n\terr = -EACCES;\n\tif (ipcperms(ns, &sma->sem_perm, S_IWUGO))\n\t\tgoto out_unlock;\n\n\terr = security_sem_semctl(sma, SETVAL);\n\tif (err)\n\t\tgoto out_unlock;\n\n\terr = -EINVAL;\n\tif(semnum < 0 || semnum >= nsems)\n\t\tgoto out_unlock;\n\n\tcurr = &sma->sem_base[semnum];\n\n\terr = -ERANGE;\n\tif (val > SEMVMX || val < 0)\n\t\tgoto out_unlock;\n\n\tassert_spin_locked(&sma->sem_perm.lock);\n\tlist_for_each_entry(un, &sma->list_id, list_id)\n\t\tun->semadj[semnum] = 0;\n\n\tcurr->semval = val;\n\tcurr->sempid = task_tgid_vnr(current);\n\tsma->sem_ctime = get_seconds();\n\t/* maybe some queued-up processes were waiting for this */\n\tdo_smart_update(sma, NULL, 0, 0, &tasks);\n\terr = 0;\nout_unlock:\n\tsem_unlock(sma);\n\twake_up_sem_queue_do(&tasks);\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-189", "cwe_name": "Numeric Errors", "description": "Weaknesses in this category are related to improper calculation or conversion of numbers.", "url": "https://cwe.mitre.org/data/definitions/189.html", "label_name": "vulnerable"} {"code": "static void br_multicast_del_pg(struct net_bridge *br,\n\t\t\t\tstruct net_bridge_port_group *pg)\n{\n\tstruct net_bridge_mdb_htable *mdb;\n\tstruct net_bridge_mdb_entry *mp;\n\tstruct net_bridge_port_group *p;\n\tstruct net_bridge_port_group __rcu **pp;\n\n\tmdb = mlock_dereference(br->mdb, br);\n\n\tmp = br_mdb_ip_get(mdb, &pg->addr);\n\tif (WARN_ON(!mp))\n\t\treturn;\n\n\tfor (pp = &mp->ports;\n\t (p = mlock_dereference(*pp, br)) != NULL;\n\t pp = &p->next) {\n\t\tif (p != pg)\n\t\t\tcontinue;\n\n\t\trcu_assign_pointer(*pp, p->next);\n\t\thlist_del_init(&p->mglist);\n\t\tdel_timer(&p->timer);\n\t\tcall_rcu_bh(&p->rcu, br_multicast_free_pg);\n\n\t\tif (!mp->ports && !mp->mglist &&\n\t\t netif_running(br->dev))\n\t\t\tmod_timer(&mp->timer, jiffies);\n\n\t\treturn;\n\t}\n\n\tWARN_ON(1);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int persistent_prepare_exception(struct dm_exception_store *store,\n\t\t\t\t\tstruct dm_exception *e)\n{\n\tstruct pstore *ps = get_info(store);\n\tuint32_t stride;\n\tchunk_t next_free;\n\tsector_t size = get_dev_size(dm_snap_cow(store->snap)->bdev);\n\n\t/* Is there enough room ? */\n\tif (size < ((ps->next_free + 1) * store->chunk_size))\n\t\treturn -ENOSPC;\n\n\te->new_chunk = ps->next_free;\n\n\t/*\n\t * Move onto the next free pending, making sure to take\n\t * into account the location of the metadata chunks.\n\t */\n\tstride = (ps->exceptions_per_area + 1);\n\tnext_free = ++ps->next_free;\n\tif (sector_div(next_free, stride) == 1)\n\t\tps->next_free++;\n\n\tatomic_inc(&ps->pending_count);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,\n\t\t gfp_t gfp, struct dma_attrs *attrs)\n{\n\tpgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);\n\tvoid *memory;\n\n\tif (dma_alloc_from_coherent(dev, size, handle, &memory))\n\t\treturn memory;\n\n\treturn __dma_alloc(dev, size, handle, gfp, prot, false,\n\t\t\t __builtin_return_address(0));\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "int qeth_snmp_command(struct qeth_card *card, char __user *udata)\n{\n\tstruct qeth_cmd_buffer *iob;\n\tstruct qeth_ipa_cmd *cmd;\n\tstruct qeth_snmp_ureq *ureq;\n\tint req_len;\n\tstruct qeth_arp_query_info qinfo = {0, };\n\tint rc = 0;\n\n\tQETH_CARD_TEXT(card, 3, \"snmpcmd\");\n\n\tif (card->info.guestlan)\n\t\treturn -EOPNOTSUPP;\n\n\tif ((!qeth_adp_supported(card, IPA_SETADP_SET_SNMP_CONTROL)) &&\n\t (!card->options.layer2)) {\n\t\treturn -EOPNOTSUPP;\n\t}\n\t/* skip 4 bytes (data_len struct member) to get req_len */\n\tif (copy_from_user(&req_len, udata + sizeof(int), sizeof(int)))\n\t\treturn -EFAULT;\n\tureq = memdup_user(udata, req_len + sizeof(struct qeth_snmp_ureq_hdr));\n\tif (IS_ERR(ureq)) {\n\t\tQETH_CARD_TEXT(card, 2, \"snmpnome\");\n\t\treturn PTR_ERR(ureq);\n\t}\n\tqinfo.udata_len = ureq->hdr.data_len;\n\tqinfo.udata = kzalloc(qinfo.udata_len, GFP_KERNEL);\n\tif (!qinfo.udata) {\n\t\tkfree(ureq);\n\t\treturn -ENOMEM;\n\t}\n\tqinfo.udata_offset = sizeof(struct qeth_snmp_ureq_hdr);\n\n\tiob = qeth_get_adapter_cmd(card, IPA_SETADP_SET_SNMP_CONTROL,\n\t\t\t\t QETH_SNMP_SETADP_CMDLENGTH + req_len);\n\tcmd = (struct qeth_ipa_cmd *)(iob->data+IPA_PDU_HEADER_SIZE);\n\tmemcpy(&cmd->data.setadapterparms.data.snmp, &ureq->cmd, req_len);\n\trc = qeth_send_ipa_snmp_cmd(card, iob, QETH_SETADP_BASE_LEN + req_len,\n\t\t\t\t qeth_snmp_command_cb, (void *)&qinfo);\n\tif (rc)\n\t\tQETH_DBF_MESSAGE(2, \"SNMP command failed on %s: (0x%x)\\n\",\n\t\t\t QETH_CARD_IFNAME(card), rc);\n\telse {\n\t\tif (copy_to_user(udata, qinfo.udata, qinfo.udata_len))\n\t\t\trc = -EFAULT;\n\t}\n\n\tkfree(ureq);\n\tkfree(qinfo.udata);\n\treturn rc;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "void __fput_sync(struct file *file)\n{\n\tif (atomic_long_dec_and_test(&file->f_count)) {\n\t\tstruct task_struct *task = current;\n\t\tfile_sb_list_del(file);\n\t\tBUG_ON(!(task->flags & PF_KTHREAD));\n\t\t__fput(file);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-17", "cwe_name": "DEPRECATED: Code", "description": "This entry has been deprecated. It was originally used for organizing the Development View (CWE-699) and some other views, but it introduced unnecessary complexity and depth to the resulting tree.", "url": "https://cwe.mitre.org/data/definitions/17.html", "label_name": "vulnerable"} {"code": "static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk,\n\t\tstruct msghdr *msg, size_t len, int noblock, int flags,\n\t\tint *addr_len)\n{\n\tsize_t copied = 0;\n\tint err = -EOPNOTSUPP;\n\tstruct sk_buff *skb;\n\tstruct sockaddr_ieee802154 *saddr;\n\n\tsaddr = (struct sockaddr_ieee802154 *)msg->msg_name;\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb)\n\t\tgoto out;\n\n\tcopied = skb->len;\n\tif (len < copied) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\t/* FIXME: skip headers if necessary ?! */\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto done;\n\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\tif (saddr) {\n\t\tsaddr->family = AF_IEEE802154;\n\t\tsaddr->addr = mac_cb(skb)->sa;\n\t}\n\tif (addr_len)\n\t\t*addr_len = sizeof(*saddr);\n\n\tif (flags & MSG_TRUNC)\n\t\tcopied = skb->len;\ndone:\n\tskb_free_datagram(sk, skb);\nout:\n\tif (err)\n\t\treturn err;\n\treturn copied;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t ignored, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct skcipher_ctx *ctx = ask->private;\n\tunsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(\n\t\t&ctx->req));\n\tstruct skcipher_sg_list *sgl;\n\tstruct scatterlist *sg;\n\tunsigned long iovlen;\n\tstruct iovec *iov;\n\tint err = -EAGAIN;\n\tint used;\n\tlong copied = 0;\n\n\tlock_sock(sk);\n\tmsg->msg_namelen = 0;\n\tfor (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;\n\t iovlen--, iov++) {\n\t\tunsigned long seglen = iov->iov_len;\n\t\tchar __user *from = iov->iov_base;\n\n\t\twhile (seglen) {\n\t\t\tsgl = list_first_entry(&ctx->tsgl,\n\t\t\t\t\t struct skcipher_sg_list, list);\n\t\t\tsg = sgl->sg;\n\n\t\t\twhile (!sg->length)\n\t\t\t\tsg++;\n\n\t\t\tused = ctx->used;\n\t\t\tif (!used) {\n\t\t\t\terr = skcipher_wait_for_data(sk, flags);\n\t\t\t\tif (err)\n\t\t\t\t\tgoto unlock;\n\t\t\t}\n\n\t\t\tused = min_t(unsigned long, used, seglen);\n\n\t\t\tused = af_alg_make_sg(&ctx->rsgl, from, used, 1);\n\t\t\terr = used;\n\t\t\tif (err < 0)\n\t\t\t\tgoto unlock;\n\n\t\t\tif (ctx->more || used < ctx->used)\n\t\t\t\tused -= used % bs;\n\n\t\t\terr = -EINVAL;\n\t\t\tif (!used)\n\t\t\t\tgoto free;\n\n\t\t\tablkcipher_request_set_crypt(&ctx->req, sg,\n\t\t\t\t\t\t ctx->rsgl.sg, used,\n\t\t\t\t\t\t ctx->iv);\n\n\t\t\terr = af_alg_wait_for_completion(\n\t\t\t\tctx->enc ?\n\t\t\t\t\tcrypto_ablkcipher_encrypt(&ctx->req) :\n\t\t\t\t\tcrypto_ablkcipher_decrypt(&ctx->req),\n\t\t\t\t&ctx->completion);\n\nfree:\n\t\t\taf_alg_free_sg(&ctx->rsgl);\n\n\t\t\tif (err)\n\t\t\t\tgoto unlock;\n\n\t\t\tcopied += used;\n\t\t\tfrom += used;\n\t\t\tseglen -= used;\n\t\t\tskcipher_pull_sgl(sk, used);\n\t\t}\n\t}\n\n\terr = 0;\n\nunlock:\n\tskcipher_wmem_wakeup(sk);\n\trelease_sock(sk);\n\n\treturn copied ?: err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "mISDN_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tstruct sk_buff\t\t*skb;\n\tstruct sock\t\t*sk = sock->sk;\n\tstruct sockaddr_mISDN\t*maddr;\n\n\tint\t\tcopied, err;\n\n\tif (*debug & DEBUG_SOCKET)\n\t\tprintk(KERN_DEBUG \"%s: len %d, flags %x ch.nr %d, proto %x\\n\",\n\t\t __func__, (int)len, flags, _pms(sk)->ch.nr,\n\t\t sk->sk_protocol);\n\tif (flags & (MSG_OOB))\n\t\treturn -EOPNOTSUPP;\n\n\tif (sk->sk_state == MISDN_CLOSED)\n\t\treturn 0;\n\n\tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n\tif (!skb)\n\t\treturn err;\n\n\tif (msg->msg_namelen >= sizeof(struct sockaddr_mISDN)) {\n\t\tmsg->msg_namelen = sizeof(struct sockaddr_mISDN);\n\t\tmaddr = (struct sockaddr_mISDN *)msg->msg_name;\n\t\tmaddr->family = AF_ISDN;\n\t\tmaddr->dev = _pms(sk)->dev->id;\n\t\tif ((sk->sk_protocol == ISDN_P_LAPD_TE) ||\n\t\t (sk->sk_protocol == ISDN_P_LAPD_NT)) {\n\t\t\tmaddr->channel = (mISDN_HEAD_ID(skb) >> 16) & 0xff;\n\t\t\tmaddr->tei = (mISDN_HEAD_ID(skb) >> 8) & 0xff;\n\t\t\tmaddr->sapi = mISDN_HEAD_ID(skb) & 0xff;\n\t\t} else {\n\t\t\tmaddr->channel = _pms(sk)->ch.nr;\n\t\t\tmaddr->sapi = _pms(sk)->ch.addr & 0xFF;\n\t\t\tmaddr->tei = (_pms(sk)->ch.addr >> 8) & 0xFF;\n\t\t}\n\t} else {\n\t\tif (msg->msg_namelen)\n\t\t\tprintk(KERN_WARNING \"%s: too small namelen %d\\n\",\n\t\t\t __func__, msg->msg_namelen);\n\t\tmsg->msg_namelen = 0;\n\t}\n\n\tcopied = skb->len + MISDN_HEADER_LEN;\n\tif (len < copied) {\n\t\tif (flags & MSG_PEEK)\n\t\t\tatomic_dec(&skb->users);\n\t\telse\n\t\t\tskb_queue_head(&sk->sk_receive_queue, skb);\n\t\treturn -ENOSPC;\n\t}\n\tmemcpy(skb_push(skb, MISDN_HEADER_LEN), mISDN_HEAD_P(skb),\n\t MISDN_HEADER_LEN);\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tmISDN_sock_cmsg(sk, msg, skb);\n\n\tskb_free_datagram(sk, skb);\n\n\treturn err ? : copied;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,\n\t\tsize_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct atm_vcc *vcc;\n\tstruct sk_buff *skb;\n\tint copied, error = -EINVAL;\n\n\tmsg->msg_namelen = 0;\n\n\tif (sock->state != SS_CONNECTED)\n\t\treturn -ENOTCONN;\n\n\t/* only handle MSG_DONTWAIT and MSG_PEEK */\n\tif (flags & ~(MSG_DONTWAIT | MSG_PEEK))\n\t\treturn -EOPNOTSUPP;\n\n\tvcc = ATM_SD(sock);\n\tif (test_bit(ATM_VF_RELEASED, &vcc->flags) ||\n\t test_bit(ATM_VF_CLOSE, &vcc->flags) ||\n\t !test_bit(ATM_VF_READY, &vcc->flags))\n\t\treturn 0;\n\n\tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error);\n\tif (!skb)\n\t\treturn error;\n\n\tcopied = skb->len;\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\terror = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (error)\n\t\treturn error;\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\tif (!(flags & MSG_PEEK)) {\n\t\tpr_debug(\"%d -= %d\\n\", atomic_read(&sk->sk_rmem_alloc),\n\t\t\t skb->truesize);\n\t\tatm_return(vcc, skb->truesize);\n\t}\n\n\tskb_free_datagram(sk, skb);\n\treturn copied;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int ax25_recvmsg(struct kiocb *iocb, struct socket *sock,\n\tstruct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint copied;\n\tint err = 0;\n\n\tlock_sock(sk);\n\t/*\n\t * \tThis works for seqpacket too. The receiver has ordered the\n\t *\tqueue for us! We do one quick check first though\n\t */\n\tif (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) {\n\t\terr = -ENOTCONN;\n\t\tgoto out;\n\t}\n\n\t/* Now we can treat all alike */\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &err);\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tif (!ax25_sk(sk)->pidincl)\n\t\tskb_pull(skb, 1);\t\t/* Remove PID */\n\n\tskb_reset_transport_header(skb);\n\tcopied = skb->len;\n\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\tskb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tif (msg->msg_namelen != 0) {\n\t\tstruct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;\n\t\tax25_digi digi;\n\t\tax25_address src;\n\t\tconst unsigned char *mac = skb_mac_header(skb);\n\n\t\tmemset(sax, 0, sizeof(struct full_sockaddr_ax25));\n\t\tax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL,\n\t\t\t\t&digi, NULL, NULL);\n\t\tsax->sax25_family = AF_AX25;\n\t\t/* We set this correctly, even though we may not let the\n\t\t application know the digi calls further down (because it\n\t\t did NOT ask to know them). This could get political... **/\n\t\tsax->sax25_ndigis = digi.ndigi;\n\t\tsax->sax25_call = src;\n\n\t\tif (sax->sax25_ndigis != 0) {\n\t\t\tint ct;\n\t\t\tstruct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax;\n\n\t\t\tfor (ct = 0; ct < digi.ndigi; ct++)\n\t\t\t\tfsa->fsa_digipeater[ct] = digi.calls[ct];\n\t\t}\n\t\tmsg->msg_namelen = sizeof(struct full_sockaddr_ax25);\n\t}\n\n\tskb_free_datagram(sk, skb);\n\terr = copied;\n\nout:\n\trelease_sock(sk);\n\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;\n\tint len;\n\n\tif (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {\n\t\trfcomm_dlc_accept(d);\n\t\tmsg->msg_namelen = 0;\n\t\treturn 0;\n\t}\n\n\tlen = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);\n\n\tlock_sock(sk);\n\tif (!(flags & MSG_PEEK) && len > 0)\n\t\tatomic_sub(len, &sk->sk_rmem_alloc);\n\n\tif (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))\n\t\trfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);\n\trelease_sock(sk);\n\n\treturn len;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sco_pinfo *pi = sco_pi(sk);\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state == BT_CONNECT2 &&\n\t test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {\n\t\tsco_conn_defer_accept(pi->conn->hcon, pi->setting);\n\t\tsk->sk_state = BT_CONFIG;\n\t\tmsg->msg_namelen = 0;\n\n\t\trelease_sock(sk);\n\t\treturn 0;\n\t}\n\n\trelease_sock(sk);\n\n\treturn bt_sock_recvmsg(iocb, sock, msg, len, flags);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sco_pinfo *pi = sco_pi(sk);\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state == BT_CONNECT2 &&\n\t test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {\n\t\tsco_conn_defer_accept(pi->conn->hcon, pi->setting);\n\t\tsk->sk_state = BT_CONFIG;\n\t\tmsg->msg_namelen = 0;\n\n\t\trelease_sock(sk);\n\t\treturn 0;\n\t}\n\n\trelease_sock(sk);\n\n\treturn bt_sock_recvmsg(iocb, sock, msg, len, flags);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sco_pinfo *pi = sco_pi(sk);\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state == BT_CONNECT2 &&\n\t test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {\n\t\tsco_conn_defer_accept(pi->conn->hcon, pi->setting);\n\t\tsk->sk_state = BT_CONFIG;\n\t\tmsg->msg_namelen = 0;\n\n\t\trelease_sock(sk);\n\t\treturn 0;\n\t}\n\n\trelease_sock(sk);\n\n\treturn bt_sock_recvmsg(iocb, sock, msg, len, flags);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *m, size_t len, int flags)\n\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint ret;\n\tint copylen;\n\n\tret = -EOPNOTSUPP;\n\tif (m->msg_flags&MSG_OOB)\n\t\tgoto read_error;\n\n\tm->msg_namelen = 0;\n\n\tskb = skb_recv_datagram(sk, flags, 0 , &ret);\n\tif (!skb)\n\t\tgoto read_error;\n\tcopylen = skb->len;\n\tif (len < copylen) {\n\t\tm->msg_flags |= MSG_TRUNC;\n\t\tcopylen = len;\n\t}\n\n\tret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen);\n\tif (ret)\n\t\tgoto out_free;\n\n\tret = (flags & MSG_TRUNC) ? skb->len : copylen;\nout_free:\n\tskb_free_datagram(sk, skb);\n\tcaif_check_flow_release(sk);\n\treturn ret;\n\nread_error:\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int pfkey_recvmsg(struct kiocb *kiocb,\n\t\t\t struct socket *sock, struct msghdr *msg, size_t len,\n\t\t\t int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct pfkey_sock *pfk = pfkey_sk(sk);\n\tstruct sk_buff *skb;\n\tint copied, err;\n\n\terr = -EINVAL;\n\tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))\n\t\tgoto out;\n\n\tmsg->msg_namelen = 0;\n\tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tcopied = skb->len;\n\tif (copied > len) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\tskb_reset_transport_header(skb);\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto out_free;\n\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\terr = (flags & MSG_TRUNC) ? skb->len : copied;\n\n\tif (pfk->dump.dump != NULL &&\n\t 3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)\n\t\tpfkey_do_dump(pfk);\n\nout_free:\n\tskb_free_datagram(sk, skb);\nout:\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len,\n\t\t\t int flags)\n{\n\tint err;\n\tstruct sk_buff *skb;\n\tstruct sock *sk = sock->sk;\n\n\terr = -EIO;\n\tif (sk->sk_state & PPPOX_BOUND)\n\t\tgoto end;\n\n\tmsg->msg_namelen = 0;\n\n\terr = 0;\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &err);\n\tif (!skb)\n\t\tgoto end;\n\n\tif (len > skb->len)\n\t\tlen = skb->len;\n\telse if (len < skb->len)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len);\n\tif (likely(err == 0))\n\t\terr = len;\n\n\tkfree_skb(skb);\nend:\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int nr_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;\n\tsize_t copied;\n\tstruct sk_buff *skb;\n\tint er;\n\n\t/*\n\t * This works for seqpacket too. The receiver has ordered the queue for\n\t * us! We do one quick check first though\n\t */\n\n\tlock_sock(sk);\n\tif (sk->sk_state != TCP_ESTABLISHED) {\n\t\trelease_sock(sk);\n\t\treturn -ENOTCONN;\n\t}\n\n\t/* Now we can treat all alike */\n\tif ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) {\n\t\trelease_sock(sk);\n\t\treturn er;\n\t}\n\n\tskb_reset_transport_header(skb);\n\tcopied = skb->len;\n\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\ter = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (er < 0) {\n\t\tskb_free_datagram(sk, skb);\n\t\trelease_sock(sk);\n\t\treturn er;\n\t}\n\n\tif (sax != NULL) {\n\t\tmemset(sax, 0, sizeof(*sax));\n\t\tsax->sax25_family = AF_NETROM;\n\t\tskb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call,\n\t\t\t AX25_ADDR_LEN);\n\t}\n\n\tmsg->msg_namelen = sizeof(*sax);\n\n\tskb_free_datagram(sk, skb);\n\n\trelease_sock(sk);\n\treturn copied;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int rose_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\tstruct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct rose_sock *rose = rose_sk(sk);\n\tstruct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name;\n\tsize_t copied;\n\tunsigned char *asmptr;\n\tstruct sk_buff *skb;\n\tint n, er, qbit;\n\n\t/*\n\t * This works for seqpacket too. The receiver has ordered the queue for\n\t * us! We do one quick check first though\n\t */\n\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\treturn -ENOTCONN;\n\n\t/* Now we can treat all alike */\n\tif ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL)\n\t\treturn er;\n\n\tqbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT;\n\n\tskb_pull(skb, ROSE_MIN_LEN);\n\n\tif (rose->qbitincl) {\n\t\tasmptr = skb_push(skb, 1);\n\t\t*asmptr = qbit;\n\t}\n\n\tskb_reset_transport_header(skb);\n\tcopied = skb->len;\n\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\tskb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tif (srose != NULL) {\n\t\tmemset(srose, 0, msg->msg_namelen);\n\t\tsrose->srose_family = AF_ROSE;\n\t\tsrose->srose_addr = rose->dest_addr;\n\t\tsrose->srose_call = rose->dest_call;\n\t\tsrose->srose_ndigis = rose->dest_ndigis;\n\t\tif (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) {\n\t\t\tstruct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name;\n\t\t\tfor (n = 0 ; n < rose->dest_ndigis ; n++)\n\t\t\t\tfull_srose->srose_digis[n] = rose->dest_digis[n];\n\t\t\tmsg->msg_namelen = sizeof(struct full_sockaddr_rose);\n\t\t} else {\n\t\t\tif (rose->dest_ndigis >= 1) {\n\t\t\t\tsrose->srose_ndigis = 1;\n\t\t\t\tsrose->srose_digi = rose->dest_digis[0];\n\t\t\t}\n\t\t\tmsg->msg_namelen = sizeof(struct sockaddr_rose);\n\t\t}\n\t}\n\n\tskb_free_datagram(sk, skb);\n\n\treturn copied;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,\n\t\t\t\t\tstruct vsock_sock *vsk,\n\t\t\t\t\tstruct msghdr *msg, size_t len,\n\t\t\t\t\tint flags)\n{\n\tint err;\n\tint noblock;\n\tstruct vmci_datagram *dg;\n\tsize_t payload_len;\n\tstruct sk_buff *skb;\n\n\tnoblock = flags & MSG_DONTWAIT;\n\n\tif (flags & MSG_OOB || flags & MSG_ERRQUEUE)\n\t\treturn -EOPNOTSUPP;\n\n\tmsg->msg_namelen = 0;\n\n\t/* Retrieve the head sk_buff from the socket's receive queue. */\n\terr = 0;\n\tskb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);\n\tif (err)\n\t\treturn err;\n\n\tif (!skb)\n\t\treturn -EAGAIN;\n\n\tdg = (struct vmci_datagram *)skb->data;\n\tif (!dg)\n\t\t/* err is 0, meaning we read zero bytes. */\n\t\tgoto out;\n\n\tpayload_len = dg->payload_size;\n\t/* Ensure the sk_buff matches the payload size claimed in the packet. */\n\tif (payload_len != skb->len - sizeof(*dg)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tif (payload_len > len) {\n\t\tpayload_len = len;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\t/* Place the datagram payload in the user's iovec. */\n\terr = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov,\n\t\tpayload_len);\n\tif (err)\n\t\tgoto out;\n\n\tif (msg->msg_name) {\n\t\tstruct sockaddr_vm *vm_addr;\n\n\t\t/* Provide the address of the sender. */\n\t\tvm_addr = (struct sockaddr_vm *)msg->msg_name;\n\t\tvsock_addr_init(vm_addr, dg->src.context, dg->src.resource);\n\t\tmsg->msg_namelen = sizeof(*vm_addr);\n\t}\n\terr = payload_len;\n\nout:\n\tskb_free_datagram(&vsk->sk, skb);\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int __vcpu_run(struct kvm_vcpu *vcpu)\n{\n\tint r;\n\tstruct kvm *kvm = vcpu->kvm;\n\n\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\tr = vapic_enter(vcpu);\n\tif (r) {\n\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\treturn r;\n\t}\n\n\tr = 1;\n\twhile (r > 0) {\n\t\tif (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&\n\t\t !vcpu->arch.apf.halted)\n\t\t\tr = vcpu_enter_guest(vcpu);\n\t\telse {\n\t\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\t\tkvm_vcpu_block(vcpu);\n\t\t\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\t\t\tif (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {\n\t\t\t\tkvm_apic_accept_events(vcpu);\n\t\t\t\tswitch(vcpu->arch.mp_state) {\n\t\t\t\tcase KVM_MP_STATE_HALTED:\n\t\t\t\t\tvcpu->arch.pv.pv_unhalted = false;\n\t\t\t\t\tvcpu->arch.mp_state =\n\t\t\t\t\t\tKVM_MP_STATE_RUNNABLE;\n\t\t\t\tcase KVM_MP_STATE_RUNNABLE:\n\t\t\t\t\tvcpu->arch.apf.halted = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase KVM_MP_STATE_INIT_RECEIVED:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tr = -EINTR;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (r <= 0)\n\t\t\tbreak;\n\n\t\tclear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);\n\t\tif (kvm_cpu_has_pending_timer(vcpu))\n\t\t\tkvm_inject_pending_timer_irqs(vcpu);\n\n\t\tif (dm_request_for_irq_injection(vcpu)) {\n\t\t\tr = -EINTR;\n\t\t\tvcpu->run->exit_reason = KVM_EXIT_INTR;\n\t\t\t++vcpu->stat.request_irq_exits;\n\t\t}\n\n\t\tkvm_check_async_pf_completion(vcpu);\n\n\t\tif (signal_pending(current)) {\n\t\t\tr = -EINTR;\n\t\t\tvcpu->run->exit_reason = KVM_EXIT_INTR;\n\t\t\t++vcpu->stat.signal_exits;\n\t\t}\n\t\tif (need_resched()) {\n\t\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\t\tkvm_resched(vcpu);\n\t\t\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\t\t}\n\t}\n\n\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\n\tvapic_exit(vcpu);\n\n\treturn r;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)\n{\n\tif (file->f_flags & O_DSYNC)\n\t\treturn 0;\n\tif (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))\n\t\treturn 1;\n\tif (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL ||\n\t\t\t(inode->i_flock->fl_start == 0 &&\n\t\t\tinode->i_flock->fl_end == OFFSET_MAX &&\n\t\t\tinode->i_flock->fl_type != F_RDLCK)))\n\t\treturn 1;\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "static int snd_ctl_tlv_ioctl(struct snd_ctl_file *file,\n struct snd_ctl_tlv __user *_tlv,\n int op_flag)\n{\n\tstruct snd_card *card = file->card;\n\tstruct snd_ctl_tlv tlv;\n\tstruct snd_kcontrol *kctl;\n\tstruct snd_kcontrol_volatile *vd;\n\tunsigned int len;\n\tint err = 0;\n\n\tif (copy_from_user(&tlv, _tlv, sizeof(tlv)))\n\t\treturn -EFAULT;\n\tif (tlv.length < sizeof(unsigned int) * 2)\n\t\treturn -EINVAL;\n\tdown_read(&card->controls_rwsem);\n\tkctl = snd_ctl_find_numid(card, tlv.numid);\n\tif (kctl == NULL) {\n\t\terr = -ENOENT;\n\t\tgoto __kctl_end;\n\t}\n\tif (kctl->tlv.p == NULL) {\n\t\terr = -ENXIO;\n\t\tgoto __kctl_end;\n\t}\n\tvd = &kctl->vd[tlv.numid - kctl->id.numid];\n\tif ((op_flag == 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_READ) == 0) ||\n\t (op_flag > 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE) == 0) ||\n\t (op_flag < 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND) == 0)) {\n\t \terr = -ENXIO;\n\t \tgoto __kctl_end;\n\t}\n\tif (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {\n\t\tif (vd->owner != NULL && vd->owner != file) {\n\t\t\terr = -EPERM;\n\t\t\tgoto __kctl_end;\n\t\t}\n\t\terr = kctl->tlv.c(kctl, op_flag, tlv.length, _tlv->tlv);\n\t\tif (err > 0) {\n\t\t\tup_read(&card->controls_rwsem);\n\t\t\tsnd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_TLV, &kctl->id);\n\t\t\treturn 0;\n\t\t}\n\t} else {\n\t\tif (op_flag) {\n\t\t\terr = -ENXIO;\n\t\t\tgoto __kctl_end;\n\t\t}\n\t\tlen = kctl->tlv.p[1] + 2 * sizeof(unsigned int);\n\t\tif (tlv.length < len) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto __kctl_end;\n\t\t}\n\t\tif (copy_to_user(_tlv->tlv, kctl->tlv.p, len))\n\t\t\terr = -EFAULT;\n\t}\n __kctl_end:\n\tup_read(&card->controls_rwsem);\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static struct mount *clone_mnt(struct mount *old, struct dentry *root,\n\t\t\t\t\tint flag)\n{\n\tstruct super_block *sb = old->mnt.mnt_sb;\n\tstruct mount *mnt;\n\tint err;\n\n\tmnt = alloc_vfsmnt(old->mnt_devname);\n\tif (!mnt)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tif (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))\n\t\tmnt->mnt_group_id = 0; /* not a peer of original */\n\telse\n\t\tmnt->mnt_group_id = old->mnt_group_id;\n\n\tif ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {\n\t\terr = mnt_alloc_group_id(mnt);\n\t\tif (err)\n\t\t\tgoto out_free;\n\t}\n\n\tmnt->mnt.mnt_flags = old->mnt.mnt_flags & ~(MNT_WRITE_HOLD|MNT_MARKED);\n\t/* Don't allow unprivileged users to change mount flags */\n\tif ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY))\n\t\tmnt->mnt.mnt_flags |= MNT_LOCK_READONLY;\n\n\t/* Don't allow unprivileged users to reveal what is under a mount */\n\tif ((flag & CL_UNPRIVILEGED) && list_empty(&old->mnt_expire))\n\t\tmnt->mnt.mnt_flags |= MNT_LOCKED;\n\n\tatomic_inc(&sb->s_active);\n\tmnt->mnt.mnt_sb = sb;\n\tmnt->mnt.mnt_root = dget(root);\n\tmnt->mnt_mountpoint = mnt->mnt.mnt_root;\n\tmnt->mnt_parent = mnt;\n\tlock_mount_hash();\n\tlist_add_tail(&mnt->mnt_instance, &sb->s_mounts);\n\tunlock_mount_hash();\n\n\tif ((flag & CL_SLAVE) ||\n\t ((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {\n\t\tlist_add(&mnt->mnt_slave, &old->mnt_slave_list);\n\t\tmnt->mnt_master = old;\n\t\tCLEAR_MNT_SHARED(mnt);\n\t} else if (!(flag & CL_PRIVATE)) {\n\t\tif ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))\n\t\t\tlist_add(&mnt->mnt_share, &old->mnt_share);\n\t\tif (IS_MNT_SLAVE(old))\n\t\t\tlist_add(&mnt->mnt_slave, &old->mnt_slave);\n\t\tmnt->mnt_master = old->mnt_master;\n\t}\n\tif (flag & CL_MAKE_SHARED)\n\t\tset_mnt_shared(mnt);\n\n\t/* stick the duplicate mount on the same expiry list\n\t * as the original if that was on one */\n\tif (flag & CL_EXPIRE) {\n\t\tif (!list_empty(&old->mnt_expire))\n\t\t\tlist_add(&mnt->mnt_expire, &old->mnt_expire);\n\t}\n\n\treturn mnt;\n\n out_free:\n\tmnt_free_id(mnt);\n\tfree_vfsmnt(mnt);\n\treturn ERR_PTR(err);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-269", "cwe_name": "Improper Privilege Management", "description": "The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.", "url": "https://cwe.mitre.org/data/definitions/269.html", "label_name": "vulnerable"} {"code": "static int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac,\n\t\t\t\t\t struct ceph_authorizer *a, size_t len)\n{\n\tstruct ceph_x_authorizer *au = (void *)a;\n\tstruct ceph_x_ticket_handler *th;\n\tint ret = 0;\n\tstruct ceph_x_authorize_reply reply;\n\tvoid *p = au->reply_buf;\n\tvoid *end = p + sizeof(au->reply_buf);\n\n\tth = get_ticket_handler(ac, au->service);\n\tif (IS_ERR(th))\n\t\treturn PTR_ERR(th);\n\tret = ceph_x_decrypt(&th->session_key, &p, end, &reply, sizeof(reply));\n\tif (ret < 0)\n\t\treturn ret;\n\tif (ret != sizeof(reply))\n\t\treturn -EPERM;\n\n\tif (au->nonce + 1 != le64_to_cpu(reply.nonce_plus_one))\n\t\tret = -EPERM;\n\telse\n\t\tret = 0;\n\tdout(\"verify_authorizer_reply nonce %llx got %llx ret %d\\n\",\n\t au->nonce, le64_to_cpu(reply.nonce_plus_one), ret);\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "dns_resolver_match(const struct key *key,\n\t\t const struct key_match_data *match_data)\n{\n\tint slen, dlen, ret = 0;\n\tconst char *src = key->description, *dsp = match_data->raw_data;\n\n\tkenter(\"%s,%s\", src, dsp);\n\n\tif (!src || !dsp)\n\t\tgoto no_match;\n\n\tif (strcasecmp(src, dsp) == 0)\n\t\tgoto matched;\n\n\tslen = strlen(src);\n\tdlen = strlen(dsp);\n\tif (slen <= 0 || dlen <= 0)\n\t\tgoto no_match;\n\tif (src[slen - 1] == '.')\n\t\tslen--;\n\tif (dsp[dlen - 1] == '.')\n\t\tdlen--;\n\tif (slen != dlen || strncasecmp(src, dsp, slen) != 0)\n\t\tgoto no_match;\n\nmatched:\n\tret = 1;\nno_match:\n\tkleave(\" = %d\", ret);\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "struct key *key_get_instantiation_authkey(key_serial_t target_id)\n{\n\tchar description[16];\n\tstruct keyring_search_context ctx = {\n\t\t.index_key.type\t\t= &key_type_request_key_auth,\n\t\t.index_key.description\t= description,\n\t\t.cred\t\t\t= current_cred(),\n\t\t.match_data.cmp\t\t= user_match,\n\t\t.match_data.raw_data\t= description,\n\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n\t};\n\tstruct key *authkey;\n\tkey_ref_t authkey_ref;\n\n\tsprintf(description, \"%x\", target_id);\n\n\tauthkey_ref = search_process_keyrings(&ctx);\n\n\tif (IS_ERR(authkey_ref)) {\n\t\tauthkey = ERR_CAST(authkey_ref);\n\t\tif (authkey == ERR_PTR(-EAGAIN))\n\t\t\tauthkey = ERR_PTR(-ENOKEY);\n\t\tgoto error;\n\t}\n\n\tauthkey = key_ref_to_ptr(authkey_ref);\n\tif (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) {\n\t\tkey_put(authkey);\n\t\tauthkey = ERR_PTR(-EKEYREVOKED);\n\t}\n\nerror:\n\treturn authkey;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static pfn_t kvm_pin_pages(struct kvm_memory_slot *slot, gfn_t gfn,\n\t\t\t unsigned long size)\n{\n\tgfn_t end_gfn;\n\tpfn_t pfn;\n\n\tpfn = gfn_to_pfn_memslot(slot, gfn);\n\tend_gfn = gfn + (size >> PAGE_SHIFT);\n\tgfn += 1;\n\n\tif (is_error_noslot_pfn(pfn))\n\t\treturn pfn;\n\n\twhile (gfn < end_gfn)\n\t\tgfn_to_pfn_memslot(slot, gfn++);\n\n\treturn pfn;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void ftrace_syscall_enter(void *data, struct pt_regs *regs, long id)\n{\n\tstruct trace_array *tr = data;\n\tstruct ftrace_event_file *ftrace_file;\n\tstruct syscall_trace_enter *entry;\n\tstruct syscall_metadata *sys_data;\n\tstruct ring_buffer_event *event;\n\tstruct ring_buffer *buffer;\n\tunsigned long irq_flags;\n\tint pc;\n\tint syscall_nr;\n\tint size;\n\n\tsyscall_nr = trace_get_syscall_nr(current, regs);\n\tif (syscall_nr < 0)\n\t\treturn;\n\n\t/* Here we're inside tp handler's rcu_read_lock_sched (__DO_TRACE) */\n\tftrace_file = rcu_dereference_sched(tr->enter_syscall_files[syscall_nr]);\n\tif (!ftrace_file)\n\t\treturn;\n\n\tif (ftrace_trigger_soft_disabled(ftrace_file))\n\t\treturn;\n\n\tsys_data = syscall_nr_to_meta(syscall_nr);\n\tif (!sys_data)\n\t\treturn;\n\n\tsize = sizeof(*entry) + sizeof(unsigned long) * sys_data->nb_args;\n\n\tlocal_save_flags(irq_flags);\n\tpc = preempt_count();\n\n\tbuffer = tr->trace_buffer.buffer;\n\tevent = trace_buffer_lock_reserve(buffer,\n\t\t\tsys_data->enter_event->event.type, size, irq_flags, pc);\n\tif (!event)\n\t\treturn;\n\n\tentry = ring_buffer_event_data(event);\n\tentry->nr = syscall_nr;\n\tsyscall_get_arguments(current, regs, 0, sys_data->nb_args, entry->args);\n\n\tevent_trigger_unlock_commit(ftrace_file, buffer, event, entry,\n\t\t\t\t irq_flags, pc);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static void perf_syscall_enter(void *ignore, struct pt_regs *regs, long id)\n{\n\tstruct syscall_metadata *sys_data;\n\tstruct syscall_trace_enter *rec;\n\tstruct hlist_head *head;\n\tint syscall_nr;\n\tint rctx;\n\tint size;\n\n\tsyscall_nr = trace_get_syscall_nr(current, regs);\n\tif (syscall_nr < 0)\n\t\treturn;\n\tif (!test_bit(syscall_nr, enabled_perf_enter_syscalls))\n\t\treturn;\n\n\tsys_data = syscall_nr_to_meta(syscall_nr);\n\tif (!sys_data)\n\t\treturn;\n\n\thead = this_cpu_ptr(sys_data->enter_event->perf_events);\n\tif (hlist_empty(head))\n\t\treturn;\n\n\t/* get the size after alignment with the u32 buffer size field */\n\tsize = sizeof(unsigned long) * sys_data->nb_args + sizeof(*rec);\n\tsize = ALIGN(size + sizeof(u32), sizeof(u64));\n\tsize -= sizeof(u32);\n\n\trec = (struct syscall_trace_enter *)perf_trace_buf_prepare(size,\n\t\t\t\tsys_data->enter_event->event.type, regs, &rctx);\n\tif (!rec)\n\t\treturn;\n\n\trec->nr = syscall_nr;\n\tsyscall_get_arguments(current, regs, 0, sys_data->nb_args,\n\t\t\t (unsigned long *)&rec->args);\n\tperf_trace_buf_submit(rec, size, rctx, 0, 1, regs, head, NULL);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "int ip_forward(struct sk_buff *skb)\n{\n\tu32 mtu;\n\tstruct iphdr *iph;\t/* Our header */\n\tstruct rtable *rt;\t/* Route we use */\n\tstruct ip_options *opt\t= &(IPCB(skb)->opt);\n\n\t/* that should never happen */\n\tif (skb->pkt_type != PACKET_HOST)\n\t\tgoto drop;\n\n\tif (skb_warn_if_lro(skb))\n\t\tgoto drop;\n\n\tif (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb))\n\t\tgoto drop;\n\n\tif (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb))\n\t\treturn NET_RX_SUCCESS;\n\n\tskb_forward_csum(skb);\n\n\t/*\n\t *\tAccording to the RFC, we must first decrease the TTL field. If\n\t *\tthat reaches zero, we must reply an ICMP control message telling\n\t *\tthat the packet's lifetime expired.\n\t */\n\tif (ip_hdr(skb)->ttl <= 1)\n\t\tgoto too_many_hops;\n\n\tif (!xfrm4_route_forward(skb))\n\t\tgoto drop;\n\n\trt = skb_rtable(skb);\n\n\tif (opt->is_strictroute && rt->rt_uses_gateway)\n\t\tgoto sr_failed;\n\n\tIPCB(skb)->flags |= IPSKB_FORWARDED;\n\tmtu = ip_dst_mtu_maybe_forward(&rt->dst, true);\n\tif (!ip_may_fragment(skb) && ip_exceeds_mtu(skb, mtu)) {\n\t\tIP_INC_STATS(dev_net(rt->dst.dev), IPSTATS_MIB_FRAGFAILS);\n\t\ticmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,\n\t\t\t htonl(mtu));\n\t\tgoto drop;\n\t}\n\n\t/* We are about to mangle packet. Copy it! */\n\tif (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+rt->dst.header_len))\n\t\tgoto drop;\n\tiph = ip_hdr(skb);\n\n\t/* Decrease ttl after skb cow done */\n\tip_decrease_ttl(iph);\n\n\t/*\n\t *\tWe now generate an ICMP HOST REDIRECT giving the route\n\t *\twe calculated.\n\t */\n\tif (rt->rt_flags&RTCF_DOREDIRECT && !opt->srr && !skb_sec_path(skb))\n\t\tip_rt_send_redirect(skb);\n\n\tskb->priority = rt_tos2priority(iph->tos);\n\n\treturn NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD, skb, skb->dev,\n\t\t rt->dst.dev, ip_forward_finish);\n\nsr_failed:\n\t/*\n\t *\tStrict routing permits no gatewaying\n\t */\n\t icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0);\n\t goto drop;\n\ntoo_many_hops:\n\t/* Tell the sender its packet died... */\n\tIP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_INHDRERRORS);\n\ticmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0);\ndrop:\n\tkfree_skb(skb);\n\treturn NET_RX_DROP;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-17", "cwe_name": "DEPRECATED: Code", "description": "This entry has been deprecated. It was originally used for organizing the Development View (CWE-699) and some other views, but it introduced unnecessary complexity and depth to the resulting tree.", "url": "https://cwe.mitre.org/data/definitions/17.html", "label_name": "vulnerable"} {"code": "static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n{\n\tstruct perf_event *event = file->private_data;\n\tvoid (*func)(struct perf_event *);\n\tu32 flags = arg;\n\n\tswitch (cmd) {\n\tcase PERF_EVENT_IOC_ENABLE:\n\t\tfunc = perf_event_enable;\n\t\tbreak;\n\tcase PERF_EVENT_IOC_DISABLE:\n\t\tfunc = perf_event_disable;\n\t\tbreak;\n\tcase PERF_EVENT_IOC_RESET:\n\t\tfunc = perf_event_reset;\n\t\tbreak;\n\n\tcase PERF_EVENT_IOC_REFRESH:\n\t\treturn perf_event_refresh(event, arg);\n\n\tcase PERF_EVENT_IOC_PERIOD:\n\t\treturn perf_event_period(event, (u64 __user *)arg);\n\n\tcase PERF_EVENT_IOC_ID:\n\t{\n\t\tu64 id = primary_event_id(event);\n\n\t\tif (copy_to_user((void __user *)arg, &id, sizeof(id)))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\t}\n\n\tcase PERF_EVENT_IOC_SET_OUTPUT:\n\t{\n\t\tint ret;\n\t\tif (arg != -1) {\n\t\t\tstruct perf_event *output_event;\n\t\t\tstruct fd output;\n\t\t\tret = perf_fget_light(arg, &output);\n\t\t\tif (ret)\n\t\t\t\treturn ret;\n\t\t\toutput_event = output.file->private_data;\n\t\t\tret = perf_event_set_output(event, output_event);\n\t\t\tfdput(output);\n\t\t} else {\n\t\t\tret = perf_event_set_output(event, NULL);\n\t\t}\n\t\treturn ret;\n\t}\n\n\tcase PERF_EVENT_IOC_SET_FILTER:\n\t\treturn perf_event_set_filter(event, (void __user *)arg);\n\n\tdefault:\n\t\treturn -ENOTTY;\n\t}\n\n\tif (flags & PERF_IOC_FLAG_GROUP)\n\t\tperf_event_for_each(event, func);\n\telse\n\t\tperf_event_for_each_child(event, func);\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)\n{\n\tstruct perf_event *event = file->private_data;\n\n\treturn perf_read_hw(event, buf, count);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)\n{\n\tstruct perf_event_context *src_ctx;\n\tstruct perf_event_context *dst_ctx;\n\tstruct perf_event *event, *tmp;\n\tLIST_HEAD(events);\n\n\tsrc_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;\n\tdst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;\n\n\tmutex_lock(&src_ctx->mutex);\n\tlist_for_each_entry_safe(event, tmp, &src_ctx->event_list,\n\t\t\t\t event_entry) {\n\t\tperf_remove_from_context(event, false);\n\t\tunaccount_event_cpu(event, src_cpu);\n\t\tput_ctx(src_ctx);\n\t\tlist_add(&event->migrate_entry, &events);\n\t}\n\tmutex_unlock(&src_ctx->mutex);\n\n\tsynchronize_rcu();\n\n\tmutex_lock(&dst_ctx->mutex);\n\tlist_for_each_entry_safe(event, tmp, &events, migrate_entry) {\n\t\tlist_del(&event->migrate_entry);\n\t\tif (event->state >= PERF_EVENT_STATE_OFF)\n\t\t\tevent->state = PERF_EVENT_STATE_INACTIVE;\n\t\taccount_event_cpu(event, dst_cpu);\n\t\tperf_install_in_context(dst_ctx, event, dst_cpu);\n\t\tget_ctx(dst_ctx);\n\t}\n\tmutex_unlock(&dst_ctx->mutex);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "static int perf_event_read_group(struct perf_event *event,\n\t\t\t\t u64 read_format, char __user *buf)\n{\n\tstruct perf_event *leader = event->group_leader, *sub;\n\tint n = 0, size = 0, ret = -EFAULT;\n\tstruct perf_event_context *ctx = leader->ctx;\n\tu64 values[5];\n\tu64 count, enabled, running;\n\n\tmutex_lock(&ctx->mutex);\n\tcount = perf_event_read_value(leader, &enabled, &running);\n\n\tvalues[n++] = 1 + leader->nr_siblings;\n\tif (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)\n\t\tvalues[n++] = enabled;\n\tif (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)\n\t\tvalues[n++] = running;\n\tvalues[n++] = count;\n\tif (read_format & PERF_FORMAT_ID)\n\t\tvalues[n++] = primary_event_id(leader);\n\n\tsize = n * sizeof(u64);\n\n\tif (copy_to_user(buf, values, size))\n\t\tgoto unlock;\n\n\tret = size;\n\n\tlist_for_each_entry(sub, &leader->sibling_list, group_entry) {\n\t\tn = 0;\n\n\t\tvalues[n++] = perf_event_read_value(sub, &enabled, &running);\n\t\tif (read_format & PERF_FORMAT_ID)\n\t\t\tvalues[n++] = primary_event_id(sub);\n\n\t\tsize = n * sizeof(u64);\n\n\t\tif (copy_to_user(buf + ret, values, size)) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto unlock;\n\t\t}\n\n\t\tret += size;\n\t}\nunlock:\n\tmutex_unlock(&ctx->mutex);\n\n\treturn ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "void __detach_mounts(struct dentry *dentry)\n{\n\tstruct mountpoint *mp;\n\tstruct mount *mnt;\n\n\tnamespace_lock();\n\tmp = lookup_mountpoint(dentry);\n\tif (!mp)\n\t\tgoto out_unlock;\n\n\tlock_mount_hash();\n\twhile (!hlist_empty(&mp->m_list)) {\n\t\tmnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);\n\t\tumount_tree(mnt, 0);\n\t}\n\tunlock_mount_hash();\n\tput_mountpoint(mp);\nout_unlock:\n\tnamespace_unlock();\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-284", "cwe_name": "Improper Access Control", "description": "The software does not restrict or incorrectly restricts access to a resource from an unauthorized actor.", "url": "https://cwe.mitre.org/data/definitions/284.html", "label_name": "vulnerable"} {"code": "static void umount_tree(struct mount *mnt, enum umount_tree_flags how)\n{\n\tLIST_HEAD(tmp_list);\n\tstruct mount *p;\n\n\tif (how & UMOUNT_PROPAGATE)\n\t\tpropagate_mount_unlock(mnt);\n\n\t/* Gather the mounts to umount */\n\tfor (p = mnt; p; p = next_mnt(p, mnt)) {\n\t\tp->mnt.mnt_flags |= MNT_UMOUNT;\n\t\tlist_move(&p->mnt_list, &tmp_list);\n\t}\n\n\t/* Hide the mounts from mnt_mounts */\n\tlist_for_each_entry(p, &tmp_list, mnt_list) {\n\t\tlist_del_init(&p->mnt_child);\n\t}\n\n\t/* Add propogated mounts to the tmp_list */\n\tif (how & UMOUNT_PROPAGATE)\n\t\tpropagate_umount(&tmp_list);\n\n\twhile (!list_empty(&tmp_list)) {\n\t\tp = list_first_entry(&tmp_list, struct mount, mnt_list);\n\t\tlist_del_init(&p->mnt_expire);\n\t\tlist_del_init(&p->mnt_list);\n\t\t__touch_mnt_namespace(p->mnt_ns);\n\t\tp->mnt_ns = NULL;\n\t\tif (how & UMOUNT_SYNC)\n\t\t\tp->mnt.mnt_flags |= MNT_SYNC_UMOUNT;\n\n\t\tpin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, &unmounted);\n\t\tif (mnt_has_parent(p)) {\n\t\t\tmnt_add_count(p->mnt_parent, -1);\n\t\t\tumount_mnt(p);\n\t\t}\n\t\tchange_mnt_propagation(p, MS_PRIVATE);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-284", "cwe_name": "Improper Access Control", "description": "The software does not restrict or incorrectly restricts access to a resource from an unauthorized actor.", "url": "https://cwe.mitre.org/data/definitions/284.html", "label_name": "vulnerable"} {"code": "static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm)\n{\n\treturn &crypto_rng_tfm(tfm)->__crt_alg->cra_rng;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen,\n\t\t u8 *dst, unsigned int dlen)\n{\n\treturn crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static void *__dma_alloc_coherent(struct device *dev, size_t size,\n\t\t\t\t dma_addr_t *dma_handle, gfp_t flags,\n\t\t\t\t struct dma_attrs *attrs)\n{\n\tif (dev == NULL) {\n\t\tWARN_ONCE(1, \"Use an actual device structure for DMA allocation\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (IS_ENABLED(CONFIG_ZONE_DMA) &&\n\t dev->coherent_dma_mask <= DMA_BIT_MASK(32))\n\t\tflags |= GFP_DMA;\n\tif (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) {\n\t\tstruct page *page;\n\t\tvoid *addr;\n\n\t\tsize = PAGE_ALIGN(size);\n\t\tpage = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,\n\t\t\t\t\t\t\tget_order(size));\n\t\tif (!page)\n\t\t\treturn NULL;\n\n\t\t*dma_handle = phys_to_dma(dev, page_to_phys(page));\n\t\taddr = page_address(page);\n\t\tif (flags & __GFP_ZERO)\n\t\t\tmemset(addr, 0, size);\n\t\treturn addr;\n\t} else {\n\t\treturn swiotlb_alloc_coherent(dev, size, dma_handle, flags);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "void oz_hcd_get_desc_cnf(void *hport, u8 req_id, int status, const u8 *desc,\n\t\t\tint length, int offset, int total_size)\n{\n\tstruct oz_port *port = hport;\n\tstruct urb *urb;\n\tint err = 0;\n\n\toz_dbg(ON, \"oz_hcd_get_desc_cnf length = %d offs = %d tot_size = %d\\n\",\n\t length, offset, total_size);\n\turb = oz_find_urb_by_id(port, 0, req_id);\n\tif (!urb)\n\t\treturn;\n\tif (status == 0) {\n\t\tint copy_len;\n\t\tint required_size = urb->transfer_buffer_length;\n\n\t\tif (required_size > total_size)\n\t\t\trequired_size = total_size;\n\t\tcopy_len = required_size-offset;\n\t\tif (length <= copy_len)\n\t\t\tcopy_len = length;\n\t\tmemcpy(urb->transfer_buffer+offset, desc, copy_len);\n\t\toffset += copy_len;\n\t\tif (offset < required_size) {\n\t\t\tstruct usb_ctrlrequest *setup =\n\t\t\t\t(struct usb_ctrlrequest *)urb->setup_packet;\n\t\t\tunsigned wvalue = le16_to_cpu(setup->wValue);\n\n\t\t\tif (oz_enqueue_ep_urb(port, 0, 0, urb, req_id))\n\t\t\t\terr = -ENOMEM;\n\t\t\telse if (oz_usb_get_desc_req(port->hpd, req_id,\n\t\t\t\t\tsetup->bRequestType, (u8)(wvalue>>8),\n\t\t\t\t\t(u8)wvalue, setup->wIndex, offset,\n\t\t\t\t\trequired_size-offset)) {\n\t\t\t\toz_dequeue_ep_urb(port, 0, 0, urb);\n\t\t\t\terr = -ENOMEM;\n\t\t\t}\n\t\t\tif (err == 0)\n\t\t\t\treturn;\n\t\t}\n\t}\n\turb->actual_length = total_size;\n\toz_complete_urb(port->ozhcd->hcd, urb, 0);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-189", "cwe_name": "Numeric Errors", "description": "Weaknesses in this category are related to improper calculation or conversion of numbers.", "url": "https://cwe.mitre.org/data/definitions/189.html", "label_name": "vulnerable"} {"code": "static int handle_pte_fault(struct mm_struct *mm,\n\t\t struct vm_area_struct *vma, unsigned long address,\n\t\t pte_t *pte, pmd_t *pmd, unsigned int flags)\n{\n\tpte_t entry;\n\tspinlock_t *ptl;\n\n\t/*\n\t * some architectures can have larger ptes than wordsize,\n\t * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and CONFIG_32BIT=y,\n\t * so READ_ONCE or ACCESS_ONCE cannot guarantee atomic accesses.\n\t * The code below just needs a consistent view for the ifs and\n\t * we later double check anyway with the ptl lock held. So here\n\t * a barrier will do.\n\t */\n\tentry = *pte;\n\tbarrier();\n\tif (!pte_present(entry)) {\n\t\tif (pte_none(entry)) {\n\t\t\tif (vma->vm_ops) {\n\t\t\t\tif (likely(vma->vm_ops->fault))\n\t\t\t\t\treturn do_fault(mm, vma, address, pte,\n\t\t\t\t\t\t\tpmd, flags, entry);\n\t\t\t}\n\t\t\treturn do_anonymous_page(mm, vma, address,\n\t\t\t\t\t\t pte, pmd, flags);\n\t\t}\n\t\treturn do_swap_page(mm, vma, address,\n\t\t\t\t\tpte, pmd, flags, entry);\n\t}\n\n\tif (pte_protnone(entry))\n\t\treturn do_numa_page(mm, vma, address, entry, pte, pmd);\n\n\tptl = pte_lockptr(mm, pmd);\n\tspin_lock(ptl);\n\tif (unlikely(!pte_same(*pte, entry)))\n\t\tgoto unlock;\n\tif (flags & FAULT_FLAG_WRITE) {\n\t\tif (!pte_write(entry))\n\t\t\treturn do_wp_page(mm, vma, address,\n\t\t\t\t\tpte, pmd, ptl, entry);\n\t\tentry = pte_mkdirty(entry);\n\t}\n\tentry = pte_mkyoung(entry);\n\tif (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) {\n\t\tupdate_mmu_cache(vma, address, pte);\n\t} else {\n\t\t/*\n\t\t * This is needed only for protection faults but the arch code\n\t\t * is not yet telling us if this is a protection fault or not.\n\t\t * This still avoids useless tlb flushes for .text page faults\n\t\t * with threads.\n\t\t */\n\t\tif (flags & FAULT_FLAG_WRITE)\n\t\t\tflush_tlb_fix_spurious_fault(vma, address);\n\t}\nunlock:\n\tpte_unmap_unlock(pte, ptl);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static void sctp_generate_timeout_event(struct sctp_association *asoc,\n\t\t\t\t\tsctp_event_timeout_t timeout_type)\n{\n\tstruct net *net = sock_net(asoc->base.sk);\n\tint error = 0;\n\n\tbh_lock_sock(asoc->base.sk);\n\tif (sock_owned_by_user(asoc->base.sk)) {\n\t\tpr_debug(\"%s: sock is busy: timer %d\\n\", __func__,\n\t\t\t timeout_type);\n\n\t\t/* Try again later. */\n\t\tif (!mod_timer(&asoc->timers[timeout_type], jiffies + (HZ/20)))\n\t\t\tsctp_association_hold(asoc);\n\t\tgoto out_unlock;\n\t}\n\n\t/* Is this association really dead and just waiting around for\n\t * the timer to let go of the reference?\n\t */\n\tif (asoc->base.dead)\n\t\tgoto out_unlock;\n\n\t/* Run through the state machine. */\n\terror = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,\n\t\t\t SCTP_ST_TIMEOUT(timeout_type),\n\t\t\t asoc->state, asoc->ep, asoc,\n\t\t\t (void *)timeout_type, GFP_ATOMIC);\n\n\tif (error)\n\t\tasoc->base.sk->sk_err = -error;\n\nout_unlock:\n\tbh_unlock_sock(asoc->base.sk);\n\tsctp_association_put(asoc);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "static int ovl_copy_up_locked(struct dentry *workdir, struct dentry *upperdir,\n\t\t\t struct dentry *dentry, struct path *lowerpath,\n\t\t\t struct kstat *stat, struct iattr *attr,\n\t\t\t const char *link)\n{\n\tstruct inode *wdir = workdir->d_inode;\n\tstruct inode *udir = upperdir->d_inode;\n\tstruct dentry *newdentry = NULL;\n\tstruct dentry *upper = NULL;\n\tumode_t mode = stat->mode;\n\tint err;\n\n\tnewdentry = ovl_lookup_temp(workdir, dentry);\n\terr = PTR_ERR(newdentry);\n\tif (IS_ERR(newdentry))\n\t\tgoto out;\n\n\tupper = lookup_one_len(dentry->d_name.name, upperdir,\n\t\t\t dentry->d_name.len);\n\terr = PTR_ERR(upper);\n\tif (IS_ERR(upper))\n\t\tgoto out1;\n\n\t/* Can't properly set mode on creation because of the umask */\n\tstat->mode &= S_IFMT;\n\terr = ovl_create_real(wdir, newdentry, stat, link, NULL, true);\n\tstat->mode = mode;\n\tif (err)\n\t\tgoto out2;\n\n\tif (S_ISREG(stat->mode)) {\n\t\tstruct path upperpath;\n\t\tovl_path_upper(dentry, &upperpath);\n\t\tBUG_ON(upperpath.dentry != NULL);\n\t\tupperpath.dentry = newdentry;\n\n\t\terr = ovl_copy_up_data(lowerpath, &upperpath, stat->size);\n\t\tif (err)\n\t\t\tgoto out_cleanup;\n\t}\n\n\terr = ovl_copy_xattr(lowerpath->dentry, newdentry);\n\tif (err)\n\t\tgoto out_cleanup;\n\n\tmutex_lock(&newdentry->d_inode->i_mutex);\n\terr = ovl_set_attr(newdentry, stat);\n\tif (!err && attr)\n\t\terr = notify_change(newdentry, attr, NULL);\n\tmutex_unlock(&newdentry->d_inode->i_mutex);\n\tif (err)\n\t\tgoto out_cleanup;\n\n\terr = ovl_do_rename(wdir, newdentry, udir, upper, 0);\n\tif (err)\n\t\tgoto out_cleanup;\n\n\tovl_dentry_update(dentry, newdentry);\n\tnewdentry = NULL;\n\n\t/*\n\t * Non-directores become opaque when copied up.\n\t */\n\tif (!S_ISDIR(stat->mode))\n\t\tovl_dentry_set_opaque(dentry, true);\nout2:\n\tdput(upper);\nout1:\n\tdput(newdentry);\nout:\n\treturn err;\n\nout_cleanup:\n\tovl_cleanup(wdir, newdentry);\n\tgoto out;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)\n{\n\tstruct f_midi *midi = func_to_midi(f);\n\tunsigned i;\n\tint err;\n\n\t/* we only set alt for MIDIStreaming interface */\n\tif (intf != midi->ms_id)\n\t\treturn 0;\n\n\terr = f_midi_start_ep(midi, f, midi->in_ep);\n\tif (err)\n\t\treturn err;\n\n\terr = f_midi_start_ep(midi, f, midi->out_ep);\n\tif (err)\n\t\treturn err;\n\n\t/* pre-allocate write usb requests to use on f_midi_transmit. */\n\twhile (kfifo_avail(&midi->in_req_fifo)) {\n\t\tstruct usb_request *req =\n\t\t\tmidi_alloc_ep_req(midi->in_ep, midi->buflen);\n\n\t\tif (req == NULL)\n\t\t\treturn -ENOMEM;\n\n\t\treq->length = 0;\n\t\treq->complete = f_midi_complete;\n\n\t\tkfifo_put(&midi->in_req_fifo, req);\n\t}\n\n\t/* allocate a bunch of read buffers and queue them all at once. */\n\tfor (i = 0; i < midi->qlen && err == 0; i++) {\n\t\tstruct usb_request *req =\n\t\t\tmidi_alloc_ep_req(midi->out_ep, midi->buflen);\n\n\t\tif (req == NULL)\n\t\t\treturn -ENOMEM;\n\n\t\treq->complete = f_midi_complete;\n\t\terr = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);\n\t\tif (err) {\n\t\t\tERROR(midi, \"%s: couldn't enqueue request: %d\\n\",\n\t\t\t\t midi->out_ep->name, err);\n\t\t\tfree_ep_req(midi->out_ep, req);\n\t\t\treturn err;\n\t\t}\n\t}\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,\n\t\t\t\t const struct bpf_insn *patch, u32 len)\n{\n\tu32 insn_adj_cnt, insn_rest, insn_delta = len - 1;\n\tstruct bpf_prog *prog_adj;\n\n\t/* Since our patchlet doesn't expand the image, we're done. */\n\tif (insn_delta == 0) {\n\t\tmemcpy(prog->insnsi + off, patch, sizeof(*patch));\n\t\treturn prog;\n\t}\n\n\tinsn_adj_cnt = prog->len + insn_delta;\n\n\t/* Several new instructions need to be inserted. Make room\n\t * for them. Likely, there's no need for a new allocation as\n\t * last page could have large enough tailroom.\n\t */\n\tprog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),\n\t\t\t\t GFP_USER);\n\tif (!prog_adj)\n\t\treturn NULL;\n\n\tprog_adj->len = insn_adj_cnt;\n\n\t/* Patching happens in 3 steps:\n\t *\n\t * 1) Move over tail of insnsi from next instruction onwards,\n\t * so we can patch the single target insn with one or more\n\t * new ones (patching is always from 1 to n insns, n > 0).\n\t * 2) Inject new instructions at the target location.\n\t * 3) Adjust branch offsets if necessary.\n\t */\n\tinsn_rest = insn_adj_cnt - off - len;\n\n\tmemmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,\n\t\tsizeof(*patch) * insn_rest);\n\tmemcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);\n\n\tbpf_adj_branches(prog_adj, off, insn_delta);\n\n\treturn prog_adj;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "void sock_release(struct socket *sock)\n{\n\tif (sock->ops) {\n\t\tstruct module *owner = sock->ops->owner;\n\n\t\tsock->ops->release(sock);\n\t\tsock->ops = NULL;\n\t\tmodule_put(owner);\n\t}\n\n\tif (rcu_dereference_protected(sock->wq, 1)->fasync_list)\n\t\tpr_err(\"%s: fasync list not empty!\\n\", __func__);\n\n\tif (!sock->file) {\n\t\tiput(SOCK_INODE(sock));\n\t\treturn;\n\t}\n\tsock->file = NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "static int handle_vmread(struct kvm_vcpu *vcpu)\n{\n\tunsigned long field;\n\tu64 field_value;\n\tunsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);\n\tu32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);\n\tgva_t gva = 0;\n\n\tif (!nested_vmx_check_permission(vcpu))\n\t\treturn 1;\n\n\tif (!nested_vmx_check_vmcs12(vcpu))\n\t\treturn kvm_skip_emulated_instruction(vcpu);\n\n\t/* Decode instruction info and find the field to read */\n\tfield = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));\n\t/* Read the field, zero-extended to a u64 field_value */\n\tif (vmcs12_read_any(vcpu, field, &field_value) < 0) {\n\t\tnested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);\n\t\treturn kvm_skip_emulated_instruction(vcpu);\n\t}\n\t/*\n\t * Now copy part of this value to register or memory, as requested.\n\t * Note that the number of bits actually copied is 32 or 64 depending\n\t * on the guest's mode (32 or 64 bit), not on the given field's length.\n\t */\n\tif (vmx_instruction_info & (1u << 10)) {\n\t\tkvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),\n\t\t\tfield_value);\n\t} else {\n\t\tif (get_vmx_mem_address(vcpu, exit_qualification,\n\t\t\t\tvmx_instruction_info, true, &gva))\n\t\t\treturn 1;\n\t\t/* _system ok, as hardware has verified cpl=0 */\n\t\tkvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,\n\t\t\t &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);\n\t}\n\n\tnested_vmx_succeed(vcpu);\n\treturn kvm_skip_emulated_instruction(vcpu);\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "unsigned paravirt_patch_call(void *insnbuf,\n\t\t\t const void *target, u16 tgt_clobbers,\n\t\t\t unsigned long addr, u16 site_clobbers,\n\t\t\t unsigned len)\n{\n\tstruct branch *b = insnbuf;\n\tunsigned long delta = (unsigned long)target - (addr+5);\n\n\tif (tgt_clobbers & ~site_clobbers)\n\t\treturn len;\t/* target would clobber too much for this site */\n\tif (len < 5)\n\t\treturn len;\t/* call too long for patch site */\n\n\tb->opcode = 0xe8; /* call */\n\tb->delta = delta;\n\tBUILD_BUG_ON(sizeof(*b) != 5);\n\n\treturn 5;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "static inline void vmacache_invalidate(struct mm_struct *mm)\n{\n\tmm->vmacache_seqnum++;\n\n\t/* deal with overflows */\n\tif (unlikely(mm->vmacache_seqnum == 0))\n\t\tvmacache_flush_all(mm);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static int serdes_probe(struct platform_device *pdev)\n{\n\tstruct phy_provider *provider;\n\tstruct serdes_ctrl *ctrl;\n\tunsigned int i;\n\tint ret;\n\n\tctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL);\n\tif (!ctrl)\n\t\treturn -ENOMEM;\n\n\tctrl->dev = &pdev->dev;\n\tctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node);\n\tif (IS_ERR(ctrl->regs))\n\t\treturn PTR_ERR(ctrl->regs);\n\n\tfor (i = 0; i <= SERDES_MAX; i++) {\n\t\tret = serdes_phy_create(ctrl, i, &ctrl->phys[i]);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\tdev_set_drvdata(&pdev->dev, ctrl);\n\n\tprovider = devm_of_phy_provider_register(ctrl->dev,\n\t\t\t\t\t\t serdes_simple_xlate);\n\n\treturn PTR_ERR_OR_ZERO(provider);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static int crypto_report_acomp(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_acomp racomp;\n\n\tstrlcpy(racomp.type, \"acomp\", sizeof(racomp.type));\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_ACOMP,\n\t\t sizeof(struct crypto_report_acomp), &racomp))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "static void update_blocked_averages(int cpu)\n{\n\tstruct rq *rq = cpu_rq(cpu);\n\tstruct cfs_rq *cfs_rq, *pos;\n\tconst struct sched_class *curr_class;\n\tstruct rq_flags rf;\n\tbool done = true;\n\n\trq_lock_irqsave(rq, &rf);\n\tupdate_rq_clock(rq);\n\n\t/*\n\t * Iterates the task_group tree in a bottom up fashion, see\n\t * list_add_leaf_cfs_rq() for details.\n\t */\n\tfor_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {\n\t\tstruct sched_entity *se;\n\n\t\t/* throttled entities do not contribute to load */\n\t\tif (throttled_hierarchy(cfs_rq))\n\t\t\tcontinue;\n\n\t\tif (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))\n\t\t\tupdate_tg_load_avg(cfs_rq, 0);\n\n\t\t/* Propagate pending load changes to the parent, if any: */\n\t\tse = cfs_rq->tg->se[cpu];\n\t\tif (se && !skip_blocked_update(se))\n\t\t\tupdate_load_avg(cfs_rq_of(se), se, 0);\n\n\t\t/*\n\t\t * There can be a lot of idle CPU cgroups. Don't let fully\n\t\t * decayed cfs_rqs linger on the list.\n\t\t */\n\t\tif (cfs_rq_is_decayed(cfs_rq))\n\t\t\tlist_del_leaf_cfs_rq(cfs_rq);\n\n\t\t/* Don't need periodic decay once load/util_avg are null */\n\t\tif (cfs_rq_has_blocked(cfs_rq))\n\t\t\tdone = false;\n\t}\n\n\tcurr_class = rq->curr->sched_class;\n\tupdate_rt_rq_load_avg(rq_clock_task(rq), rq, curr_class == &rt_sched_class);\n\tupdate_dl_rq_load_avg(rq_clock_task(rq), rq, curr_class == &dl_sched_class);\n\tupdate_irq_load_avg(rq, 0);\n\t/* Don't need periodic decay once load/util_avg are null */\n\tif (others_have_blocked(rq))\n\t\tdone = false;\n\n#ifdef CONFIG_NO_HZ_COMMON\n\trq->last_blocked_load_update_tick = jiffies;\n\tif (done)\n\t\trq->has_blocked_load = 0;\n#endif\n\trq_unlock_irqrestore(rq, &rf);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-835", "cwe_name": "Loop with Unreachable Exit Condition ('Infinite Loop')", "description": "The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.", "url": "https://cwe.mitre.org/data/definitions/835.html", "label_name": "vulnerable"} {"code": "static int kvm_ioctl_create_device(struct kvm *kvm,\n\t\t\t\t struct kvm_create_device *cd)\n{\n\tstruct kvm_device_ops *ops = NULL;\n\tstruct kvm_device *dev;\n\tbool test = cd->flags & KVM_CREATE_DEVICE_TEST;\n\tint ret;\n\n\tif (cd->type >= ARRAY_SIZE(kvm_device_ops_table))\n\t\treturn -ENODEV;\n\n\tops = kvm_device_ops_table[cd->type];\n\tif (ops == NULL)\n\t\treturn -ENODEV;\n\n\tif (test)\n\t\treturn 0;\n\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev)\n\t\treturn -ENOMEM;\n\n\tdev->ops = ops;\n\tdev->kvm = kvm;\n\n\tmutex_lock(&kvm->lock);\n\tret = ops->create(dev, cd->type);\n\tif (ret < 0) {\n\t\tmutex_unlock(&kvm->lock);\n\t\tkfree(dev);\n\t\treturn ret;\n\t}\n\tlist_add(&dev->vm_node, &kvm->devices);\n\tmutex_unlock(&kvm->lock);\n\n\tif (ops->init)\n\t\tops->init(dev);\n\n\tret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);\n\tif (ret < 0) {\n\t\tmutex_lock(&kvm->lock);\n\t\tlist_del(&dev->vm_node);\n\t\tmutex_unlock(&kvm->lock);\n\t\tops->destroy(dev);\n\t\treturn ret;\n\t}\n\n\tkvm_get_kvm(kvm);\n\tcd->fd = ret;\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "struct btrfs_device *btrfs_find_device_by_devspec(\n\t\tstruct btrfs_fs_info *fs_info, u64 devid,\n\t\tconst char *device_path)\n{\n\tstruct btrfs_device *device;\n\n\tif (devid) {\n\t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, NULL,\n\t\t\t\t\t NULL);\n\t\tif (!device)\n\t\t\treturn ERR_PTR(-ENOENT);\n\t\treturn device;\n\t}\n\n\tif (!device_path || !device_path[0])\n\t\treturn ERR_PTR(-EINVAL);\n\n\tif (strcmp(device_path, \"missing\") == 0) {\n\t\t/* Find first missing device */\n\t\tlist_for_each_entry(device, &fs_info->fs_devices->devices,\n\t\t\t\t dev_list) {\n\t\t\tif (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,\n\t\t\t\t &device->dev_state) && !device->bdev)\n\t\t\t\treturn device;\n\t\t}\n\t\treturn ERR_PTR(-ENOENT);\n\t}\n\n\treturn btrfs_find_device_by_path(fs_info, device_path);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "int hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2],\n\t\t unsigned char multicast_spec, u8 protocol_version)\n{\n\tstruct hsr_priv *hsr;\n\tstruct hsr_port *port;\n\tint res;\n\n\thsr = netdev_priv(hsr_dev);\n\tINIT_LIST_HEAD(&hsr->ports);\n\tINIT_LIST_HEAD(&hsr->node_db);\n\tINIT_LIST_HEAD(&hsr->self_node_db);\n\n\tether_addr_copy(hsr_dev->dev_addr, slave[0]->dev_addr);\n\n\t/* Make sure we recognize frames from ourselves in hsr_rcv() */\n\tres = hsr_create_self_node(&hsr->self_node_db, hsr_dev->dev_addr,\n\t\t\t\t slave[1]->dev_addr);\n\tif (res < 0)\n\t\treturn res;\n\n\tspin_lock_init(&hsr->seqnr_lock);\n\t/* Overflow soon to find bugs easier: */\n\thsr->sequence_nr = HSR_SEQNR_START;\n\thsr->sup_sequence_nr = HSR_SUP_SEQNR_START;\n\n\ttimer_setup(&hsr->announce_timer, hsr_announce, 0);\n\ttimer_setup(&hsr->prune_timer, hsr_prune_nodes, 0);\n\n\tether_addr_copy(hsr->sup_multicast_addr, def_multicast_addr);\n\thsr->sup_multicast_addr[ETH_ALEN - 1] = multicast_spec;\n\n\thsr->protVersion = protocol_version;\n\n\t/* FIXME: should I modify the value of these?\n\t *\n\t * - hsr_dev->flags - i.e.\n\t *\t\t\tIFF_MASTER/SLAVE?\n\t * - hsr_dev->priv_flags - i.e.\n\t *\t\t\tIFF_EBRIDGE?\n\t *\t\t\tIFF_TX_SKB_SHARING?\n\t *\t\t\tIFF_HSR_MASTER/SLAVE?\n\t */\n\n\t/* Make sure the 1st call to netif_carrier_on() gets through */\n\tnetif_carrier_off(hsr_dev);\n\n\tres = hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER);\n\tif (res)\n\t\treturn res;\n\n\tres = register_netdevice(hsr_dev);\n\tif (res)\n\t\tgoto fail;\n\n\tres = hsr_add_port(hsr, slave[0], HSR_PT_SLAVE_A);\n\tif (res)\n\t\tgoto fail;\n\tres = hsr_add_port(hsr, slave[1], HSR_PT_SLAVE_B);\n\tif (res)\n\t\tgoto fail;\n\n\tmod_timer(&hsr->prune_timer, jiffies + msecs_to_jiffies(PRUNE_PERIOD));\n\n\treturn 0;\n\nfail:\n\thsr_for_each_port(hsr, port)\n\t\thsr_del_port(port);\n\n\treturn res;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-401", "cwe_name": "Missing Release of Memory after Effective Lifetime", "description": "The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.", "url": "https://cwe.mitre.org/data/definitions/401.html", "label_name": "vulnerable"} {"code": "static ssize_t f_hidg_write(struct file *file, const char __user *buffer,\n\t\t\t size_t count, loff_t *offp)\n{\n\tstruct f_hidg *hidg = file->private_data;\n\tstruct usb_request *req;\n\tunsigned long flags;\n\tssize_t status = -ENOMEM;\n\n\tif (!access_ok(buffer, count))\n\t\treturn -EFAULT;\n\n\tspin_lock_irqsave(&hidg->write_spinlock, flags);\n\n#define WRITE_COND (!hidg->write_pending)\ntry_again:\n\t/* write queue */\n\twhile (!WRITE_COND) {\n\t\tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n\t\tif (file->f_flags & O_NONBLOCK)\n\t\t\treturn -EAGAIN;\n\n\t\tif (wait_event_interruptible_exclusive(\n\t\t\t\thidg->write_queue, WRITE_COND))\n\t\t\treturn -ERESTARTSYS;\n\n\t\tspin_lock_irqsave(&hidg->write_spinlock, flags);\n\t}\n\n\thidg->write_pending = 1;\n\treq = hidg->req;\n\tcount = min_t(unsigned, count, hidg->report_length);\n\n\tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n\tstatus = copy_from_user(req->buf, buffer, count);\n\n\tif (status != 0) {\n\t\tERROR(hidg->func.config->cdev,\n\t\t\t\"copy_from_user error\\n\");\n\t\tstatus = -EINVAL;\n\t\tgoto release_write_pending;\n\t}\n\n\tspin_lock_irqsave(&hidg->write_spinlock, flags);\n\n\t/* when our function has been disabled by host */\n\tif (!hidg->req) {\n\t\tfree_ep_req(hidg->in_ep, req);\n\t\t/*\n\t\t * TODO\n\t\t * Should we fail with error here?\n\t\t */\n\t\tgoto try_again;\n\t}\n\n\treq->status = 0;\n\treq->zero = 0;\n\treq->length = count;\n\treq->complete = f_hidg_req_complete;\n\treq->context = hidg;\n\n\tstatus = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC);\n\tif (status < 0) {\n\t\tERROR(hidg->func.config->cdev,\n\t\t\t\"usb_ep_queue error on int endpoint %zd\\n\", status);\n\t\tgoto release_write_pending_unlocked;\n\t} else {\n\t\tstatus = count;\n\t}\n\tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n\n\treturn status;\nrelease_write_pending:\n\tspin_lock_irqsave(&hidg->write_spinlock, flags);\nrelease_write_pending_unlocked:\n\thidg->write_pending = 0;\n\tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n\n\twake_up(&hidg->write_queue);\n\n\treturn status;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-667", "cwe_name": "Improper Locking", "description": "The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.", "url": "https://cwe.mitre.org/data/definitions/667.html", "label_name": "vulnerable"} {"code": "static inline u32 net_hash_mix(const struct net *net)\n{\n#ifdef CONFIG_NET_NS\n\treturn (u32)(((unsigned long)net) >> ilog2(sizeof(*net)));\n#else\n\treturn 0;\n#endif\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "vulnerable"} {"code": "static inline void get_page(struct page *page)\n{\n\tpage = compound_head(page);\n\t/*\n\t * Getting a normal page or the head of a compound page\n\t * requires to already have an elevated page->_refcount.\n\t */\n\tVM_BUG_ON_PAGE(page_ref_count(page) <= 0, page);\n\tpage_ref_inc(page);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "find_extend_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct vm_area_struct *vma, *prev;\n\n\taddr &= PAGE_MASK;\n\tvma = find_vma_prev(mm, addr, &prev);\n\tif (vma && (vma->vm_start <= addr))\n\t\treturn vma;\n\tif (!prev || expand_stack(prev, addr))\n\t\treturn NULL;\n\tif (prev->vm_flags & VM_LOCKED)\n\t\tpopulate_vma_page_range(prev, addr, prev->vm_end, NULL);\n\treturn prev;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-667", "cwe_name": "Improper Locking", "description": "The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.", "url": "https://cwe.mitre.org/data/definitions/667.html", "label_name": "vulnerable"} {"code": "qedi_dbg_notice(struct qedi_dbg_ctx *qedi, const char *func, u32 line,\n\t\tconst char *fmt, ...)\n{\n\tva_list va;\n\tstruct va_format vaf;\n\tchar nfunc[32];\n\n\tmemset(nfunc, 0, sizeof(nfunc));\n\tmemcpy(nfunc, func, sizeof(nfunc) - 1);\n\n\tva_start(va, fmt);\n\n\tvaf.fmt = fmt;\n\tvaf.va = &va;\n\n\tif (!(qedi_dbg_log & QEDI_LOG_NOTICE))\n\t\tgoto ret;\n\n\tif (likely(qedi) && likely(qedi->pdev))\n\t\tpr_notice(\"[%s]:[%s:%d]:%d: %pV\",\n\t\t\t dev_name(&qedi->pdev->dev), nfunc, line,\n\t\t\t qedi->host_no, &vaf);\n\telse\n\t\tpr_notice(\"[0000:00:00.0]:[%s:%d]: %pV\", nfunc, line, &vaf);\n\nret:\n\tva_end(va);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static struct desc_struct *get_desc(unsigned short sel)\n{\n\tstruct desc_ptr gdt_desc = {0, 0};\n\tunsigned long desc_base;\n\n#ifdef CONFIG_MODIFY_LDT_SYSCALL\n\tif ((sel & SEGMENT_TI_MASK) == SEGMENT_LDT) {\n\t\tstruct desc_struct *desc = NULL;\n\t\tstruct ldt_struct *ldt;\n\n\t\t/* Bits [15:3] contain the index of the desired entry. */\n\t\tsel >>= 3;\n\n\t\tmutex_lock(¤t->active_mm->context.lock);\n\t\tldt = current->active_mm->context.ldt;\n\t\tif (ldt && sel < ldt->nr_entries)\n\t\t\tdesc = &ldt->entries[sel];\n\n\t\tmutex_unlock(¤t->active_mm->context.lock);\n\n\t\treturn desc;\n\t}\n#endif\n\tnative_store_gdt(&gdt_desc);\n\n\t/*\n\t * Segment descriptors have a size of 8 bytes. Thus, the index is\n\t * multiplied by 8 to obtain the memory offset of the desired descriptor\n\t * from the base of the GDT. As bits [15:3] of the segment selector\n\t * contain the index, it can be regarded as multiplied by 8 already.\n\t * All that remains is to clear bits [2:0].\n\t */\n\tdesc_base = sel & ~(SEGMENT_RPL_MASK | SEGMENT_TI_MASK);\n\n\tif (desc_base > gdt_desc.size)\n\t\treturn NULL;\n\n\treturn (struct desc_struct *)(gdt_desc.address + desc_base);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx)\n{\n\tstruct desc_struct *desc;\n\tshort sel;\n\n\tsel = get_segment_selector(regs, seg_reg_idx);\n\tif (sel < 0)\n\t\treturn -1L;\n\n\tif (v8086_mode(regs))\n\t\t/*\n\t\t * Base is simply the segment selector shifted 4\n\t\t * bits to the right.\n\t\t */\n\t\treturn (unsigned long)(sel << 4);\n\n\tif (user_64bit_mode(regs)) {\n\t\t/*\n\t\t * Only FS or GS will have a base address, the rest of\n\t\t * the segments' bases are forced to 0.\n\t\t */\n\t\tunsigned long base;\n\n\t\tif (seg_reg_idx == INAT_SEG_REG_FS)\n\t\t\trdmsrl(MSR_FS_BASE, base);\n\t\telse if (seg_reg_idx == INAT_SEG_REG_GS)\n\t\t\t/*\n\t\t\t * swapgs was called at the kernel entry point. Thus,\n\t\t\t * MSR_KERNEL_GS_BASE will have the user-space GS base.\n\t\t\t */\n\t\t\trdmsrl(MSR_KERNEL_GS_BASE, base);\n\t\telse\n\t\t\tbase = 0;\n\t\treturn base;\n\t}\n\n\t/* In protected mode the segment selector cannot be null. */\n\tif (!sel)\n\t\treturn -1L;\n\n\tdesc = get_desc(sel);\n\tif (!desc)\n\t\treturn -1L;\n\n\treturn get_desc_base(desc);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)\n{\n\tstruct task_group *tg = cfs_rq->tg;\n\tstruct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);\n\tu64 amount = 0, min_amount, expires;\n\tint expires_seq;\n\n\t/* note: this is a positive sum as runtime_remaining <= 0 */\n\tmin_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;\n\n\traw_spin_lock(&cfs_b->lock);\n\tif (cfs_b->quota == RUNTIME_INF)\n\t\tamount = min_amount;\n\telse {\n\t\tstart_cfs_bandwidth(cfs_b);\n\n\t\tif (cfs_b->runtime > 0) {\n\t\t\tamount = min(cfs_b->runtime, min_amount);\n\t\t\tcfs_b->runtime -= amount;\n\t\t\tcfs_b->idle = 0;\n\t\t}\n\t}\n\texpires_seq = cfs_b->expires_seq;\n\texpires = cfs_b->runtime_expires;\n\traw_spin_unlock(&cfs_b->lock);\n\n\tcfs_rq->runtime_remaining += amount;\n\t/*\n\t * we may have advanced our local expiration to account for allowed\n\t * spread between our sched_clock and the one on which runtime was\n\t * issued.\n\t */\n\tif (cfs_rq->expires_seq != expires_seq) {\n\t\tcfs_rq->expires_seq = expires_seq;\n\t\tcfs_rq->runtime_expires = expires;\n\t}\n\n\treturn cfs_rq->runtime_remaining > 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "static ssize_t qrtr_tun_write_iter(struct kiocb *iocb, struct iov_iter *from)\n{\n\tstruct file *filp = iocb->ki_filp;\n\tstruct qrtr_tun *tun = filp->private_data;\n\tsize_t len = iov_iter_count(from);\n\tssize_t ret;\n\tvoid *kbuf;\n\n\tkbuf = kzalloc(len, GFP_KERNEL);\n\tif (!kbuf)\n\t\treturn -ENOMEM;\n\n\tif (!copy_from_iter_full(kbuf, len, from))\n\t\treturn -EFAULT;\n\n\tret = qrtr_endpoint_post(&tun->ep, kbuf, len);\n\n\treturn ret < 0 ? ret : len;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-401", "cwe_name": "Missing Release of Memory after Effective Lifetime", "description": "The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.", "url": "https://cwe.mitre.org/data/definitions/401.html", "label_name": "vulnerable"} {"code": "int adis_update_scan_mode(struct iio_dev *indio_dev,\n\tconst unsigned long *scan_mask)\n{\n\tstruct adis *adis = iio_device_get_drvdata(indio_dev);\n\tconst struct iio_chan_spec *chan;\n\tunsigned int scan_count;\n\tunsigned int i, j;\n\t__be16 *tx, *rx;\n\n\tkfree(adis->xfer);\n\tkfree(adis->buffer);\n\n\tif (adis->burst && adis->burst->en)\n\t\treturn adis_update_scan_mode_burst(indio_dev, scan_mask);\n\n\tscan_count = indio_dev->scan_bytes / 2;\n\n\tadis->xfer = kcalloc(scan_count + 1, sizeof(*adis->xfer), GFP_KERNEL);\n\tif (!adis->xfer)\n\t\treturn -ENOMEM;\n\n\tadis->buffer = kcalloc(indio_dev->scan_bytes, 2, GFP_KERNEL);\n\tif (!adis->buffer)\n\t\treturn -ENOMEM;\n\n\trx = adis->buffer;\n\ttx = rx + scan_count;\n\n\tspi_message_init(&adis->msg);\n\n\tfor (j = 0; j <= scan_count; j++) {\n\t\tadis->xfer[j].bits_per_word = 8;\n\t\tif (j != scan_count)\n\t\t\tadis->xfer[j].cs_change = 1;\n\t\tadis->xfer[j].len = 2;\n\t\tadis->xfer[j].delay_usecs = adis->data->read_delay;\n\t\tif (j < scan_count)\n\t\t\tadis->xfer[j].tx_buf = &tx[j];\n\t\tif (j >= 1)\n\t\t\tadis->xfer[j].rx_buf = &rx[j - 1];\n\t\tspi_message_add_tail(&adis->xfer[j], &adis->msg);\n\t}\n\n\tchan = indio_dev->channels;\n\tfor (i = 0; i < indio_dev->num_channels; i++, chan++) {\n\t\tif (!test_bit(chan->scan_index, scan_mask))\n\t\t\tcontinue;\n\t\tif (chan->scan_type.storagebits == 32)\n\t\t\t*tx++ = cpu_to_be16((chan->address + 2) << 8);\n\t\t*tx++ = cpu_to_be16(chan->address << 8);\n\t}\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-401", "cwe_name": "Missing Release of Memory after Effective Lifetime", "description": "The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.", "url": "https://cwe.mitre.org/data/definitions/401.html", "label_name": "vulnerable"} {"code": "static int crypto_report(struct sk_buff *in_skb, struct nlmsghdr *in_nlh,\n\t\t\t struct nlattr **attrs)\n{\n\tstruct net *net = sock_net(in_skb->sk);\n\tstruct crypto_user_alg *p = nlmsg_data(in_nlh);\n\tstruct crypto_alg *alg;\n\tstruct sk_buff *skb;\n\tstruct crypto_dump_info info;\n\tint err;\n\n\tif (!null_terminated(p->cru_name) || !null_terminated(p->cru_driver_name))\n\t\treturn -EINVAL;\n\n\talg = crypto_alg_match(p, 0);\n\tif (!alg)\n\t\treturn -ENOENT;\n\n\terr = -ENOMEM;\n\tskb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);\n\tif (!skb)\n\t\tgoto drop_alg;\n\n\tinfo.in_skb = in_skb;\n\tinfo.out_skb = skb;\n\tinfo.nlmsg_seq = in_nlh->nlmsg_seq;\n\tinfo.nlmsg_flags = 0;\n\n\terr = crypto_report_alg(alg, &info);\n\ndrop_alg:\n\tcrypto_mod_put(alg);\n\n\tif (err)\n\t\treturn err;\n\n\treturn nlmsg_unicast(net->crypto_nlsk, skb, NETLINK_CB(in_skb).portid);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-401", "cwe_name": "Missing Release of Memory after Effective Lifetime", "description": "The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.", "url": "https://cwe.mitre.org/data/definitions/401.html", "label_name": "vulnerable"} {"code": "static int sof_set_get_large_ctrl_data(struct snd_sof_dev *sdev,\n\t\t\t\t struct sof_ipc_ctrl_data *cdata,\n\t\t\t\t struct sof_ipc_ctrl_data_params *sparams,\n\t\t\t\t bool send)\n{\n\tstruct sof_ipc_ctrl_data *partdata;\n\tsize_t send_bytes;\n\tsize_t offset = 0;\n\tsize_t msg_bytes;\n\tsize_t pl_size;\n\tint err;\n\tint i;\n\n\t/* allocate max ipc size because we have at least one */\n\tpartdata = kzalloc(SOF_IPC_MSG_MAX_SIZE, GFP_KERNEL);\n\tif (!partdata)\n\t\treturn -ENOMEM;\n\n\tif (send)\n\t\terr = sof_get_ctrl_copy_params(cdata->type, cdata, partdata,\n\t\t\t\t\t sparams);\n\telse\n\t\terr = sof_get_ctrl_copy_params(cdata->type, partdata, cdata,\n\t\t\t\t\t sparams);\n\tif (err < 0)\n\t\treturn err;\n\n\tmsg_bytes = sparams->msg_bytes;\n\tpl_size = sparams->pl_size;\n\n\t/* copy the header data */\n\tmemcpy(partdata, cdata, sparams->hdr_bytes);\n\n\t/* Serialise IPC TX */\n\tmutex_lock(&sdev->ipc->tx_mutex);\n\n\t/* copy the payload data in a loop */\n\tfor (i = 0; i < sparams->num_msg; i++) {\n\t\tsend_bytes = min(msg_bytes, pl_size);\n\t\tpartdata->num_elems = send_bytes;\n\t\tpartdata->rhdr.hdr.size = sparams->hdr_bytes + send_bytes;\n\t\tpartdata->msg_index = i;\n\t\tmsg_bytes -= send_bytes;\n\t\tpartdata->elems_remaining = msg_bytes;\n\n\t\tif (send)\n\t\t\tmemcpy(sparams->dst, sparams->src + offset, send_bytes);\n\n\t\terr = sof_ipc_tx_message_unlocked(sdev->ipc,\n\t\t\t\t\t\t partdata->rhdr.hdr.cmd,\n\t\t\t\t\t\t partdata,\n\t\t\t\t\t\t partdata->rhdr.hdr.size,\n\t\t\t\t\t\t partdata,\n\t\t\t\t\t\t partdata->rhdr.hdr.size);\n\t\tif (err < 0)\n\t\t\tbreak;\n\n\t\tif (!send)\n\t\t\tmemcpy(sparams->dst + offset, sparams->src, send_bytes);\n\n\t\toffset += pl_size;\n\t}\n\n\tmutex_unlock(&sdev->ipc->tx_mutex);\n\n\tkfree(partdata);\n\treturn err;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-401", "cwe_name": "Missing Release of Memory after Effective Lifetime", "description": "The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.", "url": "https://cwe.mitre.org/data/definitions/401.html", "label_name": "vulnerable"} {"code": "static void set_fdc(int drive)\n{\n\tif (drive >= 0 && drive < N_DRIVE) {\n\t\tfdc = FDC(drive);\n\t\tcurrent_drive = drive;\n\t}\n\tif (fdc != 1 && fdc != 0) {\n\t\tpr_info(\"bad fdc value\\n\");\n\t\treturn;\n\t}\n\tset_dor(fdc, ~0, 8);\n#if N_FDC > 1\n\tset_dor(1 - fdc, ~8, 0);\n#endif\n\tif (FDCS->rawcmd == 2)\n\t\treset_fdc_info(1);\n\tif (fd_inb(FD_STATUS) != STATUS_READY)\n\t\tFDCS->reset = 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": " */\nstatic enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer)\n{\n\tstruct bfq_data *bfqd = container_of(timer, struct bfq_data,\n\t\t\t\t\t idle_slice_timer);\n\tstruct bfq_queue *bfqq = bfqd->in_service_queue;\n\n\t/*\n\t * Theoretical race here: the in-service queue can be NULL or\n\t * different from the queue that was idling if a new request\n\t * arrives for the current queue and there is a full dispatch\n\t * cycle that changes the in-service queue. This can hardly\n\t * happen, but in the worst case we just expire a queue too\n\t * early.\n\t */\n\tif (bfqq)\n\t\tbfq_idle_slice_timer_body(bfqq);\n\n\treturn HRTIMER_NORESTART;", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static inline void get_conn_text(const conn *c, const int af,\n char* addr, struct sockaddr *sock_addr) {\n char addr_text[MAXPATHLEN];\n addr_text[0] = '\\0';\n const char *protoname = \"?\";\n unsigned short port = 0;\n\n switch (af) {\n case AF_INET:\n (void) inet_ntop(af,\n &((struct sockaddr_in *)sock_addr)->sin_addr,\n addr_text,\n sizeof(addr_text) - 1);\n port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port);\n protoname = IS_UDP(c->transport) ? \"udp\" : \"tcp\";\n break;\n\n case AF_INET6:\n addr_text[0] = '[';\n addr_text[1] = '\\0';\n if (inet_ntop(af,\n &((struct sockaddr_in6 *)sock_addr)->sin6_addr,\n addr_text + 1,\n sizeof(addr_text) - 2)) {\n strcat(addr_text, \"]\");\n }\n port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port);\n protoname = IS_UDP(c->transport) ? \"udp6\" : \"tcp6\";\n break;\n\n case AF_UNIX:\n strncpy(addr_text,\n ((struct sockaddr_un *)sock_addr)->sun_path,\n sizeof(addr_text) - 1);\n addr_text[sizeof(addr_text)-1] = '\\0';\n protoname = \"unix\";\n break;\n }\n\n if (strlen(addr_text) < 2) {\n /* Most likely this is a connected UNIX-domain client which\n * has no peer socket address, but there's no portable way\n * to tell for sure.\n */\n sprintf(addr_text, \"\", af);\n }\n\n if (port) {\n sprintf(addr, \"%s:%s:%u\", protoname, addr_text, port);\n } else {\n sprintf(addr, \"%s:%s\", protoname, addr_text);\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "void gtkui_conf_read(void) {\n FILE *fd;\n const char *path;\n char line[100], name[30];\n short value;\n\n#ifdef OS_WINDOWS\n path = ec_win_get_user_dir();\n#else\n /* TODO: get the dopped privs home dir instead of \"/root\" */\n /* path = g_get_home_dir(); */\n path = g_get_tmp_dir();\n#endif\n\n filename = g_build_filename(path, \".ettercap_gtk\", NULL);\n\n DEBUG_MSG(\"gtkui_conf_read: %s\", filename);\n\n fd = fopen(filename, \"r\");\n if(!fd) \n return;\n\n while(fgets(line, 100, fd)) {\n sscanf(line, \"%s = %hd\", name, &value);\n\n gtkui_conf_set(name, value);\n }\n fclose(fd);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "static int cbs_av1_read_uvlc(CodedBitstreamContext *ctx, GetBitContext *gbc,\n const char *name, uint32_t *write_to,\n uint32_t range_min, uint32_t range_max)\n{\n uint32_t value;\n int position, zeroes, i, j;\n char bits[65];\n\n if (ctx->trace_enable)\n position = get_bits_count(gbc);\n\n zeroes = i = 0;\n while (1) {\n if (get_bits_left(gbc) < zeroes + 1) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid uvlc code at \"\n \"%s: bitstream ended.\\n\", name);\n return AVERROR_INVALIDDATA;\n }\n\n if (get_bits1(gbc)) {\n bits[i++] = '1';\n break;\n } else {\n bits[i++] = '0';\n ++zeroes;\n }\n }\n\n if (zeroes >= 32) {\n value = MAX_UINT_BITS(32);\n } else {\n value = get_bits_long(gbc, zeroes);\n\n for (j = 0; j < zeroes; j++)\n bits[i++] = (value >> (zeroes - j - 1) & 1) ? '1' : '0';\n\n value += (1 << zeroes) - 1;\n }\n\n if (ctx->trace_enable) {\n bits[i] = 0;\n ff_cbs_trace_syntax_element(ctx, position, name, NULL,\n bits, value);\n }\n\n if (value < range_min || value > range_max) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"%s out of range: \"\n \"%\"PRIu32\", but must be in [%\"PRIu32\",%\"PRIu32\"].\\n\",\n name, value, range_min, range_max);\n return AVERROR_INVALIDDATA;\n }\n\n *write_to = value;\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-129", "cwe_name": "Improper Validation of Array Index", "description": "The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.", "url": "https://cwe.mitre.org/data/definitions/129.html", "label_name": "vulnerable"} {"code": "static int store_icy(URLContext *h, int size)\n{\n HTTPContext *s = h->priv_data;\n /* until next metadata packet */\n int remaining = s->icy_metaint - s->icy_data_read;\n\n if (remaining < 0)\n return AVERROR_INVALIDDATA;\n\n if (!remaining) {\n /* The metadata packet is variable sized. It has a 1 byte header\n * which sets the length of the packet (divided by 16). If it's 0,\n * the metadata doesn't change. After the packet, icy_metaint bytes\n * of normal data follows. */\n uint8_t ch;\n int len = http_read_stream_all(h, &ch, 1);\n if (len < 0)\n return len;\n if (ch > 0) {\n char data[255 * 16 + 1];\n int ret;\n len = ch * 16;\n ret = http_read_stream_all(h, data, len);\n if (ret < 0)\n return ret;\n data[len + 1] = 0;\n if ((ret = av_opt_set(s, \"icy_metadata_packet\", data, 0)) < 0)\n return ret;\n update_metadata(s, data);\n }\n s->icy_data_read = 0;\n remaining = s->icy_metaint;\n }\n\n return FFMIN(size, remaining);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static int decode_zbuf(AVBPrint *bp, const uint8_t *data,\n const uint8_t *data_end)\n{\n z_stream zstream;\n unsigned char *buf;\n unsigned buf_size;\n int ret;\n\n zstream.zalloc = ff_png_zalloc;\n zstream.zfree = ff_png_zfree;\n zstream.opaque = NULL;\n if (inflateInit(&zstream) != Z_OK)\n return AVERROR_EXTERNAL;\n zstream.next_in = (unsigned char *)data;\n zstream.avail_in = data_end - data;\n av_bprint_init(bp, 0, -1);\n\n while (zstream.avail_in > 0) {\n av_bprint_get_buffer(bp, 1, &buf, &buf_size);\n if (!buf_size) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n zstream.next_out = buf;\n zstream.avail_out = buf_size;\n ret = inflate(&zstream, Z_PARTIAL_FLUSH);\n if (ret != Z_OK && ret != Z_STREAM_END) {\n ret = AVERROR_EXTERNAL;\n goto fail;\n }\n bp->len += zstream.next_out - buf;\n if (ret == Z_STREAM_END)\n break;\n }\n inflateEnd(&zstream);\n bp->str[bp->len] = 0;\n return 0;\n\nfail:\n inflateEnd(&zstream);\n av_bprint_finalize(bp, NULL);\n return ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "static int filter_frame(AVFilterLink *inlink, AVFrame *in)\n{\n AVFilterContext *ctx = inlink->dst;\n BoxBlurContext *s = ctx->priv;\n AVFilterLink *outlink = inlink->dst->outputs[0];\n AVFrame *out;\n int plane;\n int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub);\n int w[4] = { inlink->w, cw, cw, inlink->w };\n int h[4] = { in->height, ch, ch, in->height };\n\n out = ff_get_video_buffer(outlink, outlink->w, outlink->h);\n if (!out) {\n av_frame_free(&in);\n return AVERROR(ENOMEM);\n }\n av_frame_copy_props(out, in);\n\n for (plane = 0; in->data[plane] && plane < 4; plane++)\n hblur(out->data[plane], out->linesize[plane],\n in ->data[plane], in ->linesize[plane],\n w[plane], h[plane], s->radius[plane], s->power[plane],\n s->temp);\n\n for (plane = 0; in->data[plane] && plane < 4; plane++)\n vblur(out->data[plane], out->linesize[plane],\n out->data[plane], out->linesize[plane],\n w[plane], h[plane], s->radius[plane], s->power[plane],\n s->temp);\n\n av_frame_free(&in);\n\n return ff_filter_frame(outlink, out);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void scsi_dma_restart_bh(void *opaque)\n{\n SCSIDiskState *s = opaque;\n SCSIRequest *req;\n SCSIDiskReq *r;\n\n qemu_bh_delete(s->bh);\n s->bh = NULL;\n\n QTAILQ_FOREACH(req, &s->qdev.requests, next) {\n r = DO_UPCAST(SCSIDiskReq, req, req);\n if (r->status & SCSI_REQ_STATUS_RETRY) {\n int status = r->status;\n int ret;\n\n r->status &=\n ~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK);\n\n switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) {\n case SCSI_REQ_STATUS_RETRY_READ:\n scsi_read_data(&r->req);\n break;\n case SCSI_REQ_STATUS_RETRY_WRITE:\n scsi_write_data(&r->req);\n break;\n case SCSI_REQ_STATUS_RETRY_FLUSH:\n ret = scsi_disk_emulate_command(r, r->iov.iov_base);\n if (ret == 0) {\n scsi_req_complete(&r->req, GOOD);\n }\n }\n }\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "char *curl_easy_escape(CURL *handle, const char *string, int inlength)\n{\n size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;\n char *ns;\n char *testing_ptr = NULL;\n unsigned char in; /* we need to treat the characters unsigned */\n size_t newlen = alloc;\n int strindex=0;\n size_t length;\n CURLcode res;\n\n ns = malloc(alloc);\n if(!ns)\n return NULL;\n\n length = alloc-1;\n while(length--) {\n in = *string;\n\n if(Curl_isunreserved(in))\n /* just copy this */\n ns[strindex++]=in;\n else {\n /* encode it */\n newlen += 2; /* the size grows with two, since this'll become a %XX */\n if(newlen > alloc) {\n alloc *= 2;\n testing_ptr = realloc(ns, alloc);\n if(!testing_ptr) {\n free( ns );\n return NULL;\n }\n else {\n ns = testing_ptr;\n }\n }\n\n res = Curl_convert_to_network(handle, &in, 1);\n if(res) {\n /* Curl_convert_to_network calls failf if unsuccessful */\n free(ns);\n return NULL;\n }\n\n snprintf(&ns[strindex], 4, \"%%%02X\", in);\n\n strindex+=3;\n }\n string++;\n }\n ns[strindex]=0; /* terminate it */\n return ns;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "static CURLcode imap_parse_url_path(struct connectdata *conn)\n{\n /* the imap struct is already inited in imap_connect() */\n struct imap_conn *imapc = &conn->proto.imapc;\n struct SessionHandle *data = conn->data;\n const char *path = data->state.path;\n int len;\n\n if(!*path)\n path = \"INBOX\";\n\n /* url decode the path and use this mailbox */\n imapc->mailbox = curl_easy_unescape(data, path, 0, &len);\n if(!imapc->mailbox)\n return CURLE_OUT_OF_MEMORY;\n\n return CURLE_OK;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "int dsOpen(void) {\n struct stat sb;\n int retval;\n char *path = server.diskstore_path;\n\n if ((retval = stat(path,&sb) == -1) && errno != ENOENT) {\n redisLog(REDIS_WARNING, \"Error opening disk store at %s: %s\",\n path, strerror(errno));\n return REDIS_ERR;\n }\n\n /* Directory already in place. Assume everything is ok. */\n if (retval == 0 && S_ISDIR(sb.st_mode)) return REDIS_OK;\n\n /* File exists but it's not a directory */\n if (retval == 0 && !S_ISDIR(sb.st_mode)) {\n redisLog(REDIS_WARNING,\"Disk store at %s is not a directory\", path);\n return REDIS_ERR;\n }\n\n /* New disk store, create the directory structure now, as creating\n * them in a lazy way is not a good idea, after very few insertions\n * we'll need most of the 65536 directories anyway. */\n if (mkdir(path) == -1) {\n redisLog(REDIS_WARNING,\"Disk store init failed creating dir %s: %s\",\n path, strerror(errno));\n return REDIS_ERR;\n }\n return REDIS_OK;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static size_t optsize (lua_State *L, char opt, const char **fmt) {\n switch (opt) {\n case 'B': case 'b': return sizeof(char);\n case 'H': case 'h': return sizeof(short);\n case 'L': case 'l': return sizeof(long);\n case 'T': return sizeof(size_t);\n case 'f': return sizeof(float);\n case 'd': return sizeof(double);\n case 'x': return 1;\n case 'c': return getnum(fmt, 1);\n case 'i': case 'I': {\n int sz = getnum(fmt, sizeof(int));\n if (sz > MAXINTSIZE)\n luaL_error(L, \"integral size %d is larger than limit of %d\",\n sz, MAXINTSIZE);\n return sz;\n }\n default: return 0; /* other cases do not need alignment */\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "choose_filters(struct archive_read *a)\n{\n\tint number_bidders, i, bid, best_bid;\n\tstruct archive_read_filter_bidder *bidder, *best_bidder;\n\tstruct archive_read_filter *filter;\n\tssize_t avail;\n\tint r;\n\n\tfor (;;) {\n\t\tnumber_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]);\n\n\t\tbest_bid = 0;\n\t\tbest_bidder = NULL;\n\n\t\tbidder = a->bidders;\n\t\tfor (i = 0; i < number_bidders; i++, bidder++) {\n\t\t\tif (bidder->bid != NULL) {\n\t\t\t\tbid = (bidder->bid)(bidder, a->filter);\n\t\t\t\tif (bid > best_bid) {\n\t\t\t\t\tbest_bid = bid;\n\t\t\t\t\tbest_bidder = bidder;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* If no bidder, we're done. */\n\t\tif (best_bidder == NULL) {\n\t\t\t/* Verify the filter by asking it for some data. */\n\t\t\t__archive_read_filter_ahead(a->filter, 1, &avail);\n\t\t\tif (avail < 0) {\n\t\t\t\t__archive_read_close_filters(a);\n\t\t\t\t__archive_read_free_filters(a);\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t\t}\n\t\t\ta->archive.compression_name = a->filter->name;\n\t\t\ta->archive.compression_code = a->filter->code;\n\t\t\treturn (ARCHIVE_OK);\n\t\t}\n\n\t\tfilter\n\t\t = (struct archive_read_filter *)calloc(1, sizeof(*filter));\n\t\tif (filter == NULL)\n\t\t\treturn (ARCHIVE_FATAL);\n\t\tfilter->bidder = best_bidder;\n\t\tfilter->archive = a;\n\t\tfilter->upstream = a->filter;\n\t\ta->filter = filter;\n\t\tr = (best_bidder->init)(a->filter);\n\t\tif (r != ARCHIVE_OK) {\n\t\t\t__archive_read_close_filters(a);\n\t\t\t__archive_read_free_filters(a);\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "cib_send_plaintext(int sock, xmlNode * msg)\n{\n char *xml_text = dump_xml_unformatted(msg);\n\n if (xml_text != NULL) {\n int rc = 0;\n char *unsent = xml_text;\n int len = strlen(xml_text);\n\n len++; /* null char */\n crm_trace(\"Message on socket %d: size=%d\", sock, len);\n retry:\n rc = write(sock, unsent, len);\n if (rc < 0) {\n switch (errno) {\n case EINTR:\n case EAGAIN:\n crm_trace(\"Retry\");\n goto retry;\n default:\n crm_perror(LOG_ERR, \"Could only write %d of the remaining %d bytes\", rc, len);\n break;\n }\n\n } else if (rc < len) {\n crm_trace(\"Only sent %d of %d remaining bytes\", rc, len);\n len -= rc;\n unsent += rc;\n goto retry;\n\n } else {\n crm_trace(\"Sent %d bytes: %.100s\", rc, xml_text);\n }\n }\n free(xml_text);\n return NULL;\n\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "int CLASS parse_jpeg(int offset)\n{\n int len, save, hlen, mark;\n fseek(ifp, offset, SEEK_SET);\n if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)\n return 0;\n\n while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)\n {\n order = 0x4d4d;\n len = get2() - 2;\n save = ftell(ifp);\n if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)\n {\n fgetc(ifp);\n raw_height = get2();\n raw_width = get2();\n }\n order = get2();\n hlen = get4();\n if (get4() == 0x48454150) /* \"HEAP\" */\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n#endif\n parse_ciff(save + hlen, len - hlen, 0);\n }\n if (parse_tiff(save + 6))\n apply_tiff();\n fseek(ifp, save + len, SEEK_SET);\n }\n return 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void mspack_fmap_free(void *mem)\n{\n\tfree(mem);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "PHPAPI zend_string *php_escape_shell_cmd(char *str)\n{\n\tregister int x, y, l = (int)strlen(str);\n\tsize_t estimate = (2 * l) + 1;\n\tzend_string *cmd;\n#ifndef PHP_WIN32\n\tchar *p = NULL;\n#endif\n\n\n\tcmd = zend_string_alloc(2 * l, 0);\n\n\tfor (x = 0, y = 0; x < l; x++) {\n\t\tint mb_len = php_mblen(str + x, (l - x));\n\n\t\t/* skip non-valid multibyte characters */\n\t\tif (mb_len < 0) {\n\t\t\tcontinue;\n\t\t} else if (mb_len > 1) {\n\t\t\tmemcpy(ZSTR_VAL(cmd) + y, str + x, mb_len);\n\t\t\ty += mb_len;\n\t\t\tx += mb_len - 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (str[x]) {\n#ifndef PHP_WIN32\n\t\t\tcase '\"':\n\t\t\tcase '\\'':\n\t\t\t\tif (!p && (p = memchr(str + x + 1, str[x], l - x - 1))) {\n\t\t\t\t\t/* noop */\n\t\t\t\t} else if (p && *p == str[x]) {\n\t\t\t\t\tp = NULL;\n\t\t\t\t} else {\n\t\t\t\t\tZSTR_VAL(cmd)[y++] = '\\\\';\n\t\t\t\t}\n\t\t\t\tZSTR_VAL(cmd)[y++] = str[x];\n\t\t\t\tbreak;\n#else\n\t\t\t/* % is Windows specific for environmental variables, ^%PATH% will \n\t\t\t\toutput PATH while ^%PATH^% will not. escapeshellcmd->val will escape all % and !.\n\t\t\t*/\n\t\t\tcase '%':\n\t\t\tcase '!':\n\t\t\tcase '\"':\n\t\t\tcase '\\'':\n#endif\n\t\t\tcase '#': /* This is character-set independent */\n\t\t\tcase '&':\n\t\t\tcase ';':\n\t\t\tcase '`':\n\t\t\tcase '|':\n\t\t\tcase '*':\n\t\t\tcase '?':\n\t\t\tcase '~':\n\t\t\tcase '<':\n\t\t\tcase '>':\n\t\t\tcase '^':\n\t\t\tcase '(':\n\t\t\tcase ')':\n\t\t\tcase '[':\n\t\t\tcase ']':\n\t\t\tcase '{':\n\t\t\tcase '}':\n\t\t\tcase '$':\n\t\t\tcase '\\\\':\n\t\t\tcase '\\x0A': /* excluding these two */\n\t\t\tcase '\\xFF':\n#ifdef PHP_WIN32\n\t\t\t\tZSTR_VAL(cmd)[y++] = '^';\n#else\n\t\t\t\tZSTR_VAL(cmd)[y++] = '\\\\';\n#endif\n\t\t\t\t/* fall-through */\n\t\t\tdefault:\n\t\t\t\tZSTR_VAL(cmd)[y++] = str[x];\n\n\t\t}\n\t}\n\tZSTR_VAL(cmd)[y] = '\\0';\n\n\tif ((estimate - y) > 4096) {\n\t\t/* realloc if the estimate was way overill\n\t\t * Arbitrary cutoff point of 4096 */\n\t\tcmd = zend_string_truncate(cmd, y, 0);\n\t}\n\n\tZSTR_LEN(cmd) = y;\n\n\treturn cmd;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-189", "cwe_name": "Numeric Errors", "description": "Weaknesses in this category are related to improper calculation or conversion of numbers.", "url": "https://cwe.mitre.org/data/definitions/189.html", "label_name": "vulnerable"} {"code": "SPL_METHOD(SplDoublyLinkedList, offsetSet)\n{\n\tzval *zindex, *value;\n\tspl_dllist_object *intern;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"zz\", &zindex, &value) == FAILURE) {\n\t\treturn;\n\t}\n\n\tintern = Z_SPLDLLIST_P(getThis());\n\n\tif (Z_TYPE_P(zindex) == IS_NULL) {\n\t\t/* $obj[] = ... */\n\t\tspl_ptr_llist_push(intern->llist, value);\n\t} else {\n\t\t/* $obj[$foo] = ... */\n\t\tzend_long index;\n\t\tspl_ptr_llist_element *element;\n\n\t\tindex = spl_offset_convert_to_long(zindex);\n\n\t\tif (index < 0 || index >= intern->llist->count) {\n\t\t\tzval_ptr_dtor(value);\n\t\t\tzend_throw_exception(spl_ce_OutOfRangeException, \"Offset invalid or out of range\", 0);\n\t\t\treturn;\n\t\t}\n\n\t\telement = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO);\n\n\t\tif (element != NULL) {\n\t\t\t/* call dtor on the old element as in spl_ptr_llist_pop */\n\t\t\tif (intern->llist->dtor) {\n\t\t\t\tintern->llist->dtor(element);\n\t\t\t}\n\n\t\t\t/* the element is replaced, delref the old one as in\n\t\t\t * SplDoublyLinkedList::pop() */\n\t\t\tzval_ptr_dtor(&element->data);\n\t\t\tZVAL_COPY_VALUE(&element->data, value);\n\n\t\t\t/* new element, call ctor as in spl_ptr_llist_push */\n\t\t\tif (intern->llist->ctor) {\n\t\t\t\tintern->llist->ctor(element);\n\t\t\t}\n\t\t} else {\n\t\t\tzval_ptr_dtor(value);\n\t\t\tzend_throw_exception(spl_ce_OutOfRangeException, \"Offset invalid\", 0);\n\t\t\treturn;\n\t\t}\n\t}\n} /* }}} */", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "static inline int process_numeric_entity(const char **buf, unsigned *code_point)\n{\n\tlong code_l;\n\tint hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows \"X\" */\n\tchar *endptr;\n\n\tif (hexadecimal && (**buf != '\\0'))\n\t\t(*buf)++;\n\t\t\t\n\t/* strtol allows whitespace and other stuff in the beginning\n\t\t* we're not interested */\n\tif ((hexadecimal && !isxdigit(**buf)) ||\n\t\t\t(!hexadecimal && !isdigit(**buf))) {\n\t\treturn FAILURE;\n\t}\n\n\tcode_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10);\n\t/* we're guaranteed there were valid digits, so *endptr > buf */\n\t*buf = endptr;\n\n\tif (**buf != ';')\n\t\treturn FAILURE;\n\n\t/* many more are invalid, but that depends on whether it's HTML\n\t * (and which version) or XML. */\n\tif (code_l > 0x10FFFFL)\n\t\treturn FAILURE;\n\n\tif (code_point != NULL)\n\t\t*code_point = (unsigned)code_l;\n\n\treturn SUCCESS;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static inline void write_s3row_data(\n\tconst entity_stage3_row *r,\n\tunsigned orig_cp,\n\tenum entity_charset charset,\n\tzval *arr)\n{\n\tchar key[9] = \"\"; /* two unicode code points in UTF-8 */\n\tchar entity[LONGEST_ENTITY_LENGTH + 2] = {'&'};\n\tsize_t written_k1;\n\n\twritten_k1 = write_octet_sequence(key, charset, orig_cp);\n\n\tif (!r->ambiguous) {\n\t\tsize_t l = r->data.ent.entity_len;\n\t\tmemcpy(&entity[1], r->data.ent.entity, l);\n\t\tentity[l + 1] = ';';\n\t\tadd_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1);\n\t} else {\n\t\tunsigned i,\n\t\t\t num_entries;\n\t\tconst entity_multicodepoint_row *mcpr = r->data.multicodepoint_table;\n\n\t\tif (mcpr[0].leading_entry.default_entity != NULL) {\n\t\t\tsize_t l = mcpr[0].leading_entry.default_entity_len;\n\t\t\tmemcpy(&entity[1], mcpr[0].leading_entry.default_entity, l);\n\t\t\tentity[l + 1] = ';';\n\t\t\tadd_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1);\n\t\t}\n\t\tnum_entries = mcpr[0].leading_entry.size;\n\t\tfor (i = 1; i <= num_entries; i++) {\n\t\t\tsize_t l,\n\t\t\t\t written_k2;\n\t\t\tunsigned uni_cp,\n\t\t\t\t\t spe_cp;\n\n\t\t\tuni_cp = mcpr[i].normal_entry.second_cp;\n\t\t\tl = mcpr[i].normal_entry.entity_len;\n\n\t\t\tif (!CHARSET_UNICODE_COMPAT(charset)) {\n\t\t\t\tif (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE)\n\t\t\t\t\tcontinue; /* non representable in this charset */\n\t\t\t} else {\n\t\t\t\tspe_cp = uni_cp;\n\t\t\t}\n\t\t\t\n\t\t\twritten_k2 = write_octet_sequence(&key[written_k1], charset, spe_cp);\n\t\t\tmemcpy(&entity[1], mcpr[i].normal_entry.entity, l);\n\t\t\tentity[l + 1] = ';';\n\t\t\tentity[l + 1] = '\\0';\n\t\t\tadd_assoc_stringl_ex(arr, key, written_k1 + written_k2 + 1, entity, l + 1, 1);\n\t\t}\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static int getSingletonPos(const char* str)\n{\n\tint result =-1;\n\tint i=0;\n\tint len = 0;\n\t\n\tif( str && ((len=strlen(str))>0) ){\n\t\tfor( i=0; i= 0 ){ \n\t\t/* (\"Grandfathered Tag. No variants.\"); */\n\t}\n\telse {\t\n\t/* Call ICU variant */\n\t\tvariant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0);\n\t\tif( result > 0 && variant){\n\t\t\t/* Tokenize on the \"_\" or \"-\" */\n\t\t\ttoken = php_strtok_r( variant , DELIMITER , &saved_ptr);\t\n\t\t\tadd_next_index_stringl( return_value, token , strlen(token) ,TRUE );\n\t\t\t/* tokenize on the \"_\" or \"-\" and stop at singleton if any\t*/\n\t\t\twhile( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){\n \t\t\t\tadd_next_index_stringl( return_value, token , strlen(token) ,TRUE );\n\t\t\t}\n\t\t}\n\t\tif( variant ){\n\t\t\tefree( variant );\n\t\t}\n\t}\n\t\t\t\n\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "PHP_FUNCTION(locale_get_display_language) \n{\n get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "SPL_METHOD(RecursiveDirectoryIterator, getChildren)\n{\n\tzval *zpath, *zflags;\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tspl_filesystem_object *subdir;\n\tchar slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tspl_filesystem_object_get_file_name(intern TSRMLS_CC);\n\n\tMAKE_STD_ZVAL(zflags);\n\tMAKE_STD_ZVAL(zpath);\n\tZVAL_LONG(zflags, intern->flags);\n\tZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1);\n\tspl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC);\n\tzval_ptr_dtor(&zpath);\n\tzval_ptr_dtor(&zflags);\n\n\tsubdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC);\n\tif (subdir) {\n\t\tif (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) {\n\t\t\tsubdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, \"%s%c%s\", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);\n\t\t} else {\n\t\t\tsubdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name);\n\t\t\tsubdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len);\n\t\t}\n\t\tsubdir->info_class = intern->info_class;\n\t\tsubdir->file_class = intern->file_class;\n\t\tsubdir->oth = intern->oth;\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)\n{\n\tspl_filesystem_iterator *iterator;\n\tspl_filesystem_object *dir_object;\n\n\tif (by_ref) {\n\t\tzend_error(E_ERROR, \"An iterator cannot be used with foreach by reference\");\n\t}\n\tdir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC);\n\titerator = spl_filesystem_object_to_iterator(dir_object);\n\n\t/* initialize iterator if it wasn't gotten before */\n\tif (iterator->intern.data == NULL) {\n\t\titerator->intern.data = object;\n\t\titerator->intern.funcs = &spl_filesystem_dir_it_funcs;\n\t\t/* ->current must be initialized; rewind doesn't set it and valid\n\t\t * doesn't check whether it's set */\n\t\titerator->current = object;\n\t}\n\tzval_add_ref(&object);\n\t\n\treturn (zend_object_iterator*)iterator;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "SPL_METHOD(SplFileInfo, getPathInfo)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tzend_class_entry *ce = intern->info_class;\n\tzend_error_handling error_handling;\n\t\n\tzend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|C\", &ce) == SUCCESS) {\n\t\tint path_len;\n\t\tchar *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC);\n\t\tif (path) {\n\t\t\tchar *dpath = estrndup(path, path_len);\n\t\t\tpath_len = php_dirname(dpath, path_len);\n\t\t\tspl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC);\n\t\t\tefree(dpath);\n\t\t}\n\t}\n\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC)\n{\n\tspl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter);\n\t\n\tobject->u.dir.index = 0;\n\tif (object->u.dir.dirp) {\n\t\tphp_stream_rewinddir(object->u.dir.dirp);\n\t}\n\tspl_filesystem_dir_read(object TSRMLS_CC);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "SPL_METHOD(SplFileInfo, setFileClass)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tzend_class_entry *ce = spl_ce_SplFileObject;\n\tzend_error_handling error_handling;\n\t\n\tzend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|C\", &ce) == SUCCESS) {\n\t\tintern->file_class = ce;\n\t}\n\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "SPL_METHOD(DirectoryIterator, getFilename)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tRETURN_STRING(intern->u.dir.entry.d_name, 1);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */\n{\n\tchar *p1, *p2;\n\t\n\tif (intern->file_name) {\n\t\tefree(intern->file_name);\n\t}\n\n\tintern->file_name = use_copy ? estrndup(path, len) : path;\n\tintern->file_name_len = len;\n\n\twhile(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) {\n\t\tintern->file_name[intern->file_name_len-1] = 0;\n\t\tintern->file_name_len--;\n\t}\n\n\tp1 = strrchr(intern->file_name, '/');\n#if defined(PHP_WIN32) || defined(NETWARE)\n\tp2 = strrchr(intern->file_name, '\\\\');\n#else\n\tp2 = 0;\n#endif\n\tif (p1 || p2) {\n\t\tintern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name;\n\t} else {\n\t\tintern->_path_len = 0;\n\t}\n\t\n\tif (intern->_path) {\n\t\tefree(intern->_path);\n\t}\n\tintern->_path = estrndup(path, intern->_path_len);\n} /* }}} */", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC)\n{\n\tspl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;\n\tspl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator);\n\t\n\tobject->u.dir.index++;\n\tdo {\n\t\tspl_filesystem_dir_read(object TSRMLS_CC);\n\t} while (spl_filesystem_is_dot(object->u.dir.entry.d_name));\n\tif (object->file_name) {\n\t\tefree(object->file_name);\n\t\tobject->file_name = NULL;\n\t}\n\tif (iterator->current) {\n\t\tzval_ptr_dtor(&iterator->current);\n\t\titerator->current = NULL;\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */\n{\n\tif (intern->u.file.current_line) {\n\t\treturn intern->u.file.current_line_len == 0;\n\t} else if (intern->u.file.current_zval) {\n\t\tswitch(Z_TYPE_P(intern->u.file.current_zval)) {\n\t\tcase IS_STRING:\n\t\t\treturn Z_STRLEN_P(intern->u.file.current_zval) == 0;\n\t\tcase IS_ARRAY:\n\t\t\tif (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)\n\t\t\t&& zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) {\n\t\t\t\tzval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData;\n\t\t\t\t\t\n\t\t\t\treturn Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0;\n\t\t\t}\n\t\t\treturn zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0;\n\t\tcase IS_NULL:\n\t\t\treturn 1;\n\t\tdefault:\n\t\t\treturn 0;\n\t\t}\n\t} else {\n\t\treturn 1;\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "SPL_METHOD(DirectoryIterator, valid)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tRETURN_BOOL(intern->u.dir.entry.d_name[0] != '\\0');\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "PHP_FUNCTION(mb_ereg_search_init)\n{\n\tsize_t argc = ZEND_NUM_ARGS();\n\tzval *arg_str;\n\tchar *arg_pattern = NULL, *arg_options = NULL;\n\tint arg_pattern_len = 0, arg_options_len = 0;\n\tOnigSyntaxType *syntax = NULL;\n\tOnigOptionType option;\n\n\tif (zend_parse_parameters(argc TSRMLS_CC, \"z|ss\", &arg_str, &arg_pattern, &arg_pattern_len, &arg_options, &arg_options_len) == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tif (argc > 1 && arg_pattern_len == 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Empty pattern\");\n\t\tRETURN_FALSE;\n\t}\n\n\toption = MBREX(regex_default_options);\n\tsyntax = MBREX(regex_default_syntax);\n\n\tif (argc == 3) {\n\t\toption = 0;\n\t\t_php_mb_regex_init_options(arg_options, arg_options_len, &option, &syntax, NULL);\n\t}\n\n\tif (argc > 1) {\n\t\t/* create regex pattern buffer */\n\t\tif ((MBREX(search_re) = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), syntax TSRMLS_CC)) == NULL) {\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}\n\n\tif (MBREX(search_str) != NULL) {\n\t\tzval_ptr_dtor(&MBREX(search_str));\n\t\tMBREX(search_str) = (zval *)NULL;\n\t}\n\n\tMBREX(search_str) = arg_str;\n\tZ_ADDREF_P(MBREX(search_str));\n\tSEPARATE_ZVAL_IF_NOT_REF(&MBREX(search_str));\n\n\tMBREX(search_pos) = 0;\n\n\tif (MBREX(search_regs) != NULL) {\n\t\tonig_region_free(MBREX(search_regs), 1);\n\t\tMBREX(search_regs) = (OnigRegion *) NULL;\n\t}\n\n\tRETURN_TRUE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "PHP_FUNCTION(curl_escape)\n{\n\tchar *str = NULL, *res = NULL;\n\tsize_t str_len = 0;\n\tzval *zid;\n\tphp_curl *ch;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"rs\", &zid, &str, &str_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif ((res = curl_easy_escape(ch->cp, str, str_len))) {\n\t\tRETVAL_STRING(res);\n\t\tcurl_free(res);\n\t} else {\n\t\tRETURN_FALSE;\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof)\n{\n\tchar *ksep, *vsep, *val;\n\tsize_t klen, vlen;\n\tsize_t new_vlen;\n\n\tif (var->ptr >= var->end) {\n\t\treturn 0;\n\t}\n\n\tvsep = memchr(var->ptr, '&', var->end - var->ptr);\n\tif (!vsep) {\n\t\tif (!eof) {\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tvsep = var->end;\n\t\t}\n\t}\n\n\tksep = memchr(var->ptr, '=', vsep - var->ptr);\n\tif (ksep) {\n\t\t*ksep = '\\0';\n\t\t/* \"foo=bar&\" or \"foo=&\" */\n\t\tklen = ksep - var->ptr;\n\t\tvlen = vsep - ++ksep;\n\t} else {\n\t\tksep = \"\";\n\t\t/* \"foo&\" */\n\t\tklen = vsep - var->ptr;\n\t\tvlen = 0;\n\t}\n\n\tphp_url_decode(var->ptr, klen);\n\n\tval = estrndup(ksep, vlen);\n\tif (vlen) {\n\t\tvlen = php_url_decode(val, vlen);\n\t}\n\n\tif (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) {\n\t\tphp_register_variable_safe(var->ptr, val, new_vlen, arr);\n\t}\n\tefree(val);\n\n\tvar->ptr = vsep + (vsep != var->end);\n\treturn 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)\n{\n\tchar *ksep, *vsep, *val;\n\tsize_t klen, vlen;\n\t/* FIXME: string-size_t */\n\tunsigned int new_vlen;\n\n\tif (var->ptr >= var->end) {\n\t\treturn 0;\n\t}\n\n\tvsep = memchr(var->ptr, '&', var->end - var->ptr);\n\tif (!vsep) {\n\t\tif (!eof) {\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tvsep = var->end;\n\t\t}\n\t}\n\n\tksep = memchr(var->ptr, '=', vsep - var->ptr);\n\tif (ksep) {\n\t\t*ksep = '\\0';\n\t\t/* \"foo=bar&\" or \"foo=&\" */\n\t\tklen = ksep - var->ptr;\n\t\tvlen = vsep - ++ksep;\n\t} else {\n\t\tksep = \"\";\n\t\t/* \"foo&\" */\n\t\tklen = vsep - var->ptr;\n\t\tvlen = 0;\n\t}\n\n\tphp_url_decode(var->ptr, klen);\n\n\tval = estrndup(ksep, vlen);\n\tif (vlen) {\n\t\tvlen = php_url_decode(val, vlen);\n\t}\n\n\tif (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {\n\t\tphp_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);\n\t}\n\tefree(val);\n\n\tvar->ptr = vsep + (vsep != var->end);\n\treturn 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "static BOOL region16_simplify_bands(REGION16* region)\n{\n\t/** Simplify consecutive bands that touch and have the same items\n\t *\n\t * ==================== ====================\n\t * | 1 | | 2 | | | | |\n\t * ==================== | | | |\n\t * | 1 | | 2 |\t ====> | 1 | | 2 |\n\t * ==================== | | | |\n\t * | 1 | | 2 | | | | |\n\t * ==================== ====================\n\t *\n\t */\n\tRECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp;\n\tint nbRects, finalNbRects;\n\tint bandItems, toMove;\n\tfinalNbRects = nbRects = region16_n_rects(region);\n\n\tif (nbRects < 2)\n\t\treturn TRUE;\n\n\tband1 = region16_rects_noconst(region);\n\tendPtr = band1 + nbRects;\n\n\tdo\n\t{\n\t\tband2 = next_band(band1, endPtr, &bandItems);\n\n\t\tif (band2 == endPtr)\n\t\t\tbreak;\n\n\t\tif ((band1->bottom == band2->top) && band_match(band1, band2, endPtr))\n\t\t{\n\t\t\t/* adjust the bottom of band1 items */\n\t\t\ttmp = band1;\n\n\t\t\twhile (tmp < band2)\n\t\t\t{\n\t\t\t\ttmp->bottom = band2->bottom;\n\t\t\t\ttmp++;\n\t\t\t}\n\n\t\t\t/* override band2, we don't move band1 pointer as the band after band2\n\t\t\t * may be merged too */\n\t\t\tendBand = band2 + bandItems;\n\t\t\ttoMove = (endPtr - endBand) * sizeof(RECTANGLE_16);\n\n\t\t\tif (toMove)\n\t\t\t\tMoveMemory(band2, endBand, toMove);\n\n\t\t\tfinalNbRects -= bandItems;\n\t\t\tendPtr -= bandItems;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tband1 = band2;\n\t\t}\n\t}\n\twhile (TRUE);\n\n\tif (finalNbRects != nbRects)\n\t{\n\t\tint allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16));\n\t\tregion->data = realloc(region->data, allocSize);\n\n\t\tif (!region->data)\n\t\t{\n\t\t\tregion->data = &empty_region;\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tregion->data->nbRects = finalNbRects;\n\t\tregion->data->size = allocSize;\n\t}\n\n\treturn TRUE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-401", "cwe_name": "Missing Release of Memory after Effective Lifetime", "description": "The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.", "url": "https://cwe.mitre.org/data/definitions/401.html", "label_name": "vulnerable"} {"code": "BOOL update_recv(rdpUpdate* update, wStream* s)\n{\n\tBOOL rc = FALSE;\n\tUINT16 updateType;\n\trdpContext* context = update->context;\n\n\tif (Stream_GetRemainingLength(s) < 2)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_GetRemainingLength(s) < 2\");\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT16(s, updateType); /* updateType (2 bytes) */\n\tWLog_Print(update->log, WLOG_TRACE, \"%s Update Data PDU\", UPDATE_TYPE_STRINGS[updateType]);\n\n\tif (!update_begin_paint(update))\n\t\tgoto fail;\n\n\tswitch (updateType)\n\t{\n\t\tcase UPDATE_TYPE_ORDERS:\n\t\t\trc = update_recv_orders(update, s);\n\t\t\tbreak;\n\n\t\tcase UPDATE_TYPE_BITMAP:\n\t\t{\n\t\t\tBITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s);\n\n\t\t\tif (!bitmap_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update);\n\t\t\tfree_bitmap_update(update->context, bitmap_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_PALETTE:\n\t\t{\n\t\t\tPALETTE_UPDATE* palette_update = update_read_palette(update, s);\n\n\t\t\tif (!palette_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_PALETTE - update_read_palette() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->Palette, context, palette_update);\n\t\t\tfree_palette_update(context, palette_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_SYNCHRONIZE:\n\t\t\tupdate_read_synchronize(update, s);\n\t\t\trc = IFCALLRESULT(TRUE, update->Synchronize, context);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\nfail:\n\n\tif (!update_end_paint(update))\n\t\trc = FALSE;\n\n\tif (!rc)\n\t{\n\t\tWLog_ERR(TAG, \"UPDATE_TYPE %s [%\" PRIu16 \"] failed\", update_type_to_string(updateType),\n\t\t updateType);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;\n\tDWORD nbWritten = 0;\n\n\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;\n\n\tStream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */\n\tStream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */\n\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */\n\t/* MS-RDPESP 3.2.5.1.5: The Offset field is ignored\n\t * assert(Offset == 0);\n\t *\n\t * Using a serial printer, noticed though this field could be\n\t * set.\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG, \"writing %\" PRIu32 \" bytes to %s\", Length,\n\t serial->device.name);\n\n\t/* FIXME: CommWriteFile to be replaced by WriteFile */\n\tif (CommWriteFile(serial->hComm, Stream_Pointer(irp->input), Length, &nbWritten, NULL))\n\t{\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"write failure to %s, nbWritten=%\" PRIu32 \", last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, nbWritten, GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}\n\n\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" bytes written to %s\", nbWritten,\n\t serial->device.name);\n\tStream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */\n\tStream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */\n\treturn CHANNEL_RC_OK;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags)\n{\n\tint i;\n\tBYTE iBitmapFormat;\n\tBOOL compressed = FALSE;\n\n\tif (!Stream_EnsureRemainingCapacity(s,\n\t update_approximate_cache_brush_order(cache_brush, flags)))\n\t\treturn FALSE;\n\n\tiBitmapFormat = BPP_BMF[cache_brush->bpp];\n\tStream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */\n\tStream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */\n\tStream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */\n\tStream_Write_UINT8(s, cache_brush->cy); /* cy (1 byte) */\n\tStream_Write_UINT8(s, cache_brush->style); /* style (1 byte) */\n\tStream_Write_UINT8(s, cache_brush->length); /* iBytes (1 byte) */\n\n\tif ((cache_brush->cx == 8) && (cache_brush->cy == 8))\n\t{\n\t\tif (cache_brush->bpp == 1)\n\t\t{\n\t\t\tif (cache_brush->length != 8)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"incompatible 1bpp brush of length:%\" PRIu32 \"\", cache_brush->length);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\tfor (i = 7; i >= 0; i--)\n\t\t\t{\n\t\t\t\tStream_Write_UINT8(s, cache_brush->data[i]);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20))\n\t\t\t\tcompressed = TRUE;\n\t\t\telse if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24))\n\t\t\t\tcompressed = TRUE;\n\t\t\telse if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32))\n\t\t\t\tcompressed = TRUE;\n\n\t\t\tif (compressed != FALSE)\n\t\t\t{\n\t\t\t\t/* compressed brush */\n\t\t\t\tif (!update_compress_brush(s, cache_brush->data, cache_brush->bpp))\n\t\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* uncompressed brush */\n\t\t\t\tint scanline = (cache_brush->bpp / 8) * 8;\n\n\t\t\t\tfor (i = 7; i >= 0; i--)\n\t\t\t\t{\n\t\t\t\t\tStream_Write(s, &cache_brush->data[i * scanline], scanline);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn TRUE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)\n{\n\tif (Stream_GetRemainingLength(s) < 8)\n\t\treturn -1;\n\n\tStream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */\n\tStream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */\n\tStream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */\n\treturn 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)\n{\n\tif (fields->MaxLen < 1)\n\t\tfields->MaxLen = fields->Len;\n\n\tStream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */\n\tStream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */\n\tStream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)\n{\n\tif (fields->Len > 0)\n\t{\n\t\tStream_SetPosition(s, fields->BufferOffset);\n\t\tStream_Write(s, fields->Buffer, fields->Len);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)\n{\n\tnsc_encode_argb_to_aycocg(context, bmpdata, rowstride);\n\n\tif (context->ChromaSubsamplingLevel)\n\t{\n\t\tnsc_encode_subsampling(context);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "horizontalDifference16(unsigned short *ip, int n, int stride, \n\tunsigned short *wp, uint16 *From14)\n{\n register int r1, g1, b1, a1, r2, g2, b2, a2, mask;\n\n/* assumption is unsigned pixel values */\n#undef CLAMP\n#define CLAMP(v) From14[(v) >> 2]\n\n mask = CODE_MASK;\n if (n >= stride) {\n\tif (stride == 3) {\n\t r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);\n\t b2 = wp[2] = CLAMP(ip[2]);\n\t n -= 3;\n\t while (n > 0) {\n\t\tn -= 3;\n\t\twp += 3;\n\t\tip += 3;\n\t\tr1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;\n\t\tg1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;\n\t\tb1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;\n\t }\n\t} else if (stride == 4) {\n\t r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);\n\t b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);\n\t n -= 4;\n\t while (n > 0) {\n\t\tn -= 4;\n\t\twp += 4;\n\t\tip += 4;\n\t\tr1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;\n\t\tg1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;\n\t\tb1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;\n\t\ta1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;\n\t }\n\t} else {\n\t ip += n - 1;\t/* point to last one */\n\t wp += n - 1;\t/* point to last one */\n\t n -= stride;\n\t while (n > 0) {\n\t\tREPEAT(stride, wp[0] = CLAMP(ip[0]);\n\t\t\t\twp[stride] -= wp[0];\n\t\t\t\twp[stride] &= mask;\n\t\t\t\twp--; ip--)\n\t\tn -= stride;\n\t }\n\t REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)\n\t}\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)\n{\n uint8* bufp = buf;\n int32 bytes_read = 0;\n uint16 strip, nstrips = TIFFNumberOfStrips(in);\n uint32 stripsize = TIFFStripSize(in);\n uint32 rows = 0;\n uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);\n tsize_t scanline_size = TIFFScanlineSize(in);\n\n if (scanline_size == 0) {\n TIFFError(\"\", \"TIFF scanline size is zero!\"); \n return 0;\n }\n\n for (strip = 0; strip < nstrips; strip++) {\n bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);\n rows = bytes_read / scanline_size;\n if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))\n TIFFError(\"\", \"Strip %d: read %lu bytes, strip size %lu\",\n (int)strip + 1, (unsigned long) bytes_read,\n (unsigned long)stripsize);\n\n if (bytes_read < 0 && !ignore) {\n TIFFError(\"\", \"Error reading strip %lu after %lu rows\",\n (unsigned long) strip, (unsigned long)rows);\n return 0;\n }\n bufp += bytes_read;\n }\n\n return 1;\n} /* end readContigStripsIntoBuffer */", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "unsigned long lh_char_hash(const void *k)\n{\n\tunsigned int h = 0;\n\tconst char* data = (const char*)k;\n \n\twhile( *data!=0 ) h = h*129 + (unsigned int)(*data++) + LH_PRIME;\n\n\treturn h;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static char *lxclock_name(const char *p, const char *n)\n{\n\tint ret;\n\tint len;\n\tchar *dest;\n\tchar *rundir;\n\n\t/* lockfile will be:\n\t * \"/run\" + \"/lock/lxc/$lxcpath/$lxcname + '\\0' if root\n\t * or\n\t * $XDG_RUNTIME_DIR + \"/lock/lxc/$lxcpath/$lxcname + '\\0' if non-root\n\t */\n\n\t/* length of \"/lock/lxc/\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0' */\n\tlen = strlen(\"/lock/lxc/\") + strlen(n) + strlen(p) + 3;\n\trundir = get_rundir();\n\tif (!rundir)\n\t\treturn NULL;\n\tlen += strlen(rundir);\n\n\tif ((dest = malloc(len)) == NULL) {\n\t\tfree(rundir);\n\t\treturn NULL;\n\t}\n\n\tret = snprintf(dest, len, \"%s/lock/lxc/%s\", rundir, p);\n\tif (ret < 0 || ret >= len) {\n\t\tfree(dest);\n\t\tfree(rundir);\n\t\treturn NULL;\n\t}\n\tret = mkdir_p(dest, 0755);\n\tif (ret < 0) {\n\t\t/* fall back to \"/tmp/\" + $(id -u) + \"/lxc\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0'\n\t\t * * maximum length of $(id -u) is 10 calculated by (log (2 ** (sizeof(uid_t) * 8) - 1) / log 10 + 1)\n\t\t * * lxcpath always starts with '/'\n\t\t */\n\t\tint l2 = 22 + strlen(n) + strlen(p);\n\t\tif (l2 > len) {\n\t\t\tchar *d;\n\t\t\td = realloc(dest, l2);\n\t\t\tif (!d) {\n\t\t\t\tfree(dest);\n\t\t\t\tfree(rundir);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tlen = l2;\n\t\t\tdest = d;\n\t\t}\n\t\tret = snprintf(dest, len, \"/tmp/%d/lxc%s\", geteuid(), p);\n\t\tif (ret < 0 || ret >= len) {\n\t\t\tfree(dest);\n\t\t\tfree(rundir);\n\t\t\treturn NULL;\n\t\t}\n\t\tret = mkdir_p(dest, 0755);\n\t\tif (ret < 0) {\n\t\t\tfree(dest);\n\t\t\tfree(rundir);\n\t\t\treturn NULL;\n\t\t}\n\t\tret = snprintf(dest, len, \"/tmp/%d/lxc%s/.%s\", geteuid(), p, n);\n\t} else\n\t\tret = snprintf(dest, len, \"%s/lock/lxc/%s/.%s\", rundir, p, n);\n\n\tfree(rundir);\n\n\tif (ret < 0 || ret >= len) {\n\t\tfree(dest);\n\t\treturn NULL;\n\t}\n\treturn dest;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-59", "cwe_name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.", "url": "https://cwe.mitre.org/data/definitions/59.html", "label_name": "vulnerable"} {"code": "static void ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc,\n\t\t\t\t\t struct pluto_crypto_req *r,\n\t\t\t\t\t err_t ugh)\n{\n\tstruct ke_continuation *ke = (struct ke_continuation *)pcrc;\n\tstruct msg_digest *md = ke->md;\n\tstruct state *const st = md->st;\n\tstf_status e;\n\n\tDBG(DBG_CONTROLMORE,\n\t DBG_log(\"ikev2 parent inI1outR1: calculated ke+nonce, sending R1\"));\n\n\tif (st == NULL) {\n\t\tloglog(RC_LOG_SERIOUS,\n\t\t \"%s: Request was disconnected from state\",\n\t\t __FUNCTION__);\n\t\tif (ke->md)\n\t\t\trelease_md(ke->md);\n\t\treturn;\n\t}\n\n\t/* XXX should check out ugh */\n\tpassert(ugh == NULL);\n\tpassert(cur_state == NULL);\n\tpassert(st != NULL);\n\n\tpassert(st->st_suspended_md == ke->md);\n\tset_suspended(st, NULL); /* no longer connected or suspended */\n\n\tset_cur_state(st);\n\n\tst->st_calculating = FALSE;\n\n\te = ikev2_parent_inI1outR1_tail(pcrc, r);\n\n\tif (ke->md != NULL) {\n\t\tcomplete_v2_state_transition(&ke->md, e);\n\t\tif (ke->md)\n\t\t\trelease_md(ke->md);\n\t}\n\treset_globals();\n\n\tpassert(GLOBALS_ARE_RESET());\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,\n size_t len, const cdf_header_t *h, cdf_secid_t id)\n{\n\tsize_t ss = CDF_SHORT_SEC_SIZE(h);\n\tsize_t pos = CDF_SHORT_SEC_POS(h, id);\n\tassert(ss == len);\n\tif (pos > CDF_SEC_SIZE(h) * sst->sst_len) {\n\t\tDPRINTF((\"Out of bounds read %\" SIZE_T_FORMAT \"u > %\"\n\t\t SIZE_T_FORMAT \"u\\n\",\n\t\t pos, CDF_SEC_SIZE(h) * sst->sst_len));\n\t\treturn -1;\n\t}\n\t(void)memcpy(((char *)buf) + offs,\n\t ((const char *)sst->sst_tab) + pos, len);\n\treturn len;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)\n{\n\tsize_t i, j;\n\tcdf_secid_t maxsector = (cdf_secid_t)(sat->sat_len * size);\n\n\tDPRINTF((\"Chain:\"));\n\tfor (j = i = 0; sid >= 0; i++, j++) {\n\t\tDPRINTF((\" %d\", sid));\n\t\tif (j >= CDF_LOOP_LIMIT) {\n\t\t\tDPRINTF((\"Counting chain loop limit\"));\n\t\t\terrno = EFTYPE;\n\t\t\treturn (size_t)-1;\n\t\t}\n\t\tif (sid > maxsector) {\n\t\t\tDPRINTF((\"Sector %d > %d\\n\", sid, maxsector));\n\t\t\terrno = EFTYPE;\n\t\t\treturn (size_t)-1;\n\t\t}\n\t\tsid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);\n\t}\n\tif (i == 0) {\n\t\tDPRINTF((\" none, sid: %d\\n\", sid));\n\t\treturn (size_t)-1;\n\n\t}\n\tDPRINTF((\"\\n\"));\n\treturn i;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,\n size_t nbytes)\n{\n\tunion {\n\t\tint32_t l;\n\t\tchar c[sizeof (int32_t)];\n\t} u;\n\tint clazz;\n\tint swap;\n\tstruct stat st;\n\toff_t fsize;\n\tint flags = 0;\n\tElf32_Ehdr elf32hdr;\n\tElf64_Ehdr elf64hdr;\n\tuint16_t type;\n\n\tif (ms->flags & (MAGIC_MIME|MAGIC_APPLE))\n\t\treturn 0;\n\t/*\n\t * ELF executables have multiple section headers in arbitrary\n\t * file locations and thus file(1) cannot determine it from easily.\n\t * Instead we traverse thru all section headers until a symbol table\n\t * one is found or else the binary is stripped.\n\t * Return immediately if it's not ELF (so we avoid pipe2file unless needed).\n\t */\n\tif (buf[EI_MAG0] != ELFMAG0\n\t || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)\n\t || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)\n\t\treturn 0;\n\n\t/*\n\t * If we cannot seek, it must be a pipe, socket or fifo.\n\t */\n\tif((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))\n\t\tfd = file_pipe2file(ms, fd, buf, nbytes);\n\n\tif (fstat(fd, &st) == -1) {\n \t\tfile_badread(ms);\n\t\treturn -1;\n\t}\n\tfsize = st.st_size;\n\n\tclazz = buf[EI_CLASS];\n\n\tswitch (clazz) {\n\tcase ELFCLASS32:\n#undef elf_getu\n#define elf_getu(a, b)\telf_getu32(a, b)\n#undef elfhdr\n#define elfhdr elf32hdr\n#include \"elfclass.h\"\n\tcase ELFCLASS64:\n#undef elf_getu\n#define elf_getu(a, b)\telf_getu64(a, b)\n#undef elfhdr\n#define elfhdr elf64hdr\n#include \"elfclass.h\"\n\tdefault:\n\t if (file_printf(ms, \", unknown class %d\", clazz) == -1)\n\t\t return -1;\n\t break;\n\t}\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)\n{\n\tint rlen, remain;\n\tdpIOCtxPtr dctx;\n\tdynamicPtr *dp;\n\n\tdctx = (dpIOCtxPtr) ctx;\n\tdp = dctx->dp;\n\n\tremain = dp->logicalSize - dp->pos;\n\tif(remain >= len) {\n\t\trlen = len;\n\t} else {\n\t\tif(remain == 0) {\n\t\t\t/* 2.0.34: EOF is incorrect. We use 0 for\n\t\t\t * errors and EOF, just like fileGetbuf,\n\t\t\t * which is a simple fread() wrapper.\n\t\t\t * TBB. Original bug report: Daniel Cowgill. */\n\t\t\treturn 0; /* NOT EOF */\n\t\t}\n\n\t\trlen = remain;\n\t}\n\n\tmemcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);\n\tdp->pos += rlen;\n\n\treturn rlen;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile)\n{\n\tgdIOCtx *out = gdNewFileCtx(outFile);\n\tif (out == NULL) {\n\t\treturn;\n\t}\n\tgdImageWebpCtx(im, out, -1);\n\tout->gd_free(out);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "gdImageScaleTwoPass(const gdImagePtr src, const unsigned int new_width,\n const unsigned int new_height)\n{\n const unsigned int src_width = src->sx;\n const unsigned int src_height = src->sy;\n\tgdImagePtr tmp_im = NULL;\n\tgdImagePtr dst = NULL;\n\n /* First, handle the trivial case. */\n if (src_width == new_width && src_height == new_height) {\n return gdImageClone(src);\n }/* if */\n\n\t/* Convert to truecolor if it isn't; this code requires it. */\n\tif (!src->trueColor) {\n\t\tgdImagePaletteToTrueColor(src);\n\t}/* if */\n\n /* Scale horizontally unless sizes are the same. */\n if (src_width == new_width) {\n tmp_im = src;\n } else {\n tmp_im = gdImageCreateTrueColor(new_width, src_height);\n if (tmp_im == NULL) {\n return NULL;\n }\n gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);\n\n _gdScalePass(src, src_width, tmp_im, new_width, src_height, HORIZONTAL);\n }/* if .. else*/\n\n /* If vertical sizes match, we're done. */\n if (src_height == new_height) {\n assert(tmp_im != src);\n return tmp_im;\n }/* if */\n\n /* Otherwise, we need to scale vertically. */\n\tdst = gdImageCreateTrueColor(new_width, new_height);\n\tif (dst != NULL) {\n gdImageSetInterpolationMethod(dst, src->interpolation_id);\n _gdScalePass(tmp_im, src_height, dst, new_height, new_width, VERTICAL);\n }/* if */\n\n if (src != tmp_im) {\n gdFree(tmp_im);\n }/* if */\n\n\treturn dst;\n}/* gdImageScaleTwoPass*/", "label": 0, "programming_language": "C", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "vulnerable"} {"code": "BGD_DECLARE(void) gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)\n{\n\tint lastBorder;\n\t/* Seek left */\n\tint leftLimit, rightLimit;\n\tint i;\n\tint restoreAlphaBleding;\n\n\tif (border < 0) {\n\t\t/* Refuse to fill to a non-solid border */\n\t\treturn;\n\t}\n\n\tleftLimit = (-1);\n\n\trestoreAlphaBleding = im->alphaBlendingFlag;\n\tim->alphaBlendingFlag = 0;\n\n\tif (x >= im->sx) {\n\t\tx = im->sx - 1;\n\t} else if (x < 0) {\n\t\tx = 0;\n\t}\n\tif (y >= im->sy) {\n\t\ty = im->sy - 1;\n\t} else if (y < 0) {\n\t\ty = 0;\n\t}\n\t\n\tfor (i = x; (i >= 0); i--) {\n\t\tif (gdImageGetPixel (im, i, y) == border) {\n\t\t\tbreak;\n\t\t}\n\t\tgdImageSetPixel (im, i, y, color);\n\t\tleftLimit = i;\n\t}\n\tif (leftLimit == (-1)) {\n\t\tim->alphaBlendingFlag = restoreAlphaBleding;\n\t\treturn;\n\t}\n\t/* Seek right */\n\trightLimit = x;\n\tfor (i = (x + 1); (i < im->sx); i++) {\n\t\tif (gdImageGetPixel (im, i, y) == border) {\n\t\t\tbreak;\n\t\t}\n\t\tgdImageSetPixel (im, i, y, color);\n\t\trightLimit = i;\n\t}\n\t/* Look at lines above and below and start paints */\n\t/* Above */\n\tif (y > 0) {\n\t\tlastBorder = 1;\n\t\tfor (i = leftLimit; (i <= rightLimit); i++) {\n\t\t\tint c;\n\t\t\tc = gdImageGetPixel (im, i, y - 1);\n\t\t\tif (lastBorder) {\n\t\t\t\tif ((c != border) && (c != color)) {\n\t\t\t\t\tgdImageFillToBorder (im, i, y - 1, border, color);\n\t\t\t\t\tlastBorder = 0;\n\t\t\t\t}\n\t\t\t} else if ((c == border) || (c == color)) {\n\t\t\t\tlastBorder = 1;\n\t\t\t}\n\t\t}\n\t}\n\t/* Below */\n\tif (y < ((im->sy) - 1)) {\n\t\tlastBorder = 1;\n\t\tfor (i = leftLimit; (i <= rightLimit); i++) {\n\t\t\tint c = gdImageGetPixel (im, i, y + 1);\n\t\t\tif (lastBorder) {\n\t\t\t\tif ((c != border) && (c != color)) {\n\t\t\t\t\tgdImageFillToBorder (im, i, y + 1, border, color);\n\t\t\t\t\tlastBorder = 0;\n\t\t\t\t}\n\t\t\t} else if ((c == border) || (c == color)) {\n\t\t\t\tlastBorder = 1;\n\t\t\t}\n\t\t}\n\t}\n\tim->alphaBlendingFlag = restoreAlphaBleding;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "txid_snapshot_recv(PG_FUNCTION_ARGS)\n{\n\tStringInfo\tbuf = (StringInfo) PG_GETARG_POINTER(0);\n\tTxidSnapshot *snap;\n\ttxid\t\tlast = 0;\n\tint\t\t\tnxip;\n\tint\t\t\ti;\n\tint\t\t\tavail;\n\tint\t\t\texpect;\n\ttxid\t\txmin,\n\t\t\t\txmax;\n\n\t/*\n\t * load nxip and check for nonsense.\n\t *\n\t * (nxip > avail) check is against int overflows in 'expect'.\n\t */\n\tnxip = pq_getmsgint(buf, 4);\n\tavail = buf->len - buf->cursor;\n\texpect = 8 + 8 + nxip * 8;\n\tif (nxip < 0 || nxip > avail || expect > avail)\n\t\tgoto bad_format;\n\n\txmin = pq_getmsgint64(buf);\n\txmax = pq_getmsgint64(buf);\n\tif (xmin == 0 || xmax == 0 || xmin > xmax || xmax > MAX_TXID)\n\t\tgoto bad_format;\n\n\tsnap = palloc(TXID_SNAPSHOT_SIZE(nxip));\n\tsnap->xmin = xmin;\n\tsnap->xmax = xmax;\n\tsnap->nxip = nxip;\n\tSET_VARSIZE(snap, TXID_SNAPSHOT_SIZE(nxip));\n\n\tfor (i = 0; i < nxip; i++)\n\t{\n\t\ttxid\t\tcur = pq_getmsgint64(buf);\n\n\t\tif (cur <= last || cur < xmin || cur >= xmax)\n\t\t\tgoto bad_format;\n\t\tsnap->xip[i] = cur;\n\t\tlast = cur;\n\t}\n\tPG_RETURN_POINTER(snap);\n\nbad_format:\n\telog(ERROR, \"invalid snapshot data\");\n\treturn (Datum) NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-189", "cwe_name": "Numeric Errors", "description": "Weaknesses in this category are related to improper calculation or conversion of numbers.", "url": "https://cwe.mitre.org/data/definitions/189.html", "label_name": "vulnerable"} {"code": "char *string_crypt(const char *key, const char *salt) {\n assertx(key);\n assertx(salt);\n\n char random_salt[12];\n if (!*salt) {\n memcpy(random_salt,\"$1$\",3);\n ito64(random_salt+3,rand(),8);\n random_salt[11] = '\\0';\n return string_crypt(key, random_salt);\n }\n\n auto const saltLen = strlen(salt);\n if ((saltLen > sizeof(\"$2X$00$\")) &&\n (salt[0] == '$') &&\n (salt[1] == '2') &&\n (salt[2] >= 'a') && (salt[2] <= 'z') &&\n (salt[3] == '$') &&\n (salt[4] >= '0') && (salt[4] <= '3') &&\n (salt[5] >= '0') && (salt[5] <= '9') &&\n (salt[6] == '$')) {\n // Bundled blowfish crypt()\n char output[61];\n\n static constexpr size_t maxSaltLength = 123;\n char paddedSalt[maxSaltLength + 1];\n paddedSalt[0] = paddedSalt[maxSaltLength] = '\\0';\n\n memset(&paddedSalt[1], '$', maxSaltLength - 1);\n memcpy(paddedSalt, salt, std::min(maxSaltLength, saltLen));\n paddedSalt[saltLen] = '\\0';\n\n if (php_crypt_blowfish_rn(key, paddedSalt, output, sizeof(output))) {\n return strdup(output);\n }\n\n } else {\n // System crypt() function\n#ifdef USE_PHP_CRYPT_R\n return php_crypt_r(key, salt);\n#else\n static Mutex mutex;\n Lock lock(mutex);\n char *crypt_res = crypt(key,salt);\n\n if (crypt_res) {\n return strdup(crypt_res);\n }\n#endif\n }\n\n return ((salt[0] == '*') && (salt[1] == '0'))\n ? strdup(\"*1\") : strdup(\"*0\");\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)\n{\n char *str;\n ASN1_TIME atm;\n long offset;\n char buff1[24], buff2[24], *p;\n int i, j;\n\n p = buff1;\n i = ctm->length;\n str = (char *)ctm->data;\n if (ctm->type == V_ASN1_UTCTIME) {\n if ((i < 11) || (i > 17))\n return 0;\n memcpy(p, str, 10);\n p += 10;\n str += 10;\n } else {\n if (i < 13)\n return 0;\n memcpy(p, str, 12);\n p += 12;\n str += 12;\n }\n\n if ((*str == 'Z') || (*str == '-') || (*str == '+')) {\n *(p++) = '0';\n *(p++) = '0';\n } else {\n *(p++) = *(str++);\n *(p++) = *(str++);\n /* Skip any fractional seconds... */\n if (*str == '.') {\n str++;\n while ((*str >= '0') && (*str <= '9'))\n str++;\n }\n\n }\n *(p++) = 'Z';\n *(p++) = '\\0';\n\n if (*str == 'Z')\n offset = 0;\n else {\n if ((*str != '+') && (*str != '-'))\n return 0;\n offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;\n offset += (str[3] - '0') * 10 + (str[4] - '0');\n if (*str == '-')\n offset = -offset;\n }\n atm.type = ctm->type;\n atm.flags = 0;\n atm.length = sizeof(buff2);\n atm.data = (unsigned char *)buff2;\n\n if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)\n return 0;\n\n if (ctm->type == V_ASN1_UTCTIME) {\n i = (buff1[0] - '0') * 10 + (buff1[1] - '0');\n if (i < 50)\n i += 100; /* cf. RFC 2459 */\n j = (buff2[0] - '0') * 10 + (buff2[1] - '0');\n if (j < 50)\n j += 100;\n\n if (i < j)\n return -1;\n if (i > j)\n return 1;\n }\n i = strcmp(buff1, buff2);\n if (i == 0) /* wait a second then return younger :-) */\n return -1;\n else\n return i;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "ParseNameValue(const char * buffer, int bufsize,\n struct NameValueParserData * data)\n{\n\tstruct xmlparser parser;\n\tdata->l_head = NULL;\n\tdata->portListing = NULL;\n\tdata->portListingLength = 0;\n\t/* init xmlparser object */\n\tparser.xmlstart = buffer;\n\tparser.xmlsize = bufsize;\n\tparser.data = data;\n\tparser.starteltfunc = NameValueParserStartElt;\n\tparser.endeltfunc = NameValueParserEndElt;\n\tparser.datafunc = NameValueParserGetData;\n\tparser.attfunc = 0;\n\tparsexml(&parser);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void upnp_event_prepare(struct upnp_event_notify * obj)\n{\n\tstatic const char notifymsg[] =\n\t\t\"NOTIFY %s HTTP/1.1\\r\\n\"\n\t\t\"Host: %s%s\\r\\n\"\n#if (UPNP_VERSION_MAJOR == 1) && (UPNP_VERSION_MINOR == 0)\n\t\t\"Content-Type: text/xml\\r\\n\"\t/* UDA v1.0 */\n#else\n\t\t\"Content-Type: text/xml; charset=\\\"utf-8\\\"\\r\\n\"\t/* UDA v1.1 or later */\n#endif\n\t\t\"Content-Length: %d\\r\\n\"\n\t\t\"NT: upnp:event\\r\\n\"\n\t\t\"NTS: upnp:propchange\\r\\n\"\n\t\t\"SID: %s\\r\\n\"\n\t\t\"SEQ: %u\\r\\n\"\n\t\t\"Connection: close\\r\\n\"\n\t\t\"Cache-Control: no-cache\\r\\n\"\n\t\t\"\\r\\n\"\n\t\t\"%.*s\\r\\n\";\n\tchar * xml;\n\tint l;\n\tif(obj->sub == NULL) {\n\t\tobj->state = EError;\n\t\treturn;\n\t}\n\tswitch(obj->sub->service) {\n\tcase EWanCFG:\n\t\txml = getVarsWANCfg(&l);\n\t\tbreak;\n\tcase EWanIPC:\n\t\txml = getVarsWANIPCn(&l);\n\t\tbreak;\n#ifdef ENABLE_L3F_SERVICE\n\tcase EL3F:\n\t\txml = getVarsL3F(&l);\n\t\tbreak;\n#endif\n#ifdef ENABLE_6FC_SERVICE\n\tcase E6FC:\n\t\txml = getVars6FC(&l);\n\t\tbreak;\n#endif\n#ifdef ENABLE_DP_SERVICE\n\tcase EDP:\n\t\txml = getVarsDP(&l);\n\t\tbreak;\n#endif\n\tdefault:\n\t\txml = NULL;\n\t\tl = 0;\n\t}\n\tobj->buffersize = 1024;\n\tobj->buffer = malloc(obj->buffersize);\n\tif(!obj->buffer) {\n\t\tsyslog(LOG_ERR, \"%s: malloc returned NULL\", \"upnp_event_prepare\");\n\t\tif(xml) {\n\t\t\tfree(xml);\n\t\t}\n\t\tobj->state = EError;\n\t\treturn;\n\t}\n\tobj->tosend = snprintf(obj->buffer, obj->buffersize, notifymsg,\n\t obj->path, obj->addrstr, obj->portstr, l+2,\n\t obj->sub->uuid, obj->sub->seq,\n\t l, xml);\n\tif(xml) {\n\t\tfree(xml);\n\t\txml = NULL;\n\t}\n\tobj->state = ESending;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-252", "cwe_name": "Unchecked Return Value", "description": "The software does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions.", "url": "https://cwe.mitre.org/data/definitions/252.html", "label_name": "vulnerable"} {"code": "read_attribute(cdk_stream_t inp, size_t pktlen, cdk_pkt_userid_t attr,\n\t int name_size)\n{\n\tconst byte *p;\n\tbyte *buf;\n\tsize_t len, nread;\n\tcdk_error_t rc;\n\n\tif (!inp || !attr || !pktlen)\n\t\treturn CDK_Inv_Value;\n\n\tif (DEBUG_PKT)\n\t\t_gnutls_write_log(\"read_attribute: %d octets\\n\",\n\t\t\t\t (int) pktlen);\n\n\t_gnutls_str_cpy(attr->name, name_size, ATTRIBUTE);\n\tattr->len = MIN(name_size, sizeof(ATTRIBUTE) - 1);\n\n\tbuf = cdk_calloc(1, pktlen);\n\tif (!buf)\n\t\treturn CDK_Out_Of_Core;\n\trc = stream_read(inp, buf, pktlen, &nread);\n\tif (rc) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tp = buf;\n\tlen = *p++;\n\tpktlen--;\n\tif (len == 255) {\n\t\tlen = _cdk_buftou32(p);\n\t\tp += 4;\n\t\tpktlen -= 4;\n\t} else if (len >= 192) {\n\t\tif (pktlen < 2) {\n\t\t\tcdk_free(buf);\n\t\t\treturn CDK_Inv_Packet;\n\t\t}\n\t\tlen = ((len - 192) << 8) + *p + 192;\n\t\tp++;\n\t\tpktlen--;\n\t}\n\n\tif (*p != 1) {\t\t/* Currently only 1, meaning an image, is defined. */\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tp++;\n\tlen--;\n\n\tif (len >= pktlen) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tattr->attrib_img = cdk_calloc(1, len);\n\tif (!attr->attrib_img) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Out_Of_Core;\n\t}\n\tattr->attrib_len = len;\n\tmemcpy(attr->attrib_img, p, len);\n\tcdk_free(buf);\n\treturn rc;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "juniper_mlfr_print(netdissect_options *ndo,\n const struct pcap_pkthdr *h, register const u_char *p)\n{\n struct juniper_l2info_t l2info;\n\n l2info.pictype = DLT_JUNIPER_MLFR;\n if (juniper_parse_header(ndo, p, h, &l2info) == 0)\n return l2info.header_len;\n\n p+=l2info.header_len;\n\n /* suppress Bundle-ID if frame was captured on a child-link */\n if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)\n ND_PRINT((ndo, \"Bundle-ID %u, \", l2info.bundle));\n switch (l2info.proto) {\n case (LLC_UI):\n case (LLC_UI<<8):\n isoclns_print(ndo, p, l2info.length, l2info.caplen);\n break;\n case (LLC_UI<<8 | NLPID_Q933):\n case (LLC_UI<<8 | NLPID_IP):\n case (LLC_UI<<8 | NLPID_IP6):\n /* pass IP{4,6} to the OSI layer for proper link-layer printing */\n isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1);\n break;\n default:\n ND_PRINT((ndo, \"unknown protocol 0x%04x, length %u\", l2info.proto, l2info.length));\n }\n\n return l2info.header_len;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "l2tp_q931_cc_print(netdissect_options *ndo, const u_char *dat, u_int length)\n{\n\tprint_16bits_val(ndo, (const uint16_t *)dat);\n\tND_PRINT((ndo, \", %02x\", dat[2]));\n\tif (length > 3) {\n\t\tND_PRINT((ndo, \" \"));\n\t\tprint_string(ndo, dat+3, length-3);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)\n{\n\n\tif (tl1 > l2)\n\t\treturn 0;\n\n\treturn (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "pim_print(netdissect_options *ndo,\n register const u_char *bp, register u_int len, const u_char *bp2)\n{\n\tregister const u_char *ep;\n\tregister const struct pim *pim = (const struct pim *)bp;\n\n\tep = (const u_char *)ndo->ndo_snapend;\n\tif (bp >= ep)\n\t\treturn;\n#ifdef notyet\t\t\t/* currently we see only version and type */\n\tND_TCHECK(pim->pim_rsv);\n#endif\n\n\tswitch (PIM_VER(pim->pim_typever)) {\n\tcase 2:\n\t\tif (!ndo->ndo_vflag) {\n\t\t\tND_PRINT((ndo, \"PIMv%u, %s, length %u\",\n\t\t\t PIM_VER(pim->pim_typever),\n\t\t\t tok2str(pimv2_type_values,\"Unknown Type\",PIM_TYPE(pim->pim_typever)),\n\t\t\t len));\n\t\t\treturn;\n\t\t} else {\n\t\t\tND_PRINT((ndo, \"PIMv%u, length %u\\n\\t%s\",\n\t\t\t PIM_VER(pim->pim_typever),\n\t\t\t len,\n\t\t\t tok2str(pimv2_type_values,\"Unknown Type\",PIM_TYPE(pim->pim_typever))));\n\t\t\tpimv2_print(ndo, bp, len, bp2);\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \"PIMv%u, length %u\",\n\t\t PIM_VER(pim->pim_typever),\n\t\t len));\n\t\tbreak;\n\t}\n\treturn;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "sf_flac_write_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data)\n{\tSF_PRIVATE *psf = (SF_PRIVATE*) client_data ;\n\tFLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;\n\n\tpflac->frame = frame ;\n\tpflac->bufferpos = 0 ;\n\n\tpflac->bufferbackup = SF_FALSE ;\n\tpflac->wbuffer = buffer ;\n\n\tflac_buffer_copy (psf) ;\n\n\treturn FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE ;\n} /* sf_flac_write_callback */", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "sf_flac_write_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data)\n{\tSF_PRIVATE *psf = (SF_PRIVATE*) client_data ;\n\tFLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;\n\n\tpflac->frame = frame ;\n\tpflac->bufferpos = 0 ;\n\n\tpflac->bufferbackup = SF_FALSE ;\n\tpflac->wbuffer = buffer ;\n\n\tflac_buffer_copy (psf) ;\n\n\treturn FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE ;\n} /* sf_flac_write_callback */", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "header_put_le_short (SF_PRIVATE *psf, int x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 2)\n\t{\tpsf->header [psf->headindex++] = x ;\n\t\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\t} ;\n} /* header_put_le_short */", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "header_put_be_int (SF_PRIVATE *psf, int x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 4)\n\t{\tpsf->header [psf->headindex++] = (x >> 24) ;\n\t\tpsf->header [psf->headindex++] = (x >> 16) ;\n\t\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = x ;\n\t\t} ;\n} /* header_put_be_int */", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "header_put_be_short (SF_PRIVATE *psf, int x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 2)\n\t{\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = x ;\n\t\t} ;\n} /* header_put_be_short */", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "sf_open\t(const char *path, int mode, SF_INFO *sfinfo)\n{\tSF_PRIVATE \t*psf ;\n\n\t/* Ultimate sanity check. */\n\tassert (sizeof (sf_count_t) == 8) ;\n\n\tif ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL)\n\t{\tsf_errno = SFE_MALLOC_FAILED ;\n\t\treturn\tNULL ;\n\t\t} ;\n\n\tpsf_init_files (psf) ;\n\n\tpsf_log_printf (psf, \"File : %s\\n\", path) ;\n\n\tif (copy_filename (psf, path) != 0)\n\t{\tsf_errno = psf->error ;\n\t\treturn\tNULL ;\n\t\t} ;\n\n\tpsf->file.mode = mode ;\n\tif (strcmp (path, \"-\") == 0)\n\t\tpsf->error = psf_set_stdio (psf) ;\n\telse\n\t\tpsf->error = psf_fopen (psf) ;\n\n\treturn psf_open_file (psf, sfinfo) ;\n} /* sf_open */", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void role(int argc, char **argv)\n{\n HttpAuth *auth;\n HttpRole *role;\n MprJson *abilities;\n MprBuf *buf;\n MprKey *kp;\n cchar *cmd, *def, *key, *rolename;\n\n if ((auth = app->route->auth) == 0) {\n fail(\"Authentication not configured in package.json\");\n return;\n }\n if (argc < 2) {\n usageError();\n return;\n }\n cmd = argv[0];\n rolename = argv[1];\n\n if (smatch(cmd, \"remove\")) {\n key = sfmt(\"app.http.auth.roles.%s\", rolename);\n if (mprRemoveJson(app->config, key) < 0) {\n fail(\"Cannot remove %s\", key);\n return;\n }\n if (!app->noupdate) {\n savePackage();\n trace(\"Remove\", \"Role %s\", rolename);\n }\n return;\n\n } else if (smatch(cmd, \"add\")) {\n if (smatch(cmd, \"add\")) {\n def = sfmt(\"[%s]\", sjoinArgs(argc - 2, (cchar**) &argv[2], \",\"));\n abilities = mprParseJson(def);\n key = sfmt(\"app.http.auth.roles.%s\", rolename);\n if (mprSetJsonObj(app->config, key, abilities) < 0) {\n fail(\"Cannot update %s\", key);\n return;\n }\n savePackage();\n if (!app->noupdate) {\n trace(\"Update\", \"Role %s\", rolename);\n }\n }\n if (app->show) {\n trace(\"Info\", \"%s %s\", rolename, sjoinArgs(argc - 2, (cchar**) &argv[3], \" \"));\n }\n } else if (smatch(cmd, \"show\")) {\n if ((role = httpLookupRole(app->route->auth, rolename)) == 0) {\n fail(\"Cannot find role %s\", rolename);\n return;\n }\n buf = mprCreateBuf(0, 0);\n for (ITERATE_KEYS(role->abilities, kp)) {\n mprPutToBuf(buf, \"%s \", kp->key);\n }\n trace(\"Info\", \"%s %s\", role->name, mprBufToString(buf));\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static bool inRange(cchar *expr, cchar *version)\n{\n char *cp, *op, *base, *pre, *low, *high, *preVersion;\n int64 min, max, numberVersion;\n ssize i;\n\n if ((i = strspn(expr, \"<>=~ \\t\")) > 0) {\n op = snclone(expr, i);\n expr = &expr[i];\n } else {\n op = 0;\n }\n if (smatch(expr, \"*\")) {\n expr = \"x\";\n }\n version = stok(sclone(version), \"-\", &preVersion);\n base = stok(sclone(expr), \"-\", &pre);\n if (op && (*op == '~' || *op == '^')) {\n if (*op == '^' && schr(version, '-')) {\n return 0;\n }\n base = slower(base);\n if ((cp = scontains(base, \".x\")) != 0) {\n *cp = '\\0';\n }\n return sstarts(version, base);\n }\n if (scontains(base, \"x\") && !schr(version, '-')) {\n low = sfmt(\">=%s\", sreplace(base, \"x\", \"0\"));\n high = sfmt(\"<%s\", sreplace(base, \"x\", VER_FACTOR_MAX));\n return inRange(low, version) && inRange(high, version);\n }\n min = 0;\n max = MAX_VER;\n if (!op) {\n min = max = asNumber(base);\n } else if (smatch(op, \">=\")) {\n min = asNumber(base);\n } else if (*op == '>') {\n min = asNumber(base) + 1;\n } else if (smatch(op, \"<=\")) {\n max = asNumber(base);\n } else if (*op == '<') {\n max = asNumber(base) - 1;\n } else {\n min = max = asNumber(base);\n }\n numberVersion = asNumber(version);\n if (min <= numberVersion && numberVersion <= max) {\n if ((pre && smatch(pre, preVersion)) || (!pre && !preVersion)) {\n return 1;\n }\n }\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static cchar *getVxCPU(cchar *arch)\n{\n char *cpu, *family;\n\n family = stok(sclone(arch), \":\", &cpu);\n if (!cpu || *cpu == '\\0') {\n if (smatch(family, \"i386\")) {\n cpu = \"I80386\";\n } else if (smatch(family, \"i486\")) {\n cpu = \"I80486\";\n } else if (smatch(family, \"x86\") | sends(family, \"86\")) {\n cpu = \"PENTIUM\";\n } else if (scaselessmatch(family, \"mips\")) {\n cpu = \"MIPS32\";\n } else if (scaselessmatch(family, \"arm\")) {\n cpu = \"ARM7TDMI\";\n } else if (scaselessmatch(family, \"ppc\")) {\n cpu = \"PPC\";\n } else {\n cpu = (char*) arch;\n }\n }\n return supper(cpu);\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "PUBLIC int httpGetIntParam(HttpConn *conn, cchar *var, int defaultValue)\n{\n cchar *value;\n\n value = mprLookupJson(httpGetParams(conn), var);\n return (value) ? (int) stoi(value) : defaultValue;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static void parseServerAccount(HttpRoute *route, cchar *key, MprJson *prop)\n{\n cchar *value;\n\n if ((value = mprGetJson(prop, \"user\")) != 0) {\n if (!smatch(value, \"_unchanged_\") && !mprGetDebugMode()) {\n httpSetGroupAccount(value);\n }\n }\n if ((value = mprGetJson(prop, \"user\")) != 0) {\n if (!smatch(value, \"_unchanged_\") && !mprGetDebugMode()) {\n httpSetUserAccount(value);\n }\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "PUBLIC MprJson *mprLookupJsonObj(MprJson *obj, cchar *name)\n{\n MprJson *child;\n int i, index;\n\n if (!obj || !name) {\n return 0;\n }\n if (obj->type & MPR_JSON_OBJ) {\n for (ITERATE_JSON(obj, child, i)) {\n if (smatch(child->name, name)) {\n return child;\n }\n }\n } else if (obj->type & MPR_JSON_ARRAY) {\n /*\n Note this does a linear traversal counting array elements. Not the fastest.\n This code is not optimized for huge arrays.\n */\n if (*name == '$') {\n return 0;\n }\n index = (int) stoi(name);\n for (ITERATE_JSON(obj, child, i)) {\n if (i == index) {\n return child;\n }\n }\n }\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static MprJson *queryCore(MprJson *obj, cchar *key, MprJson *value, int flags)\n{\n MprJson *result, *child;\n char *property, *rest;\n int termType;\n\n if (obj == 0 || key == 0 || *key == '\\0' || obj->type & MPR_JSON_VALUE) {\n return 0;\n }\n result = 0;\n for (property = getNextTerm(obj, value, sclone(key), &rest, &termType); property; ) {\n if (termType & JSON_PROP_COMPOUND) {\n result = queryCompound(obj, property, rest, value, flags, termType);\n break;\n\n } else if (rest == 0) {\n if (!result && !value) {\n result = mprCreateJson(MPR_JSON_ARRAY);\n }\n appendItem(result, queryLeaf(obj, property, value, flags));\n break;\n\n } else if ((child = mprLookupJsonObj(obj, property)) == 0) {\n if (value) {\n child = mprCreateJson(termType & JSON_PROP_ARRAY ? MPR_JSON_ARRAY : MPR_JSON_OBJ);\n setProperty(obj, sclone(property), child);\n obj = (MprJson*) child;\n } else {\n break;\n }\n }\n obj = (MprJson*) child;\n property = getNextTerm(obj, value, 0, &rest, &termType);\n }\n return result ? result : mprCreateJson(MPR_JSON_ARRAY);\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static void parseCertFields(MprBuf *buf, char *prefix, char *prefix2, char *info)\n{\n char c, *cp, *term, *key, *value;\n\n term = cp = info;\n do {\n c = *cp;\n if (c == '/' || c == '\\0') {\n *cp = '\\0';\n key = stok(term, \"=\", &value);\n if (smatch(key, \"emailAddress\")) {\n key = \"EMAIL\";\n }\n mprPutToBuf(buf, \"%s%s%s=%s,\", prefix, prefix2, key, value);\n term = &cp[1];\n *cp = c;\n }\n } while (*cp++ != '\\0');\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "char *strdup(const char *s1)\n{\n\tchar *s2 = 0;\n\tif (s1) {\n\t\ts2 = malloc(strlen(s1) + 1);\n\t\tstrcpy(s2, s1);\n\t}\n\treturn s2;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void show_object(struct object *obj,\n\t\t\tstruct strbuf *path, const char *last,\n\t\t\tvoid *data)\n{\n\tchar *name = path_name(path, last);\n\n\tadd_preferred_base_object(name);\n\tadd_object_entry(obj->oid.hash, obj->type, name, 0);\n\tobj->flags |= OBJECT_ADDED;\n\n\t/*\n\t * We will have generated the hash from the name,\n\t * but not saved a pointer to it - we can free it\n\t */\n\tfree((char *)name);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void show_object(struct object *obj,\n\t\t\tstruct strbuf *path, const char *component,\n\t\t\tvoid *cb_data)\n{\n\tstruct rev_list_info *info = cb_data;\n\tfinish_object(obj, path, component, cb_data);\n\tif (info->flags & REV_LIST_QUIET)\n\t\treturn;\n\tshow_object_with_name(stdout, obj, path, component);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void show_object(struct object *obj,\n\t\t\tstruct strbuf *path, const char *component,\n\t\t\tvoid *cb_data)\n{\n\tstruct rev_list_info *info = cb_data;\n\tfinish_object(obj, path, component, cb_data);\n\tif (info->flags & REV_LIST_QUIET)\n\t\treturn;\n\tshow_object_with_name(stdout, obj, path, component);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static void mark_commit(struct commit *c, void *data)\n{\n\tmark_object(&c->object, NULL, NULL, data);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static bool caller_is_in_ancestor(pid_t pid, const char *contrl, const char *cg, char **nextcg)\n{\n\tchar fnam[PROCLEN];\n\tFILE *f;\n\tbool answer = false;\n\tchar *line = NULL;\n\tsize_t len = 0;\n\tint ret;\n\n\tret = snprintf(fnam, PROCLEN, \"/proc/%d/cgroup\", pid);\n\tif (ret < 0 || ret >= PROCLEN)\n\t\treturn false;\n\tif (!(f = fopen(fnam, \"r\")))\n\t\treturn false;\n\n\twhile (getline(&line, &len, f) != -1) {\n\t\tchar *c1, *c2, *linecmp;\n\t\tif (!line[0])\n\t\t\tcontinue;\n\t\tc1 = strchr(line, ':');\n\t\tif (!c1)\n\t\t\tgoto out;\n\t\tc1++;\n\t\tc2 = strchr(c1, ':');\n\t\tif (!c2)\n\t\t\tgoto out;\n\t\t*c2 = '\\0';\n\t\tif (strcmp(c1, contrl) != 0)\n\t\t\tcontinue;\n\t\tc2++;\n\t\tstripnewline(c2);\n\t\tprune_init_slice(c2);\n\t\t/*\n\t\t * callers pass in '/' for root cgroup, otherwise they pass\n\t\t * in a cgroup without leading '/'\n\t\t */\n\t\tlinecmp = *cg == '/' ? c2 : c2+1;\n\t\tif (strncmp(linecmp, cg, strlen(linecmp)) != 0) {\n\t\t\tif (nextcg)\n\t\t\t\t*nextcg = get_next_cgroup_dir(linecmp, cg);\n\t\t\tgoto out;\n\t\t}\n\t\tanswer = true;\n\t\tgoto out;\n\t}\n\nout:\n\tfclose(f);\n\tfree(line);\n\treturn answer;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "static MYSQL *db_connect(char *host, char *database,\n char *user, char *passwd)\n{\n MYSQL *mysql;\n if (verbose)\n fprintf(stdout, \"Connecting to %s\\n\", host ? host : \"localhost\");\n if (!(mysql= mysql_init(NULL)))\n return 0;\n if (opt_compress)\n mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS);\n if (opt_local_file)\n mysql_options(mysql,MYSQL_OPT_LOCAL_INFILE,\n\t\t (char*) &opt_local_file);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n {\n mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n\t\t opt_ssl_capath, opt_ssl_cipher);\n mysql_options(mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);\n mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);\n }\n mysql_options(mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,\n (char*)&opt_ssl_verify_server_cert);\n#endif\n if (opt_protocol)\n mysql_options(mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n if (opt_bind_addr)\n mysql_options(mysql,MYSQL_OPT_BIND,opt_bind_addr);\n#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n if (shared_memory_base_name)\n mysql_options(mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset);\n mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD,\n \"program_name\", \"mysqlimport\");\n if (!(mysql_real_connect(mysql,host,user,passwd,\n database,opt_mysql_port,opt_mysql_unix_port,\n 0)))\n {\n ignore_errors=0;\t /* NO RETURN FROM db_error */\n db_error(mysql);\n }\n mysql->reconnect= 0;\n if (verbose)\n fprintf(stdout, \"Selecting database %s\\n\", database);\n if (mysql_select_db(mysql, database))\n {\n ignore_errors=0;\n db_error(mysql);\n }\n return mysql;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": "t1mac_output_ascii(char *s, int len)\n{\n if (blocktyp == POST_BINARY) {\n output_current_post();\n blocktyp = POST_ASCII;\n }\n /* Mac line endings */\n if (len > 0 && s[len-1] == '\\n')\n s[len-1] = '\\r';\n t1mac_output_data((byte *)s, len);\n if (strncmp(s, \"/FontName\", 9) == 0) {\n for (s += 9; isspace(*s); s++) ;\n if (*s == '/') {\n const char *t = ++s;\n while (*t && !isspace(*t)) t++;\n free(font_name);\n font_name = (char *)malloc(t - s + 1);\n memcpy(font_name, s, t - s);\n font_name[t - s] = 0;\n }\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "int main(int argc, char *argv[]) {\n struct mschm_decompressor *chmd;\n struct mschmd_header *chm;\n struct mschmd_file *file, **f;\n unsigned int numf, i;\n\n setbuf(stdout, NULL);\n setbuf(stderr, NULL);\n user_umask = umask(0); umask(user_umask);\n\n MSPACK_SYS_SELFTEST(i);\n if (i) return 0;\n\n if ((chmd = mspack_create_chm_decompressor(NULL))) {\n for (argv++; *argv; argv++) {\n printf(\"%s\\n\", *argv);\n if ((chm = chmd->open(chmd, *argv))) {\n\n\t/* build an ordered list of files for maximum extraction speed */\n\tfor (numf=0, file=chm->files; file; file = file->next) numf++;\n\tif ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) {\n\t for (i=0, file=chm->files; file; file = file->next) f[i++] = file;\n\t qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc);\n\n\t for (i = 0; i < numf; i++) {\n\t char *outname = create_output_name((unsigned char *)f[i]->filename,NULL,0,1,0);\n\t printf(\"Extracting %s\\n\", outname);\n\t ensure_filepath(outname);\n\t if (chmd->extract(chmd, f[i], outname)) {\n\t printf(\"%s: extract error on \\\"%s\\\": %s\\n\",\n\t\t *argv, f[i]->filename, ERROR(chmd));\n\t }\n\t free(outname);\n\t }\n\t free(f);\n\t}\n\tchmd->close(chmd, chm);\n }\n else {\n\tprintf(\"%s: can't open -- %s\\n\", *argv, ERROR(chmd));\n }\n }\n mspack_destroy_chm_decompressor(chmd);\n }\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "int read_filesystem_tables_4()\n{\n\tlong long directory_table_end, table_start;\n\n\tif(read_xattrs_from_disk(fd, &sBlk.s, no_xattrs, &table_start) == 0)\n\t\treturn FALSE;\n\n\tif(read_uids_guids(&table_start) == FALSE)\n\t\treturn FALSE;\n\n\tif(parse_exports_table(&table_start) == FALSE)\n\t\treturn FALSE;\n\n\tif(read_fragment_table(&directory_table_end) == FALSE)\n\t\treturn FALSE;\n\n\tif(read_inode_table(sBlk.s.inode_table_start,\n\t\t\t\tsBlk.s.directory_table_start) == FALSE)\n\t\treturn FALSE;\n\n\tif(read_directory_table(sBlk.s.directory_table_start,\n\t\t\t\tdirectory_table_end) == FALSE)\n\t\treturn FALSE;\n\n\tif(no_xattrs)\n\t\tsBlk.s.xattr_id_table_start = SQUASHFS_INVALID_BLK;\n\n\treturn TRUE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt)\n{\n\tint n;\n\tassert(cnt >= 0);\n\tassert(buf);\n\n\tJAS_DBGLOG(100, (\"mem_read(%p, %p, %d)\\n\", obj, buf, cnt));\n\tjas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;\n\tn = m->len_ - m->pos_;\n\tcnt = JAS_MIN(n, cnt);\n\tmemcpy(buf, &m->buf_[m->pos_], cnt);\n\tm->pos_ += cnt;\n\treturn cnt;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len)\n{\n\tjas_stream_t *in;\n\tjas_iccprof_t *prof;\n\tif (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len)))\n\t\tgoto error;\n\tif (!(prof = jas_iccprof_load(in)))\n\t\tgoto error;\n\tjas_stream_close(in);\n\treturn prof;\nerror:\n\tif (in)\n\t\tjas_stream_close(in);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val)\n{\n\tint i;\n\tint c;\n\tfor (i = n; i > 0; --i) {\n\t\tc = (val >> (8 * (i - 1))) & 0xff;\n\t\tif (jas_stream_putc(out, c) == EOF)\n\t\t\treturn -1;\n\t}\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 8, &tmp))\n\t\treturn -1;\n\t*val = tmp;\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static int jpc_pi_nextrlcp(register jpc_pi_t *pi)\n{\n\tjpc_pchg_t *pchg;\n\tint *prclyrno;\n\n\tpchg = pi->pchg;\n\tif (!pi->prgvolfirst) {\n\t\tassert(pi->prcno < pi->pirlvl->numprcs);\n\t\tprclyrno = &pi->pirlvl->prclyrnos[pi->prcno];\n\t\tgoto skip;\n\t} else {\n\t\tpi->prgvolfirst = 0;\n\t}\n\n\tfor (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&\n\t pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {\n\t\tfor (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <\n\t\t JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {\n\t\t\tfor (pi->compno = pchg->compnostart, pi->picomp =\n\t\t\t &pi->picomps[pi->compno]; pi->compno < pi->numcomps &&\n\t\t\t pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) {\n\t\t\t\tif (pi->rlvlno >= pi->picomp->numrlvls) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];\n\t\t\t\tfor (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;\n\t\t\t\t pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {\n\t\t\t\t\tif (pi->lyrno >= *prclyrno) {\n\t\t\t\t\t\t*prclyrno = pi->lyrno;\n\t\t\t\t\t\t++(*prclyrno);\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\nskip:\n\t\t\t\t\t;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,\n int stride, int parity)\n{\n\n\tint bufsize = JPC_CEILDIVPOW2(numrows, 1);\n\tjpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];\n\tjpc_fix_t *buf = splitbuf;\n\tjpc_fix_t *srcptr;\n\tjpc_fix_t *dstptr;\n\tregister jpc_fix_t *srcptr2;\n\tregister jpc_fix_t *dstptr2;\n\tregister int n;\n\tregister int i;\n\tint m;\n\tint hstartcol;\n\n\t/* Get a buffer. */\n\tif (bufsize > QMFB_SPLITBUFSIZE) {\n\t\tif (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {\n\t\t\t/* We have no choice but to commit suicide in this case. */\n\t\t\tabort();\n\t\t}\n\t}\n\n\tif (numrows >= 2) {\n\t\thstartcol = (numrows + 1 - parity) >> 1;\n\t\t// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol);\n\t\tm = numrows - hstartcol;\n\n\t\t/* Save the samples destined for the highpass channel. */\n\t\tn = m;\n\t\tdstptr = buf;\n\t\tsrcptr = &a[(1 - parity) * stride];\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < numcols; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += numcols;\n\t\t\tsrcptr += stride << 1;\n\t\t}\n\t\t/* Copy the appropriate samples into the lowpass channel. */\n\t\tdstptr = &a[(1 - parity) * stride];\n\t\tsrcptr = &a[(2 - parity) * stride];\n\t\tn = numrows - m - (!parity);\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < numcols; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += stride;\n\t\t\tsrcptr += stride << 1;\n\t\t}\n\t\t/* Copy the saved samples into the highpass channel. */\n\t\tdstptr = &a[hstartcol * stride];\n\t\tsrcptr = buf;\n\t\tn = m;\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < numcols; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += stride;\n\t\t\tsrcptr += numcols;\n\t\t}\n\t}\n\n\t/* If the split buffer was allocated on the heap, free this memory. */\n\tif (buf != splitbuf) {\n\t\tjas_free(buf);\n\t}\n\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static int timer_start(Unit *u) {\n Timer *t = TIMER(u);\n TimerValue *v;\n\n assert(t);\n assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED);\n\n if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)\n return -ENOENT;\n\n t->last_trigger = DUAL_TIMESTAMP_NULL;\n\n /* Reenable all timers that depend on unit activation time */\n LIST_FOREACH(value, v, t->values)\n if (v->base == TIMER_ACTIVE)\n v->disabled = false;\n\n if (t->stamp_path) {\n struct stat st;\n\n if (stat(t->stamp_path, &st) >= 0)\n t->last_trigger.realtime = timespec_load(&st.st_atim);\n else if (errno == ENOENT)\n /* The timer has never run before,\n * make sure a stamp file exists.\n */\n touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);\n }\n\n t->result = TIMER_SUCCESS;\n timer_enter_waiting(t, true);\n return 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "_public_ int sd_bus_enqeue_for_read(sd_bus *bus, sd_bus_message *m) {\n int r;\n\n assert_return(bus, -EINVAL);\n assert_return(bus = bus_resolve(bus), -ENOPKG);\n assert_return(m, -EINVAL);\n assert_return(m->sealed, -EINVAL);\n assert_return(!bus_pid_changed(bus), -ECHILD);\n\n if (!BUS_IS_OPEN(bus->state))\n return -ENOTCONN;\n\n /* Re-enqeue a message for reading. This is primarily useful for PolicyKit-style authentication,\n * where we want accept a message, then determine we need to interactively authenticate the user, and\n * when we have that process the message again. */\n\n r = bus_rqueue_make_room(bus);\n if (r < 0)\n return r;\n\n bus->rqueue[bus->rqueue_size++] = bus_message_ref_queued(m, bus);\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "CAMLprim value caml_alloc_dummy(value size)\n{\n mlsize_t wosize = Int_val(size);\n\n if (wosize == 0) return Atom(0);\n return caml_alloc (wosize, 0);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *\n p_code_block)\n{\n OPJ_UINT32 l_data_size;\n\n /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */\n l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *\n (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));\n\n if (l_data_size > p_code_block->data_size) {\n if (p_code_block->data) {\n /* We refer to data - 1 since below we incremented it */\n opj_free(p_code_block->data - 1);\n }\n p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);\n if (! p_code_block->data) {\n p_code_block->data_size = 0U;\n return OPJ_FALSE;\n }\n p_code_block->data_size = l_data_size;\n\n /* We reserve the initial byte as a fake byte to a non-FF value */\n /* and increment the data pointer, so that opj_mqc_init_enc() */\n /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */\n /* it. */\n p_code_block->data[0] = 0;\n p_code_block->data += 1; /*why +1 ?*/\n }\n return OPJ_TRUE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "hb_set_intersect (hb_set_t *set,\n\t\t const hb_set_t *other)\n{\n if (unlikely (hb_object_is_immutable (set)))\n return;\n\n set->intersect (*other);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,\n void *(*allocfunc)(void *, u_int, u_int),\n void (*freefunc)(void *, void *))\n{\n\tssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;\n\tssh->state->compression_out_stream.zfree = (free_func)freefunc;\n\tssh->state->compression_out_stream.opaque = ctx;\n\tssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;\n\tssh->state->compression_in_stream.zfree = (free_func)freefunc;\n\tssh->state->compression_in_stream.opaque = ctx;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "smtp_mailaddr(struct mailaddr *maddr, char *line, int mailfrom, char **args,\n const char *domain)\n{\n\tchar *p, *e;\n\n\tif (line == NULL)\n\t\treturn (0);\n\n\tif (*line != '<')\n\t\treturn (0);\n\n\te = strchr(line, '>');\n\tif (e == NULL)\n\t\treturn (0);\n\t*e++ = '\\0';\n\twhile (*e == ' ')\n\t\te++;\n\t*args = e;\n\n\tif (!text_to_mailaddr(maddr, line + 1))\n\t\treturn (0);\n\n\tp = strchr(maddr->user, ':');\n\tif (p != NULL) {\n\t\tp++;\n\t\tmemmove(maddr->user, p, strlen(p) + 1);\n\t}\n\n\tif (!valid_localpart(maddr->user) ||\n\t !valid_domainpart(maddr->domain)) {\n\t\t/* accept empty return-path in MAIL FROM, required for bounces */\n\t\tif (mailfrom && maddr->user[0] == '\\0' && maddr->domain[0] == '\\0')\n\t\t\treturn (1);\n\n\t\t/* no user-part, reject */\n\t\tif (maddr->user[0] == '\\0')\n\t\t\treturn (0);\n\n\t\t/* no domain, local user */\n\t\tif (maddr->domain[0] == '\\0') {\n\t\t\t(void)strlcpy(maddr->domain, domain,\n\t\t\t sizeof(maddr->domain));\n\t\t\treturn (1);\n\t\t}\n\t\treturn (0);\n\t}\n\n\treturn (1);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "vulnerable"} {"code": "table_regex_match(const char *string, const char *pattern)\n{\n\tregex_t preg;\n\tint\tcflags = REG_EXTENDED|REG_NOSUB;\n\n\tif (strncmp(pattern, \"(?i)\", 4) == 0) {\n\t\tcflags |= REG_ICASE;\n\t\tpattern += 4;\n\t}\n\n\tif (regcomp(&preg, pattern, cflags) != 0)\n\t\treturn (0);\n\n\tif (regexec(&preg, string, 0, NULL, 0) != 0)\n\t\treturn (0);\n\n\treturn (1);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-401", "cwe_name": "Missing Release of Memory after Effective Lifetime", "description": "The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.", "url": "https://cwe.mitre.org/data/definitions/401.html", "label_name": "vulnerable"} {"code": "static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)\n{\n int bytecnt = wpmd->byte_length;\n unsigned char *byteptr = wpmd->data;\n\n wpc->version_five = 1; // just having this block signals version 5.0\n\n wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0;\n\n if (wpc->channel_reordering) {\n free (wpc->channel_reordering);\n wpc->channel_reordering = NULL;\n }\n\n // if there's any data, the first two bytes are file_format and qmode flags\n\n if (bytecnt) {\n wpc->file_format = *byteptr++;\n wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;\n bytecnt -= 2;\n\n // another byte indicates a channel layout\n\n if (bytecnt) {\n int nchans, i;\n\n wpc->channel_layout = (int32_t) *byteptr++ << 16;\n bytecnt--;\n\n // another byte means we have a channel count for the layout and maybe a reordering\n\n if (bytecnt) {\n wpc->channel_layout += nchans = *byteptr++;\n bytecnt--;\n\n // any more means there's a reordering string\n\n if (bytecnt) {\n if (bytecnt > nchans)\n return FALSE;\n\n wpc->channel_reordering = malloc (nchans);\n\n // note that redundant reordering info is not stored, so we fill in the rest\n\n if (wpc->channel_reordering) {\n for (i = 0; i < nchans; ++i)\n if (bytecnt) {\n wpc->channel_reordering [i] = *byteptr++;\n bytecnt--;\n }\n else\n wpc->channel_reordering [i] = i;\n }\n }\n }\n else\n wpc->channel_layout += wpc->config.num_channels;\n }\n }\n\n return TRUE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)\n{\n cJSON *current_element = NULL;\n\n if ((object == NULL) || (name == NULL))\n {\n return NULL;\n }\n\n current_element = object->child;\n if (case_sensitive)\n {\n while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))\n {\n current_element = current_element->next;\n }\n }\n else\n {\n while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))\n {\n current_element = current_element->next;\n }\n }\n\n return current_element;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-754", "cwe_name": "Improper Check for Unusual or Exceptional Conditions", "description": "The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.", "url": "https://cwe.mitre.org/data/definitions/754.html", "label_name": "vulnerable"} {"code": "find_match_text(colnr_T startcol, int regstart, char_u *match_text)\n{\n colnr_T col = startcol;\n int\t c1, c2;\n int\t len1, len2;\n int\t match;\n\n for (;;)\n {\n\tmatch = TRUE;\n\tlen2 = MB_CHAR2LEN(regstart); // skip regstart\n\tfor (len1 = 0; match_text[len1] != NUL; len1 += MB_CHAR2LEN(c1))\n\t{\n\t c1 = PTR2CHAR(match_text + len1);\n\t c2 = PTR2CHAR(rex.line + col + len2);\n\t if (c1 != c2 && (!rex.reg_ic || MB_CASEFOLD(c1) != MB_CASEFOLD(c2)))\n\t {\n\t\tmatch = FALSE;\n\t\tbreak;\n\t }\n\t len2 += MB_CHAR2LEN(c2);\n\t}\n\tif (match\n\t\t// check that no composing char follows\n\t\t&& !(enc_utf8\n\t\t\t && utf_iscomposing(PTR2CHAR(rex.line + col + len2))))\n\t{\n\t cleanup_subexpr();\n\t if (REG_MULTI)\n\t {\n\t\trex.reg_startpos[0].lnum = rex.lnum;\n\t\trex.reg_startpos[0].col = col;\n\t\trex.reg_endpos[0].lnum = rex.lnum;\n\t\trex.reg_endpos[0].col = col + len2;\n\t }\n\t else\n\t {\n\t\trex.reg_startp[0] = rex.line + col;\n\t\trex.reg_endp[0] = rex.line + col + len2;\n\t }\n\t return 1L;\n\t}\n\n\t// Try finding regstart after the current match.\n\tcol += MB_CHAR2LEN(regstart); // skip regstart\n\tif (skip_to_start(regstart, &col) == FAIL)\n\t break;\n }\n return 0L;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-122", "cwe_name": "Heap-based Buffer Overflow", "description": "A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc().", "url": "https://cwe.mitre.org/data/definitions/122.html", "label_name": "vulnerable"} {"code": "get_user_commands(expand_T *xp UNUSED, int idx)\n{\n // In cmdwin, the alternative buffer should be used.\n buf_T *buf =\n#ifdef FEAT_CMDWIN\n\tis_in_cmdwin() ? prevwin->w_buffer :\n#endif\n\tcurbuf;\n\n if (idx < buf->b_ucmds.ga_len)\n\treturn USER_CMD_GA(&buf->b_ucmds, idx)->uc_name;\n idx -= buf->b_ucmds.ga_len;\n if (idx < ucmds.ga_len)\n\treturn USER_CMD(idx)->uc_name;\n return NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "cstrchr(char_u *s, int c)\n{\n char_u\t*p;\n int\t\tcc;\n\n if (!rex.reg_ic || (!enc_utf8 && mb_char2len(c) > 1))\n\treturn vim_strchr(s, c);\n\n // tolower() and toupper() can be slow, comparing twice should be a lot\n // faster (esp. when using MS Visual C++!).\n // For UTF-8 need to use folded case.\n if (enc_utf8 && c > 0x80)\n\tcc = utf_fold(c);\n else\n\t if (MB_ISUPPER(c))\n\tcc = MB_TOLOWER(c);\n else if (MB_ISLOWER(c))\n\tcc = MB_TOUPPER(c);\n else\n\treturn vim_strchr(s, c);\n\n if (has_mbyte)\n {\n\tfor (p = s; *p != NUL; p += (*mb_ptr2len)(p))\n\t{\n\t if (enc_utf8 && c > 0x80)\n\t {\n\t\tif (utf_fold(utf_ptr2char(p)) == cc)\n\t\t return p;\n\t }\n\t else if (*p == c || *p == cc)\n\t\treturn p;\n\t}\n }\n else\n\t// Faster version for when there are no multi-byte characters.\n\tfor (p = s; *p != NUL; ++p)\n\t if (*p == c || *p == cc)\n\t\treturn p;\n\n return NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "compile_lock_unlock(\n lval_T *lvp,\n char_u *name_end,\n exarg_T *eap,\n int\t deep,\n void *coookie)\n{\n cctx_T\t*cctx = coookie;\n int\t\tcc = *name_end;\n char_u\t*p = lvp->ll_name;\n int\t\tret = OK;\n size_t\tlen;\n char_u\t*buf;\n isntype_T\tisn = ISN_EXEC;\n\n if (cctx->ctx_skip == SKIP_YES)\n\treturn OK;\n\n // Cannot use :lockvar and :unlockvar on local variables.\n if (p[1] != ':')\n {\n\tchar_u *end = find_name_end(p, NULL, NULL, FNE_CHECK_START);\n\n\tif (lookup_local(p, end - p, NULL, cctx) == OK)\n\t{\n\t char_u *s = p;\n\n\t if (*end != '.' && *end != '[')\n\t {\n\t\temsg(_(e_cannot_lock_unlock_local_variable));\n\t\treturn FAIL;\n\t }\n\n\t // For \"d.member\" put the local variable on the stack, it will be\n\t // passed to ex_lockvar() indirectly.\n\t if (compile_load(&s, end, cctx, FALSE, FALSE) == FAIL)\n\t\treturn FAIL;\n\t isn = ISN_LOCKUNLOCK;\n\t}\n }\n\n // Checking is done at runtime.\n *name_end = NUL;\n len = name_end - p + 20;\n buf = alloc(len);\n if (buf == NULL)\n\tret = FAIL;\n else\n {\n\tchar *cmd = eap->cmdidx == CMD_lockvar ? \"lockvar\" : \"unlockvar\";\n\n\tif (deep < 0)\n\t vim_snprintf((char *)buf, len, \"%s! %s\", cmd, p);\n\telse\n\t vim_snprintf((char *)buf, len, \"%s %d %s\", cmd, deep, p);\n\tret = generate_EXEC_copy(cctx, isn, buf);\n\n\tvim_free(buf);\n\t*name_end = cc;\n }\n return ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-122", "cwe_name": "Heap-based Buffer Overflow", "description": "A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc().", "url": "https://cwe.mitre.org/data/definitions/122.html", "label_name": "vulnerable"} {"code": "eval_next_line(char_u *arg, evalarg_T *evalarg)\n{\n garray_T\t*gap = &evalarg->eval_ga;\n char_u\t*line;\n\n if (arg != NULL)\n {\n\tif (*arg == NL)\n\t return newline_skip_comments(arg);\n\t// Truncate before a trailing comment, so that concatenating the lines\n\t// won't turn the rest into a comment.\n\tif (*skipwhite(arg) == '#')\n\t *arg = NUL;\n }\n\n if (evalarg->eval_cookie != NULL)\n\tline = evalarg->eval_getline(0, evalarg->eval_cookie, 0,\n\t\t\t\t\t\t\t GETLINE_CONCAT_ALL);\n else\n\tline = next_line_from_context(evalarg->eval_cctx, TRUE);\n if (line == NULL)\n\treturn NULL;\n\n ++evalarg->eval_break_count;\n if (gap->ga_itemsize > 0 && ga_grow(gap, 1) == OK)\n {\n\tchar_u *p = skipwhite(line);\n\n\t// Going to concatenate the lines after parsing. For an empty or\n\t// comment line use an empty string.\n\tif (*p == NUL || vim9_comment_start(p))\n\t{\n\t vim_free(line);\n\t line = vim_strsave((char_u *)\"\");\n\t}\n\n\t((char_u **)gap->ga_data)[gap->ga_len] = line;\n\t++gap->ga_len;\n }\n else if (evalarg->eval_cookie != NULL)\n {\n\tvim_free(evalarg->eval_tofree);\n\tevalarg->eval_tofree = line;\n }\n\n // Advanced to the next line, \"arg\" no longer points into the previous\n // line.\n evalarg->eval_using_cmdline = FALSE;\n return skipwhite(line);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "f_settabvar(typval_T *argvars, typval_T *rettv)\n{\n tabpage_T\t*save_curtab;\n tabpage_T\t*tp;\n char_u\t*varname, *tabvarname;\n typval_T\t*varp;\n\n rettv->vval.v_number = 0;\n\n if (check_restricted() || check_secure())\n\treturn;\n\n tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));\n varname = tv_get_string_chk(&argvars[1]);\n varp = &argvars[2];\n\n if (varname != NULL && varp != NULL && tp != NULL)\n {\n\tsave_curtab = curtab;\n\tgoto_tabpage_tp(tp, FALSE, FALSE);\n\n\ttabvarname = alloc((unsigned)STRLEN(varname) + 3);\n\tif (tabvarname != NULL)\n\t{\n\t STRCPY(tabvarname, \"t:\");\n\t STRCPY(tabvarname + 2, varname);\n\t set_var(tabvarname, varp, TRUE);\n\t vim_free(tabvarname);\n\t}\n\n\t/* Restore current tabpage */\n\tif (valid_tabpage(save_curtab))\n\t goto_tabpage_tp(save_curtab, FALSE, FALSE);\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "vulnerable"} {"code": "static double ipow( double n, int exp )\n{\n\tdouble r;\n\n\tif ( exp < 0 )\n\t\treturn 1.0 / ipow( n, -exp );\n\tr = 1;\n\twhile ( exp > 0 ) {\n\t\tif ( exp & 1 )\n\t\t\tr *= n;\n\t\texp >>= 1;\n\t\tn *= n;\n\t}\n\treturn r;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )\n{\n\tcJSON_AddItemToArray( array, create_reference( item ) );\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "cJSON *cJSON_CreateFloat( double num )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item ) {\n\t\titem->type = cJSON_Number;\n\t\titem->valuefloat = num;\n\t\titem->valueint = num;\n\t}\n\treturn item;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "static char* cJSON_strdup( const char* str )\n{\n\tsize_t len;\n\tchar* copy;\n\n\tlen = strlen( str ) + 1;\n\tif ( ! ( copy = (char*) cJSON_malloc( len ) ) )\n\t\treturn 0;\n\tmemcpy( copy, str, len );\n\treturn copy;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "cJSON *cJSON_CreateString( const char *string )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item ) {\n\t\titem->type = cJSON_String;\n\t\titem->valuestring = cJSON_strdup( string );\n\t}\n\treturn item;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "cJSON *cJSON_Parse( const char *value )\n{\n\tcJSON *c;\n\tep = 0;\n\tif ( ! ( c = cJSON_New_Item() ) )\n\t\treturn 0;\t/* memory fail */\n\n\tif ( ! parse_value( c, skip( value ) ) ) {\n\t\tcJSON_Delete( c );\n\t\treturn 0;\n\t}\n\treturn c;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "cJSON *cJSON_CreateStringArray( const char **strings, int count )\n{\n\tint i;\n\tcJSON *n = 0, *p = 0, *a = cJSON_CreateArray();\n\tfor ( i = 0; a && i < count; ++i ) {\n\t\tn = cJSON_CreateString( strings[i] );\n\t\tif ( ! i )\n\t\t\ta->child = n;\n\t\telse\n\t\t\tsuffix_object( p, n );\n\t\tp = n;\n\t}\n\treturn a;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "cJSON *cJSON_CreateBool( int b )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item )\n\t\titem->type = b ? cJSON_True : cJSON_False;\n\treturn item;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "static void handle_run(HttpRequest req, HttpResponse res) {\n const char *action = get_parameter(req, \"action\");\n if (action) {\n if (is_readonly(req)) {\n send_error(req, res, SC_FORBIDDEN, \"You do not have sufficient privileges to access this page\");\n return;\n }\n if (IS(action, \"validate\")) {\n LogInfo(\"The Monit http server woke up on user request\\n\");\n do_wakeupcall();\n } else if (IS(action, \"stop\")) {\n LogInfo(\"The Monit http server stopped on user request\\n\");\n send_error(req, res, SC_SERVICE_UNAVAILABLE, \"The Monit http server is stopped\");\n Engine_stop();\n return;\n }\n }\n LOCK(Run.mutex)\n do_runtime(req, res);\n END_LOCK;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": "CURLcode Curl_auth_create_plain_message(struct Curl_easy *data,\n const char *userp,\n const char *passwdp,\n char **outptr, size_t *outlen)\n{\n CURLcode result;\n char *plainauth;\n size_t ulen;\n size_t plen;\n size_t plainlen;\n\n *outlen = 0;\n *outptr = NULL;\n ulen = strlen(userp);\n plen = strlen(passwdp);\n\n /* Compute binary message length. Check for overflows. */\n if((ulen > SIZE_T_MAX/2) || (plen > (SIZE_T_MAX/2 - 2)))\n return CURLE_OUT_OF_MEMORY;\n plainlen = 2 * ulen + plen + 2;\n\n plainauth = malloc(plainlen);\n if(!plainauth)\n return CURLE_OUT_OF_MEMORY;\n\n /* Calculate the reply */\n memcpy(plainauth, userp, ulen);\n plainauth[ulen] = '\\0';\n memcpy(plainauth + ulen + 1, userp, ulen);\n plainauth[2 * ulen + 1] = '\\0';\n memcpy(plainauth + 2 * ulen + 2, passwdp, plen);\n\n /* Base64 encode the reply */\n result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen);\n free(plainauth);\n\n return result;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "local unsigned long crc32_big(crc, buf, len)\n unsigned long crc;\n const unsigned char FAR *buf;\n unsigned len;\n{\n register z_crc_t c;\n register const z_crc_t FAR *buf4;\n\n c = ZSWAP32((z_crc_t)crc);\n c = ~c;\n while (len && ((ptrdiff_t)buf & 3)) {\n c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);\n len--;\n }\n\n buf4 = (const z_crc_t FAR *)(const void FAR *)buf;\n buf4--;\n while (len >= 32) {\n DOBIG32;\n len -= 32;\n }\n while (len >= 4) {\n DOBIG4;\n len -= 4;\n }\n buf4++;\n buf = (const unsigned char FAR *)buf4;\n\n if (len) do {\n c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);\n } while (--len);\n c = ~c;\n return (unsigned long)(ZSWAP32(c));\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)\n{\n\tconst char *s = name;\n\n\twhile (1) {\n\t\tconst char *s0 = s;\n\t\tchar *dirname;\n\n\t\t/* Find a directory component, if any. */\n\t\twhile (1) {\n\t\t\tif (*s == 0) {\n\t\t\t\tif (last && s != s0)\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\treturn dir;\n\t\t\t}\n\t\t\t/* This is deliberately slash-only. */\n\t\t\tif (*s == '/')\n\t\t\t\tbreak;\n\t\t\ts++;\n\t\t}\n\n\t\tdirname = g_strndup (s0, s - s0);\n\t\twhile (*s == '/')\n\t\t\ts++;\n\n\t\tif (strcmp (dirname, \".\") != 0) {\n\t\t\tGsfInput *subdir =\n\t\t\t\tgsf_infile_child_by_name (GSF_INFILE (dir),\n\t\t\t\t\t\t\t dirname);\n\t\t\tif (subdir) {\n\t\t\t\t/* Undo the ref. */\n\t\t\t\tg_object_unref (subdir);\n\t\t\t\tdir = GSF_INFILE_TAR (subdir);\n\t\t\t} else\n\t\t\t\tdir = tar_create_dir (dir, dirname);\n\t\t}\n\n\t\tg_free (dirname);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) {\n\tstruct addr_t *entry;\n\tint i;\n\n\tif (!bin->entry && !bin->sects) {\n\t\treturn NULL;\n\t}\n\tif (!(entry = calloc (1, sizeof (struct addr_t)))) {\n\t\treturn NULL;\n\t}\n\n\tif (bin->entry) {\n\t\tentry->addr = entry_to_vaddr (bin);\n\t\tentry->offset = addr_to_offset (bin, entry->addr);\n\t\tentry->haddr = sdb_num_get (bin->kv, \"mach0.entry.offset\", 0);\n\t}\n\n\tif (!bin->entry || entry->offset == 0) {\n\t\t// XXX: section name doesnt matters at all.. just check for exec flags\n\t\tfor (i = 0; i < bin->nsects; i++) {\n\t\t\tif (!strncmp (bin->sects[i].sectname, \"__text\", 6)) {\n\t\t\t\tentry->offset = (ut64)bin->sects[i].offset;\n\t\t\t\tsdb_num_set (bin->kv, \"mach0.entry\", entry->offset, 0);\n\t\t\t\tentry->addr = (ut64)bin->sects[i].addr;\n\t\t\t\tif (!entry->addr) { // workaround for object files\n\t\t\t\t\tentry->addr = entry->offset;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbin->entry = entry->addr;\n\t}\n\n\treturn entry;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {\n\tconst int nb10sz = 16;\n\tmemcpy (res, dbg_data, nb10sz);\n\tres->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {\n\tint i, j, sym, wordsize;\n\tut32 stype;\n\twordsize = MACH0_(get_bits)(bin) / 8;\n\tif (idx < 0 || idx >= bin->nsymtab) {\n\t\treturn 0;\n\t}\n\tif ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {\n\t\tstype = S_LAZY_SYMBOL_POINTERS;\n\t} else {\n\t\tstype = S_NON_LAZY_SYMBOL_POINTERS;\n\t}\n\n\treloc->offset = 0;\n\treloc->addr = 0;\n\treloc->addend = 0;\n#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break\n\tswitch (wordsize) {\n\t\tCASE(8);\n\t\tCASE(16);\n\t\tCASE(32);\n\t\tCASE(64);\n\t\tdefault: return false;\n\t}\n#undef CASE\n\n\tfor (i = 0; i < bin->nsects; i++) {\n\t\tif ((bin->sects[i].flags & SECTION_TYPE) == stype) {\n\t\t\tfor (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++)\n\t\t\t\tif (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) {\n\t\t\t\t\tsym = j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\treloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;\n\t\t\treloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "usage (int status)\n{\n if (status != EXIT_SUCCESS)\n fprintf (stderr, _(\"Try `%s --help' for more information.\\n\"),\n\t program_name);\n else\n {\n printf (_(\"\\\nUsage: %s [OPTION]... [STRINGS]...\\n\\\n\"), program_name);\n fputs (_(\"\\\nInternationalized Domain Name (IDNA2008) convert STRINGS, or standard input.\\n\\\n\\n\\\n\"), stdout);\n fputs (_(\"\\\nCommand line interface to the Libidn2 implementation of IDNA2008.\\n\\\n\\n\\\nAll strings are expected to be encoded in the locale charset.\\n\\\n\\n\\\nTo process a string that starts with `-', for example `-foo', use `--'\\n\\\nto signal the end of parameters, as in `idn2 --quiet -- -foo'.\\n\\\n\\n\\\nMandatory arguments to long options are mandatory for short options too.\\n\\\n\"), stdout);\n fputs (_(\"\\\n -h, --help Print help and exit\\n\\\n -V, --version Print version and exit\\n\\\n\"), stdout);\n fputs (_(\"\\\n -d, --decode Decode (punycode) domain name\\n\\\n -l, --lookup Lookup domain name (default)\\n\\\n -r, --register Register label\\n\\\n\"), stdout);\n fputs (_(\"\\\n -T, --tr46t Enable TR46 transitional processing\\n\\\n -N, --tr46nt Enable TR46 non-transitional processing\\n\\\n --no-tr46 Disable TR46 processing\\n\\\n\"), stdout);\n fputs (_(\"\\\n --usestd3asciirules Enable STD3 ASCII rules\\n\\\n --debug Print debugging information\\n\\\n --quiet Silent operation\\n\\\n\"), stdout);\n emit_bug_reporting_address ();\n }\n exit (status);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "main (int argc, char *argv[])\n{\n unsigned cmdn;\n int flags = IDN2_NONTRANSITIONAL;\n\n setlocale (LC_ALL, \"\");\n set_program_name (argv[0]);\n bindtextdomain (PACKAGE, LOCALEDIR);\n textdomain (PACKAGE);\n\n if (cmdline_parser (argc, argv, &args_info) != 0)\n return EXIT_FAILURE;\n\n if (args_info.version_given)\n {\n version_etc (stdout, \"idn2\", PACKAGE_NAME, VERSION,\n\t\t \"Simon Josefsson\", (char *) NULL);\n return EXIT_SUCCESS;\n }\n\n if (args_info.help_given)\n usage (EXIT_SUCCESS);\n\n if (!args_info.quiet_given\n && args_info.inputs_num == 0 && isatty (fileno (stdin)))\n fprintf (stderr, \"%s %s\\n\" GREETING, PACKAGE, VERSION);\n\n if (args_info.debug_given)\n fprintf (stderr, _(\"Charset: %s\\n\"), locale_charset ());\n\n if (!args_info.quiet_given\n && args_info.inputs_num == 0 && isatty (fileno (stdin)))\n fprintf (stderr, \"%s\", _(\"Type each input string on a line by itself, \"\n\t\t\t \"terminated by a newline character.\\n\"));\n\n if (args_info.tr46t_given)\n flags = IDN2_TRANSITIONAL;\n else if (args_info.tr46nt_given)\n flags = IDN2_NONTRANSITIONAL;\n else if (args_info.no_tr46_given)\n flags = IDN2_NO_TR46;\n\n if (flags && args_info.usestd3asciirules_given)\n flags |= IDN2_USE_STD3_ASCII_RULES;\n\n for (cmdn = 0; cmdn < args_info.inputs_num; cmdn++)\n process_input (args_info.inputs[cmdn], flags | IDN2_NFC_INPUT);\n\n if (!cmdn)\n {\n char *buf = NULL;\n size_t bufsize = 0;\n\n while (getline (&buf, &bufsize, stdin) > 0)\n\tprocess_input (buf, flags);\n\n free (buf);\n }\n\n if (ferror (stdin))\n error (EXIT_FAILURE, errno, \"%s\", _(\"input error\"));\n\n cmdline_parser_free (&args_info);\n\n return EXIT_SUCCESS;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "irc_ctcp_dcc_filename_without_quotes (const char *filename)\n{\n int length;\n\n length = strlen (filename);\n if (length > 0)\n {\n if ((filename[0] == '\\\"') && (filename[length - 1] == '\\\"'))\n return weechat_strndup (filename + 1, length - 2);\n }\n return strdup (filename);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "checked_xcalloc (size_t num, size_t size)\n{\n alloc_limit_assert (\"checked_xcalloc\", (num *size));\n return xcalloc (num, size);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static Var* Pe_r_bin_pe_parse_var(RBinPEObj* pe, PE_DWord* curAddr) {\n\tVar* var = calloc (1, sizeof (*var));\n\tif (!var) {\n\t\tpe_printf (\"Warning: calloc (Var)\\n\");\n\t\treturn NULL;\n\t}\n\tif ((var->wLength = r_buf_read_le16_at (pe->b, *curAddr)) == UT16_MAX) {\n\t\tpe_printf (\"Warning: read (Var wLength)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += sizeof (var->wLength);\n\tif ((var->wValueLength = r_buf_read_le16_at (pe->b, *curAddr)) == UT16_MAX) {\n\t\tpe_printf (\"Warning: read (Var wValueLength)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += sizeof (var->wValueLength);\n\tif ((var->wType = r_buf_read_le16_at (pe->b, *curAddr)) == UT16_MAX) {\n\t\tpe_printf (\"Warning: read (Var wType)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += sizeof (var->wType);\n\tif (var->wType != 0 && var->wType != 1) {\n\t\tpe_printf (\"Warning: check (Var wType)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\n\tvar->szKey = (ut16*) malloc (UT16_ALIGN (TRANSLATION_UTF_16_LEN)); //L\"Translation\"\n\tif (!var->szKey) {\n\t\tpe_printf (\"Warning: malloc (Var szKey)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\tif (r_buf_read_at (pe->b, *curAddr, (ut8*) var->szKey, TRANSLATION_UTF_16_LEN) < 1) {\n\t\tpe_printf (\"Warning: read (Var szKey)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += TRANSLATION_UTF_16_LEN;\n\tif (memcmp (var->szKey, TRANSLATION_UTF_16, TRANSLATION_UTF_16_LEN)) {\n\t\tpe_printf (\"Warning: check (Var szKey)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\talign32 (*curAddr);\n\tvar->numOfValues = var->wValueLength / 4;\n\tif (!var->numOfValues) {\n\t\tpe_printf (\"Warning: check (Var numOfValues)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\tvar->Value = (ut32*) malloc (var->wValueLength);\n\tif (!var->Value) {\n\t\tpe_printf (\"Warning: malloc (Var Value)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\tif (r_buf_read_at (pe->b, *curAddr, (ut8*) var->Value, var->wValueLength) != var->wValueLength) {\n\t\tpe_printf (\"Warning: read (Var Value)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += var->wValueLength;\n\treturn var;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "struct r_bin_pe_addr_t *PE_(check_unknow)(RBinPEObj *pe) {\n\tstruct r_bin_pe_addr_t *entry;\n\tif (!pe || !pe->b) {\n\t\treturn 0LL;\n\t}\n\tut8 b[512];\n\tZERO_FILL (b);\n\tentry = PE_ (r_bin_pe_get_entrypoint) (pe);\n\t// option2: /x 8bff558bec83ec20\n\tif (r_buf_read_at (pe->b, entry->paddr, b, 512) < 1) {\n\t\tpe_printf (\"Warning: Cannot read entry at 0x%08\"PFMT64x\"\\n\", entry->paddr);\n\t\tfree (entry);\n\t\treturn NULL;\n\t}\n\t/* Decode the jmp instruction, this gets the address of the 'main'\n\t function for PE produced by a compiler whose name someone forgot to\n\t write down. */\n\t// this is dirty only a single byte check, can return false positives\n\tif (b[367] == 0xe8) {\n\t\tfollow_offset (entry, pe->b, b, sizeof (b), pe->big_endian, 367);\n\t\treturn entry;\n\t}\n\tsize_t i;\n\tfor (i = 0; i < 512 - 16 ; i++) {\n\t\t// 5. ff 15 .. .. .. .. 50 e8 [main]\n\t\tif (!memcmp (b + i, \"\\xff\\x15\", 2)) {\n\t\t\tif (b[i + 6] == 0x50) {\n\t\t\t\tif (b[i + 7] == 0xe8) {\n\t\t\t\t\tfollow_offset (entry, pe->b, b, sizeof (b), pe->big_endian, i + 7);\n\t\t\t\t\treturn entry;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfree (entry);\n\treturn NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "ut32 armass_assemble(const char *str, ut64 off, int thumb) {\n\tint i, j;\n\tchar buf[128];\n\tArmOpcode aop = {.off = off};\n\tfor (i = j = 0; i < sizeof (buf) - 1 && str[i]; i++, j++) {\n\t\tif (str[j] == '#') {\n\t\t\ti--; continue;\n\t\t}\n\t\tbuf[i] = tolower ((const ut8)str[j]);\n\t}\n\tbuf[i] = 0;\n\tarm_opcode_parse (&aop, buf);\n\taop.off = off;\n\tif (thumb < 0 || thumb > 1) {\n\t\treturn -1;\n\t}\n\tif (!assemble[thumb] (&aop, off, buf)) {\n\t\t//eprintf (\"armass: Unknown opcode (%s)\\n\", buf);\n\t\treturn -1;\n\t}\n\treturn aop.o;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "IPV6DefragReverseSimpleTest(void)\n{\n DefragContext *dc = NULL;\n Packet *p1 = NULL, *p2 = NULL, *p3 = NULL;\n Packet *reassembled = NULL;\n int id = 12;\n int i;\n int ret = 0;\n\n DefragInit();\n\n dc = DefragContextNew();\n if (dc == NULL)\n goto end;\n\n p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8);\n if (p1 == NULL)\n goto end;\n p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8);\n if (p2 == NULL)\n goto end;\n p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3);\n if (p3 == NULL)\n goto end;\n\n if (Defrag(NULL, NULL, p3, NULL) != NULL)\n goto end;\n if (Defrag(NULL, NULL, p2, NULL) != NULL)\n goto end;\n reassembled = Defrag(NULL, NULL, p1, NULL);\n if (reassembled == NULL)\n goto end;\n\n /* 40 bytes in we should find 8 bytes of A. */\n for (i = 40; i < 40 + 8; i++) {\n if (GET_PKT_DATA(reassembled)[i] != 'A')\n goto end;\n }\n\n /* 28 bytes in we should find 8 bytes of B. */\n for (i = 48; i < 48 + 8; i++) {\n if (GET_PKT_DATA(reassembled)[i] != 'B')\n goto end;\n }\n\n /* And 36 bytes in we should find 3 bytes of C. */\n for (i = 56; i < 56 + 3; i++) {\n if (GET_PKT_DATA(reassembled)[i] != 'C')\n goto end;\n }\n\n ret = 1;\nend:\n if (dc != NULL)\n DefragContextDestroy(dc);\n if (p1 != NULL)\n SCFree(p1);\n if (p2 != NULL)\n SCFree(p2);\n if (p3 != NULL)\n SCFree(p3);\n if (reassembled != NULL)\n SCFree(reassembled);\n\n DefragDestroy();\n return ret;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-358", "cwe_name": "Improperly Implemented Security Check for Standard", "description": "The software does not implement or incorrectly implements one or more security-relevant checks as specified by the design of a standardized algorithm, protocol, or technique.", "url": "https://cwe.mitre.org/data/definitions/358.html", "label_name": "vulnerable"} {"code": "static int fsmVerify(const char *path, rpmfi fi)\n{\n int rc;\n int saveerrno = errno;\n struct stat dsb;\n mode_t mode = rpmfiFMode(fi);\n\n rc = fsmStat(path, 1, &dsb);\n if (rc)\n\treturn rc;\n\n if (S_ISREG(mode)) {\n\t/* HP-UX (and other os'es) don't permit unlink on busy files. */\n\tchar *rmpath = rstrscat(NULL, path, \"-RPMDELETE\", NULL);\n\trc = fsmRename(path, rmpath);\n\t/* XXX shouldn't we take unlink return code here? */\n\tif (!rc)\n\t (void) fsmUnlink(rmpath);\n\telse\n\t rc = RPMERR_UNLINK_FAILED;\n\tfree(rmpath);\n return (rc ? rc : RPMERR_ENOENT);\t/* XXX HACK */\n } else if (S_ISDIR(mode)) {\n if (S_ISDIR(dsb.st_mode)) return 0;\n if (S_ISLNK(dsb.st_mode)) {\n rc = fsmStat(path, 0, &dsb);\n if (rc == RPMERR_ENOENT) rc = 0;\n if (rc) return rc;\n errno = saveerrno;\n if (S_ISDIR(dsb.st_mode)) return 0;\n }\n } else if (S_ISLNK(mode)) {\n if (S_ISLNK(dsb.st_mode)) {\n char buf[8 * BUFSIZ];\n size_t len;\n rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len);\n errno = saveerrno;\n if (rc) return rc;\n if (rstreq(rpmfiFLink(fi), buf)) return 0;\n }\n } else if (S_ISFIFO(mode)) {\n if (S_ISFIFO(dsb.st_mode)) return 0;\n } else if (S_ISCHR(mode) || S_ISBLK(mode)) {\n if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) &&\n (dsb.st_rdev == rpmfiFRdev(fi))) return 0;\n } else if (S_ISSOCK(mode)) {\n if (S_ISSOCK(dsb.st_mode)) return 0;\n }\n /* XXX shouldn't do this with commit/undo. */\n rc = fsmUnlink(path);\n if (rc == 0)\trc = RPMERR_ENOENT;\n return (rc ? rc : RPMERR_ENOENT);\t/* XXX HACK */\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-59", "cwe_name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.", "url": "https://cwe.mitre.org/data/definitions/59.html", "label_name": "vulnerable"} {"code": "IW_IMPL(int) iw_get_i32le(const iw_byte *b)\n{\n\treturn (iw_int32)(iw_uint32)(b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24));\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-682", "cwe_name": "Incorrect Calculation", "description": "The software performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management.", "url": "https://cwe.mitre.org/data/definitions/682.html", "label_name": "vulnerable"} {"code": "static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,\n\t\tconst iw_byte *d, size_t d_len)\n{\n\tstruct iw_exif_state e;\n\tiw_uint32 ifd;\n\n\tif(d_len<8) return;\n\n\tiw_zeromem(&e,sizeof(struct iw_exif_state));\n\te.d = d;\n\te.d_len = d_len;\n\n\te.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;\n\n\tifd = iw_get_ui32_e(&d[4],e.endian);\n\n\tiwjpeg_scan_exif_ifd(rctx,&e,ifd);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,\n\t\tconst iw_byte *d, size_t d_len)\n{\n\tstruct iw_exif_state e;\n\tiw_uint32 ifd;\n\n\tif(d_len<8) return;\n\n\tiw_zeromem(&e,sizeof(struct iw_exif_state));\n\te.d = d;\n\te.d_len = d_len;\n\n\te.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;\n\n\tifd = iw_get_ui32_e(&d[4],e.endian);\n\n\tiwjpeg_scan_exif_ifd(rctx,&e,ifd);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx,\n\tstruct iw_exif_state *e, iw_uint32 ifd)\n{\n\tunsigned int tag_count;\n\tunsigned int i;\n\tunsigned int tag_pos;\n\tunsigned int tag_id;\n\tunsigned int v;\n\tdouble v_dbl;\n\n\tif(ifd<8 || ifd>e->d_len-18) return;\n\n\ttag_count = iw_get_ui16_e(&e->d[ifd],e->endian);\n\tif(tag_count>1000) return; // Sanity check.\n\n\tfor(i=0;i e->d_len) return; // Avoid overruns.\n\t\ttag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian);\n\n\t\tswitch(tag_id) {\n\t\tcase 274: // 274 = Orientation\n\t\t\tif(get_exif_tag_int_value(e,tag_pos,&v)) {\n\t\t\t\trctx->exif_orientation = v;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 296: // 296 = ResolutionUnit\n\t\t\tif(get_exif_tag_int_value(e,tag_pos,&v)) {\n\t\t\t\trctx->exif_density_unit = v;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 282: // 282 = XResolution\n\t\t\tif(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {\n\t\t\t\trctx->exif_density_x = v_dbl;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 283: // 283 = YResolution\n\t\t\tif(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {\n\t\t\t\trctx->exif_density_y = v_dbl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "IW_IMPL(int) iw_get_input_density(struct iw_context *ctx,\n double *px, double *py, int *pcode)\n{\n\t*px = 1.0;\n\t*py = 1.0;\n\t*pcode = ctx->img1.density_code;\n\tif(ctx->img1.density_code!=IW_DENSITY_UNKNOWN) {\n\t\t*px = ctx->img1.density_x;\n\t\t*py = ctx->img1.density_y;\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-369", "cwe_name": "Divide By Zero", "description": "The product divides a value by zero.", "url": "https://cwe.mitre.org/data/definitions/369.html", "label_name": "vulnerable"} {"code": "_rsvg_io_get_file_path (const gchar * filename,\n const gchar * base_uri)\n{\n gchar *absolute_filename;\n\n if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) {\n absolute_filename = g_strdup (filename);\n } else {\n gchar *tmpcdir;\n gchar *base_filename;\n\n if (base_uri) {\n base_filename = g_filename_from_uri (base_uri, NULL, NULL);\n if (base_filename != NULL) {\n tmpcdir = g_path_get_dirname (base_filename);\n g_free (base_filename);\n } else \n return NULL;\n } else\n tmpcdir = g_get_current_dir ();\n\n absolute_filename = g_build_filename (tmpcdir, filename, NULL);\n g_free (tmpcdir);\n }\n\n return absolute_filename;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox);\n\tif (e) {\n\t\treturn e;\n\t}\n\tif (!((GF_DataInformationBox *)s)->dref) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing dref box in dinf\\n\"));\n\t\t((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);\n\t}\n\treturn GF_OK;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-401", "cwe_name": "Missing Release of Memory after Effective Lifetime", "description": "The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.", "url": "https://cwe.mitre.org/data/definitions/401.html", "label_name": "vulnerable"} {"code": "static void gf_dump_vrml_simple_field(GF_SceneDumper *sdump, GF_FieldInfo field, GF_Node *parent)\n{\n\tu32 i, sf_type;\n\tGF_ChildNodeItem *list;\n\tvoid *slot_ptr;\n\n\tswitch (field.fieldType) {\n\tcase GF_SG_VRML_SFNODE:\n\t\tassert ( *(GF_Node **)field.far_ptr);\n\t\tgf_dump_vrml_node(sdump, *(GF_Node **)field.far_ptr, 0, NULL);\n\t\treturn;\n\tcase GF_SG_VRML_MFNODE:\n\t\tlist = * ((GF_ChildNodeItem **) field.far_ptr);\n\t\tassert( list );\n\t\tsdump->indent++;\n\t\twhile (list) {\n\t\t\tgf_dump_vrml_node(sdump, list->node, 1, NULL);\n\t\t\tlist = list->next;\n\t\t}\n\t\tsdump->indent--;\n\t\treturn;\n\tcase GF_SG_VRML_SFCOMMANDBUFFER:\n\t\treturn;\n\t}\n\tif (gf_sg_vrml_is_sf_field(field.fieldType)) {\n\t\tif (sdump->XMLDump) StartAttribute(sdump, \"value\");\n\t\tgf_dump_vrml_sffield(sdump, field.fieldType, field.far_ptr, 0, parent);\n\t\tif (sdump->XMLDump) EndAttribute(sdump);\n\t} else {\n\t\tGenMFField *mffield;\n\t\tmffield = (GenMFField *) field.far_ptr;\n\t\tsf_type = gf_sg_vrml_get_sf_type(field.fieldType);\n\t\tif (!sdump->XMLDump) {\n\t\t\tgf_fprintf(sdump->trace, \"[\");\n\t\t} else if (sf_type==GF_SG_VRML_SFSTRING) {\n\t\t\tgf_fprintf(sdump->trace, \" value=\\'\");\n\t\t} else {\n\t\t\tStartAttribute(sdump, \"value\");\n\t\t}\n\t\tfor (i=0; icount; i++) {\n\t\t\tif (i) gf_fprintf(sdump->trace, \" \");\n\t\t\tgf_sg_vrml_mf_get_item(field.far_ptr, field.fieldType, &slot_ptr, i);\n\t\t\t/*this is to cope with single MFString which shall appear as SF in XMT*/\n\t\t\tgf_dump_vrml_sffield(sdump, sf_type, slot_ptr, 1, parent);\n\t\t}\n\t\tif (!sdump->XMLDump) {\n\t\t\tgf_fprintf(sdump->trace, \"]\");\n\t\t} else if (sf_type==GF_SG_VRML_SFSTRING) {\n\t\t\tgf_fprintf(sdump->trace, \"\\'\");\n\t\t} else {\n\t\t\tEndAttribute(sdump);\n\t\t}\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "static u8 BS_ReadByte(GF_BitStream *bs)\n{\n\tBool is_eos;\n\tif (bs->bsmode == GF_BITSTREAM_READ) {\n\t\tu8 res;\n\t\tif (bs->position >= bs->size) {\n\t\t\tif (bs->EndOfStream) bs->EndOfStream(bs->par);\n\t\t\tif (!bs->overflow_state) bs->overflow_state = 1;\n\t\t\treturn 0;\n\t\t}\n\t\tres = bs->original[bs->position++];\n\n\t\tif (bs->remove_emul_prevention_byte) {\n\t\t\tif ((bs->nb_zeros==2) && (res==0x03) && (bs->positionsize) && (bs->original[bs->position]<0x04)) {\n\t\t\t\tbs->nb_zeros = 0;\n\t\t\t\tres = bs->original[bs->position++];\n\t\t\t}\n\t\t\tif (!res) bs->nb_zeros++;\n\t\t\telse bs->nb_zeros = 0;\n\t\t}\n\t\treturn res;\n\t}\n\tif (bs->cache_write)\n\t\tbs_flush_write_cache(bs);\n\n\tis_eos = gf_feof(bs->stream);\n\n\t/*we are in FILE mode, test for end of file*/\n\tif (!is_eos || bs->cache_read) {\n\t\tu8 res;\n\t\tBool loc_eos=GF_FALSE;\n\t\tassert(bs->position<=bs->size);\n\t\tbs->position++;\n\n\t\tres = gf_bs_load_byte(bs, &loc_eos);\n\t\tif (loc_eos) goto bs_eof;\n\n\t\tif (bs->remove_emul_prevention_byte) {\n\t\t\tif ((bs->nb_zeros==2) && (res==0x03) && (bs->positionsize)) {\n\t\t\t\tu8 next = gf_bs_load_byte(bs, &loc_eos);\n\t\t\t\tif (next < 0x04) {\n\t\t\t\t\tbs->nb_zeros = 0;\n\t\t\t\t\tres = next;\n\t\t\t\t\tbs->position++;\n\t\t\t\t} else {\n\t\t\t\t\tgf_bs_seek(bs, bs->position);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!res) bs->nb_zeros++;\n\t\t\telse bs->nb_zeros = 0;\n\t\t}\n\t\treturn res;\n\t}\n\nbs_eof:\n\tif (bs->EndOfStream) {\n\t\tbs->EndOfStream(bs->par);\n\t\tif (!bs->overflow_state) bs->overflow_state = 1;\n\t} else {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CORE, (\"[BS] Attempt to overread bitstream\\n\"));\n\t}\n\tassert(bs->position <= 1+bs->size);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-617", "cwe_name": "Reachable Assertion", "description": "The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.", "url": "https://cwe.mitre.org/data/definitions/617.html", "label_name": "vulnerable"} {"code": "static void cmd_parse_lsub (IMAP_DATA* idata, char* s)\n{\n char buf[STRING];\n char errstr[STRING];\n BUFFER err, token;\n ciss_url_t url;\n IMAP_LIST list;\n\n if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)\n {\n /* caller will handle response itself */\n cmd_parse_list (idata, s);\n return;\n }\n\n if (!option (OPTIMAPCHECKSUBSCRIBED))\n return;\n\n idata->cmdtype = IMAP_CT_LIST;\n idata->cmddata = &list;\n cmd_parse_list (idata, s);\n idata->cmddata = NULL;\n /* noselect is for a gmail quirk (#3445) */\n if (!list.name || list.noselect)\n return;\n\n dprint (3, (debugfile, \"Subscribing to %s\\n\", list.name));\n\n strfcpy (buf, \"mailboxes \\\"\", sizeof (buf));\n mutt_account_tourl (&idata->conn->account, &url);\n /* escape \\ and \" */\n imap_quote_string(errstr, sizeof (errstr), list.name);\n url.path = errstr + 1;\n url.path[strlen(url.path) - 1] = '\\0';\n if (!mutt_strcmp (url.user, ImapUser))\n url.user = NULL;\n url_ciss_tostring (&url, buf + 11, sizeof (buf) - 10, 0);\n safe_strcat (buf, sizeof (buf), \"\\\"\");\n mutt_buffer_init (&token);\n mutt_buffer_init (&err);\n err.data = errstr;\n err.dsize = sizeof (errstr);\n if (mutt_parse_rc_line (buf, &token, &err))\n dprint (1, (debugfile, \"Error adding subscribed mailbox: %s\\n\", errstr));\n FREE (&token.data);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "vulnerable"} {"code": "int mutt_seqset_iterator_next(struct SeqsetIterator *iter, unsigned int *next)\n{\n if (!iter || !next)\n return -1;\n\n if (iter->in_range)\n {\n if ((iter->down && (iter->range_cur == (iter->range_end - 1))) ||\n (!iter->down && (iter->range_cur == (iter->range_end + 1))))\n {\n iter->in_range = 0;\n }\n }\n\n if (!iter->in_range)\n {\n iter->substr_cur = iter->substr_end;\n if (iter->substr_cur == iter->eostr)\n return 1;\n\n while (!*(iter->substr_cur))\n iter->substr_cur++;\n iter->substr_end = strchr(iter->substr_cur, ',');\n if (!iter->substr_end)\n iter->substr_end = iter->eostr;\n else\n *(iter->substr_end) = '\\0';\n\n char *range_sep = strchr(iter->substr_cur, ':');\n if (range_sep)\n *range_sep++ = '\\0';\n\n if (mutt_str_atoui(iter->substr_cur, &iter->range_cur) != 0)\n return -1;\n if (range_sep)\n {\n if (mutt_str_atoui(range_sep, &iter->range_end) != 0)\n return -1;\n }\n else\n iter->range_end = iter->range_cur;\n\n iter->down = (iter->range_end < iter->range_cur);\n iter->in_range = 1;\n }\n\n *next = iter->range_cur;\n if (iter->down)\n iter->range_cur--;\n else\n iter->range_cur++;\n\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static int msg_parse_fetch(struct ImapHeader *h, char *s)\n{\n char tmp[SHORT_STRING];\n char *ptmp = NULL;\n\n if (!s)\n return -1;\n\n while (*s)\n {\n SKIPWS(s);\n\n if (mutt_str_strncasecmp(\"FLAGS\", s, 5) == 0)\n {\n s = msg_parse_flags(h, s);\n if (!s)\n return -1;\n }\n else if (mutt_str_strncasecmp(\"UID\", s, 3) == 0)\n {\n s += 3;\n SKIPWS(s);\n if (mutt_str_atoui(s, &h->data->uid) < 0)\n return -1;\n\n s = imap_next_word(s);\n }\n else if (mutt_str_strncasecmp(\"INTERNALDATE\", s, 12) == 0)\n {\n s += 12;\n SKIPWS(s);\n if (*s != '\\\"')\n {\n mutt_debug(1, \"bogus INTERNALDATE entry: %s\\n\", s);\n return -1;\n }\n s++;\n ptmp = tmp;\n while (*s && *s != '\\\"')\n *ptmp++ = *s++;\n if (*s != '\\\"')\n return -1;\n s++; /* skip past the trailing \" */\n *ptmp = '\\0';\n h->received = mutt_date_parse_imap(tmp);\n }\n else if (mutt_str_strncasecmp(\"RFC822.SIZE\", s, 11) == 0)\n {\n s += 11;\n SKIPWS(s);\n ptmp = tmp;\n while (isdigit((unsigned char) *s))\n *ptmp++ = *s++;\n *ptmp = '\\0';\n if (mutt_str_atol(tmp, &h->content_length) < 0)\n return -1;\n }\n else if ((mutt_str_strncasecmp(\"BODY\", s, 4) == 0) ||\n (mutt_str_strncasecmp(\"RFC822.HEADER\", s, 13) == 0))\n {\n /* handle above, in msg_fetch_header */\n return -2;\n }\n else if (*s == ')')\n s++; /* end of request */\n else if (*s)\n {\n /* got something i don't understand */\n imap_error(\"msg_parse_fetch\", s);\n return -1;\n }\n }\n\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "void imap_quote_string(char *dest, size_t dlen, const char *src, bool quote_backtick)\n{\n const char *quote = \"`\\\"\\\\\";\n if (!quote_backtick)\n quote++;\n\n char *pt = dest;\n const char *s = src;\n\n *pt++ = '\"';\n /* save room for trailing quote-char */\n dlen -= 2;\n\n for (; *s && dlen; s++)\n {\n if (strchr(quote, *s))\n {\n if (dlen < 2)\n break;\n dlen -= 2;\n *pt++ = '\\\\';\n *pt++ = *s;\n }\n else\n {\n *pt++ = *s;\n dlen--;\n }\n }\n *pt++ = '\"';\n *pt = '\\0';\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)\n{\n unsigned nSyms = darray_size(expr->keysym_list.syms);\n unsigned numEntries = darray_size(append->keysym_list.syms);\n\n darray_append(expr->keysym_list.symsMapIndex, nSyms);\n darray_append(expr->keysym_list.symsNumEntries, numEntries);\n darray_concat(expr->keysym_list.syms, append->keysym_list.syms);\n\n FreeStmt((ParseCommon *) &append);\n\n return expr;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)\n{\n\tcac_private_data_t * priv = CAC_DATA(card);\n\n\tSC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);\n if (card->serialnr.len) {\n *serial = card->serialnr;\n SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n }\n\tif (priv->cac_id_len) {\n\t\tserial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);\n\t\tmemcpy(serial->value, priv->cac_id, priv->cac_id_len);\n\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)\n{\n\tsize_t cipher_len;\n\tsize_t i;\n\tunsigned char iv[16] = { 0 };\n\tunsigned char plaintext[4096] = { 0 };\n\tepass2003_exdata *exdata = NULL;\n\n\tif (!card->drv_data) \n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\n\texdata = (epass2003_exdata *)card->drv_data;\n\n\t/* no cipher */\n\tif (in[0] == 0x99)\n\t\treturn 0;\n\n\t/* parse cipher length */\n\tif (0x01 == in[2] && 0x82 != in[1]) {\n\t\tcipher_len = in[1];\n\t\ti = 3;\n\t}\n\telse if (0x01 == in[3] && 0x81 == in[1]) {\n\t\tcipher_len = in[2];\n\t\ti = 4;\n\t}\n\telse if (0x01 == in[4] && 0x82 == in[1]) {\n\t\tcipher_len = in[2] * 0x100;\n\t\tcipher_len += in[3];\n\t\ti = 5;\n\t}\n\telse {\n\t\treturn -1;\n\t}\n\n\tif (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)\n\t\treturn -1;\n\n\t/* decrypt */\n\tif (KEY_TYPE_AES == exdata->smtype)\n\t\taes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);\n\telse\n\t\tdes3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);\n\n\t/* unpadding */\n\twhile (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))\n\t\tcipher_len--;\n\n\tif (2 == cipher_len)\n\t\treturn -1;\n\n\tmemcpy(out, plaintext, cipher_len - 2);\n\t*out_len = cipher_len - 2;\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n{\n\tmuscle_private_t* priv = MUSCLE_DATA(card);\n\tmscfs_t *fs = priv->fs;\n\tint x;\n\tint count = 0;\n\n\tmscfs_check_cache(priv->fs);\n\n\tfor(x = 0; x < fs->cache.size; x++) {\n\t\tu8* oid= fs->cache.array[x].objectId.id;\n\t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n\t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n\t\t\toid[0],oid[1],oid[2],oid[3]);\n\t\tif(0 == memcmp(fs->currentPath, oid, 2)) {\n\t\t\tbuf[0] = oid[2];\n\t\t\tbuf[1] = oid[3];\n\t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n\t\t\tbuf += 2;\n\t\t\tcount+=2;\n\t\t}\n\t}\n\treturn count;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,\n\t\t\t size_t sec_attr_len)\n{\n\tu8 *tmp;\n\tif (!sc_file_valid(file)) {\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\t}\n\n\tif (sec_attr == NULL) {\n\t\tif (file->sec_attr != NULL)\n\t\t\tfree(file->sec_attr);\n\t\tfile->sec_attr = NULL;\n\t\tfile->sec_attr_len = 0;\n\t\treturn 0;\n\t }\n\ttmp = (u8 *) realloc(file->sec_attr, sec_attr_len);\n\tif (!tmp) {\n\t\tif (file->sec_attr)\n\t\t\tfree(file->sec_attr);\n\t\tfile->sec_attr = NULL;\n\t\tfile->sec_attr_len = 0;\n\t\treturn SC_ERROR_OUT_OF_MEMORY;\n\t}\n\tfile->sec_attr = tmp;\n\tmemcpy(file->sec_attr, sec_attr, sec_attr_len);\n\tfile->sec_attr_len = sec_attr_len;\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "static int read_public_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\n\tu8 buf[2048], *p = buf;\n\tsize_t bufsize, keysize;\n\n\tr = select_app_df();\n\tif (r)\n\t\treturn 1;\n\tsc_format_path(\"I1012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select public key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = file->size;\n\tsc_file_free(file);\n\tr = sc_read_binary(card, 0, buf, bufsize, 0);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Unable to read public key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = r;\n\tdo {\n\t\tif (bufsize < 4)\n\t\t\treturn 3;\n\t\tkeysize = (p[0] << 8) | p[1];\n\t\tif (keysize == 0)\n\t\t\tbreak;\n\t\tif (keysize < 3)\n\t\t\treturn 3;\n\t\tif (p[2] == opt_key_num)\n\t\t\tbreak;\n\t\tp += keysize;\n\t\tbufsize -= keysize;\n\t} while (1);\n\tif (keysize == 0) {\n\t\tprintf(\"Key number %d not found.\\n\", opt_key_num);\n\t\treturn 2;\n\t}\n\treturn parse_public_key(p, keysize, rsa);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static int read_private_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\n\tconst sc_acl_entry_t *e;\n\n\tu8 buf[2048], *p = buf;\n\tsize_t bufsize, keysize;\n\n\tr = select_app_df();\n\tif (r)\n\t\treturn 1;\n\tsc_format_path(\"I0012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\te = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\tif (e == NULL || e->method == SC_AC_NEVER)\n\t\treturn 10;\n\tbufsize = file->size;\n\tsc_file_free(file);\n\tr = sc_read_binary(card, 0, buf, bufsize, 0);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Unable to read private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = r;\n\tdo {\n\t\tif (bufsize < 4)\n\t\t\treturn 3;\n\t\tkeysize = (p[0] << 8) | p[1];\n\t\tif (keysize == 0)\n\t\t\tbreak;\n\t\tif (keysize < 3)\n\t\t\treturn 3;\n\t\tif (p[2] == opt_key_num)\n\t\t\tbreak;\n\t\tp += keysize;\n\t\tbufsize -= keysize;\n\t} while (1);\n\tif (keysize == 0) {\n\t\tprintf(\"Key number %d not found.\\n\", opt_key_num);\n\t\treturn 2;\n\t}\n\treturn parse_private_key(p, keysize, rsa);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "vrrp_tfile_end_handler(void)\n{\n\tvrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files);\n\tstruct stat statb;\n\tFILE *tf;\n\tint ret;\n\n\tif (!tfile->file_path) {\n\t\treport_config_error(CONFIG_GENERAL_ERROR, \"No file set for track_file %s - removing\", tfile->fname);\n\t\tfree_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail);\n\t\treturn;\n\t}\n\n\tif (track_file_init == TRACK_FILE_NO_INIT)\n\t\treturn;\n\n\tret = stat(tfile->file_path, &statb);\n\tif (!ret) {\n\t\tif (track_file_init == TRACK_FILE_CREATE) {\n\t\t\t/* The file exists */\n\t\t\treturn;\n\t\t}\n\t\tif ((statb.st_mode & S_IFMT) != S_IFREG) {\n\t\t\t/* It is not a regular file */\n\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"Cannot initialise track file %s - it is not a regular file\", tfile->fname);\n\t\t\treturn;\n\t\t}\n\n\t\t/* Don't overwrite a file on reload */\n\t\tif (reload)\n\t\t\treturn;\n\t}\n\n\tif (!__test_bit(CONFIG_TEST_BIT, &debug)) {\n\t\t/* Write the value to the file */\n\t\tif ((tf = fopen(tfile->file_path, \"w\"))) {\n\t\t\tfprintf(tf, \"%d\\n\", track_file_init_value);\n\t\t\tfclose(tf);\n\t\t}\n\t\telse\n\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"Unable to initialise track file %s\", tfile->fname);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-59", "cwe_name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.", "url": "https://cwe.mitre.org/data/definitions/59.html", "label_name": "vulnerable"} {"code": "int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,\n\t\tconst URI_TYPE(QueryList) * queryList,\n\t\tint maxChars, int * charsWritten, int * charsRequired,\n\t\tUriBool spaceToPlus, UriBool normalizeBreaks) {\n\tUriBool firstItem = URI_TRUE;\n\tint ampersandLen = 0; /* increased to 1 from second item on */\n\tURI_CHAR * write = dest;\n\n\t/* Subtract terminator */\n\tif (dest == NULL) {\n\t\t*charsRequired = 0;\n\t} else {\n\t\tmaxChars--;\n\t}\n\n\twhile (queryList != NULL) {\n\t\tconst URI_CHAR * const key = queryList->key;\n\t\tconst URI_CHAR * const value = queryList->value;\n\t\tconst int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);\n\t\tconst int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);\n\t\tconst int keyRequiredChars = worstCase * keyLen;\n\t\tconst int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);\n\t\tconst int valueRequiredChars = worstCase * valueLen;\n\n\t\tif (dest == NULL) {\n\t\t\t(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)\n\t\t\t\t\t\t? 0\n\t\t\t\t\t\t: 1 + valueRequiredChars);\n\n\t\t\tif (firstItem == URI_TRUE) {\n\t\t\t\tampersandLen = 1;\n\t\t\t\tfirstItem = URI_FALSE;\n\t\t\t}\n\t\t} else {\n\t\t\tif ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {\n\t\t\t\treturn URI_ERROR_OUTPUT_TOO_LARGE;\n\t\t\t}\n\n\t\t\t/* Copy key */\n\t\t\tif (firstItem == URI_TRUE) {\n\t\t\t\tampersandLen = 1;\n\t\t\t\tfirstItem = URI_FALSE;\n\t\t\t} else {\n\t\t\t\twrite[0] = _UT('&');\n\t\t\t\twrite++;\n\t\t\t}\n\t\t\twrite = URI_FUNC(EscapeEx)(key, key + keyLen,\n\t\t\t\t\twrite, spaceToPlus, normalizeBreaks);\n\n\t\t\tif (value != NULL) {\n\t\t\t\tif ((write - dest) + 1 + valueRequiredChars > maxChars) {\n\t\t\t\t\treturn URI_ERROR_OUTPUT_TOO_LARGE;\n\t\t\t\t}\n\n\t\t\t\t/* Copy value */\n\t\t\t\twrite[0] = _UT('=');\n\t\t\t\twrite++;\n\t\t\t\twrite = URI_FUNC(EscapeEx)(value, value + valueLen,\n\t\t\t\t\t\twrite, spaceToPlus, normalizeBreaks);\n\t\t\t}\n\t\t}\n\n\t\tqueryList = queryList->next;\n\t}\n\n\tif (dest != NULL) {\n\t\twrite[0] = _UT('\\0');\n\t\tif (charsWritten != NULL) {\n\t\t\t*charsWritten = (int)(write - dest) + 1; /* .. for terminator */\n\t\t}\n\t}\n\n\treturn URI_SUCCESS;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "ber_parse_header(STREAM s, int tagval, int *length)\n{\n\tint tag, len;\n\n\tif (tagval > 0xff)\n\t{\n\t\tin_uint16_be(s, tag);\n\t}\n\telse\n\t{\n\t\tin_uint8(s, tag);\n\t}\n\n\tif (tag != tagval)\n\t{\n\t\tlogger(Core, Error, \"ber_parse_header(), expected tag %d, got %d\", tagval, tag);\n\t\treturn False;\n\t}\n\n\tin_uint8(s, len);\n\n\tif (len & 0x80)\n\t{\n\t\tlen &= ~0x80;\n\t\t*length = 0;\n\t\twhile (len--)\n\t\t\tnext_be(s, *length);\n\t}\n\telse\n\t\t*length = len;\n\n\treturn s_check(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "ber_parse_header(STREAM s, int tagval, int *length)\n{\n\tint tag, len;\n\n\tif (tagval > 0xff)\n\t{\n\t\tin_uint16_be(s, tag);\n\t}\n\telse\n\t{\n\t\tin_uint8(s, tag);\n\t}\n\n\tif (tag != tagval)\n\t{\n\t\tlogger(Core, Error, \"ber_parse_header(), expected tag %d, got %d\", tagval, tag);\n\t\treturn False;\n\t}\n\n\tin_uint8(s, len);\n\n\tif (len & 0x80)\n\t{\n\t\tlen &= ~0x80;\n\t\t*length = 0;\n\t\twhile (len--)\n\t\t\tnext_be(s, *length);\n\t}\n\telse\n\t\t*length = len;\n\n\treturn s_check(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "ber_parse_header(STREAM s, int tagval, int *length)\n{\n\tint tag, len;\n\n\tif (tagval > 0xff)\n\t{\n\t\tin_uint16_be(s, tag);\n\t}\n\telse\n\t{\n\t\tin_uint8(s, tag);\n\t}\n\n\tif (tag != tagval)\n\t{\n\t\tlogger(Core, Error, \"ber_parse_header(), expected tag %d, got %d\", tagval, tag);\n\t\treturn False;\n\t}\n\n\tin_uint8(s, len);\n\n\tif (len & 0x80)\n\t{\n\t\tlen &= ~0x80;\n\t\t*length = 0;\n\t\twhile (len--)\n\t\t\tnext_be(s, *length);\n\t}\n\telse\n\t\t*length = len;\n\n\treturn s_check(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n{\n\tUNUSED(size);\n\tint indexw;\n\tint indexh;\n\tint code;\n\tint collen;\n\tint replen;\n\tint color;\n\tint x;\n\tint revcode;\n\tuint8 * last_line;\n\tuint8 * this_line;\n\tuint8 * org_in;\n\tuint8 * org_out;\n\n\torg_in = in;\n\torg_out = out;\n\tlast_line = 0;\n\tindexh = 0;\n\twhile (indexh < height)\n\t{\n\t\tout = (org_out + width * height * 4) - ((indexh + 1) * width * 4);\n\t\tcolor = 0;\n\t\tthis_line = out;\n\t\tindexw = 0;\n\t\tif (last_line == 0)\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tcolor = CVAL(in);\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = CVAL(in);\n\t\t\t\t\tif (x & 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\tcolor = -x;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tcolor = x;\n\t\t\t\t\t}\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tindexh++;\n\t\tlast_line = this_line;\n\t}\n\treturn (int) (in - org_in);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "mcs_parse_domain_params(STREAM s)\n{\n\tint length;\n\n\tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n\tin_uint8s(s, length);\n\n\treturn s_check(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-191", "cwe_name": "Integer Underflow (Wrap or Wraparound)", "description": "The product subtracts one value from another, such that the result is less than the minimum allowable integer value, which produces a value that is not equal to the correct result.", "url": "https://cwe.mitre.org/data/definitions/191.html", "label_name": "vulnerable"} {"code": "mcs_parse_domain_params(STREAM s)\n{\n\tint length;\n\n\tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n\tin_uint8s(s, length);\n\n\treturn s_check(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "mcs_parse_domain_params(STREAM s)\n{\n\tint length;\n\n\tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n\tin_uint8s(s, length);\n\n\treturn s_check(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "mcs_parse_domain_params(STREAM s)\n{\n\tint length;\n\n\tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n\tin_uint8s(s, length);\n\n\treturn s_check(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "mcs_parse_domain_params(STREAM s)\n{\n\tint length;\n\n\tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n\tin_uint8s(s, length);\n\n\treturn s_check(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "process_bitmap_updates(STREAM s)\n{\n\tuint16 num_updates;\n\tuint16 left, top, right, bottom, width, height;\n\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n\tuint8 *data, *bmpdata;\n\tint i;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\n\tin_uint16_le(s, num_updates);\n\n\tfor (i = 0; i < num_updates; i++)\n\t{\n\t\tin_uint16_le(s, left);\n\t\tin_uint16_le(s, top);\n\t\tin_uint16_le(s, right);\n\t\tin_uint16_le(s, bottom);\n\t\tin_uint16_le(s, width);\n\t\tin_uint16_le(s, height);\n\t\tin_uint16_le(s, bpp);\n\t\tBpp = (bpp + 7) / 8;\n\t\tin_uint16_le(s, compress);\n\t\tin_uint16_le(s, bufsize);\n\n\t\tcx = right - left + 1;\n\t\tcy = bottom - top + 1;\n\n\t\tlogger(Graphics, Debug,\n\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n\t\t left, top, right, bottom, width, height, Bpp, compress);\n\n\t\tif (!compress)\n\t\t{\n\t\t\tint y;\n\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\t\tfor (y = 0; y < height; y++)\n\t\t\t{\n\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n\t\t\t\t\t width * Bpp);\n\t\t\t}\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t\txfree(bmpdata);\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tif (compress & 0x400)\n\t\t{\n\t\t\tsize = bufsize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tin_uint8s(s, 2);\t/* pad */\n\t\t\tin_uint16_le(s, size);\n\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n\t\t}\n\t\tin_uint8p(s, data, size);\n\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n\t\t{\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogger(Graphics, Warning,\n\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n\t\t}\n\n\t\txfree(bmpdata);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "process_bitmap_updates(STREAM s)\n{\n\tuint16 num_updates;\n\tuint16 left, top, right, bottom, width, height;\n\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n\tuint8 *data, *bmpdata;\n\tint i;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\n\tin_uint16_le(s, num_updates);\n\n\tfor (i = 0; i < num_updates; i++)\n\t{\n\t\tin_uint16_le(s, left);\n\t\tin_uint16_le(s, top);\n\t\tin_uint16_le(s, right);\n\t\tin_uint16_le(s, bottom);\n\t\tin_uint16_le(s, width);\n\t\tin_uint16_le(s, height);\n\t\tin_uint16_le(s, bpp);\n\t\tBpp = (bpp + 7) / 8;\n\t\tin_uint16_le(s, compress);\n\t\tin_uint16_le(s, bufsize);\n\n\t\tcx = right - left + 1;\n\t\tcy = bottom - top + 1;\n\n\t\tlogger(Graphics, Debug,\n\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n\t\t left, top, right, bottom, width, height, Bpp, compress);\n\n\t\tif (!compress)\n\t\t{\n\t\t\tint y;\n\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\t\tfor (y = 0; y < height; y++)\n\t\t\t{\n\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n\t\t\t\t\t width * Bpp);\n\t\t\t}\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t\txfree(bmpdata);\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tif (compress & 0x400)\n\t\t{\n\t\t\tsize = bufsize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tin_uint8s(s, 2);\t/* pad */\n\t\t\tin_uint16_le(s, size);\n\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n\t\t}\n\t\tin_uint8p(s, data, size);\n\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n\t\t{\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogger(Graphics, Warning,\n\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n\t\t}\n\n\t\txfree(bmpdata);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-191", "cwe_name": "Integer Underflow (Wrap or Wraparound)", "description": "The product subtracts one value from another, such that the result is less than the minimum allowable integer value, which produces a value that is not equal to the correct result.", "url": "https://cwe.mitre.org/data/definitions/191.html", "label_name": "vulnerable"} {"code": "process_bitmap_updates(STREAM s)\n{\n\tuint16 num_updates;\n\tuint16 left, top, right, bottom, width, height;\n\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n\tuint8 *data, *bmpdata;\n\tint i;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\n\tin_uint16_le(s, num_updates);\n\n\tfor (i = 0; i < num_updates; i++)\n\t{\n\t\tin_uint16_le(s, left);\n\t\tin_uint16_le(s, top);\n\t\tin_uint16_le(s, right);\n\t\tin_uint16_le(s, bottom);\n\t\tin_uint16_le(s, width);\n\t\tin_uint16_le(s, height);\n\t\tin_uint16_le(s, bpp);\n\t\tBpp = (bpp + 7) / 8;\n\t\tin_uint16_le(s, compress);\n\t\tin_uint16_le(s, bufsize);\n\n\t\tcx = right - left + 1;\n\t\tcy = bottom - top + 1;\n\n\t\tlogger(Graphics, Debug,\n\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n\t\t left, top, right, bottom, width, height, Bpp, compress);\n\n\t\tif (!compress)\n\t\t{\n\t\t\tint y;\n\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\t\tfor (y = 0; y < height; y++)\n\t\t\t{\n\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n\t\t\t\t\t width * Bpp);\n\t\t\t}\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t\txfree(bmpdata);\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tif (compress & 0x400)\n\t\t{\n\t\t\tsize = bufsize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tin_uint8s(s, 2);\t/* pad */\n\t\t\tin_uint16_le(s, size);\n\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n\t\t}\n\t\tin_uint8p(s, data, size);\n\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n\t\t{\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogger(Graphics, Warning,\n\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n\t\t}\n\n\t\txfree(bmpdata);\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int\n lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!target) {\n PyErr_SetString(PyExc_ValueError,\n \"field target is required for For\");\n return NULL;\n }\n if (!iter) {\n PyErr_SetString(PyExc_ValueError,\n \"field iter is required for For\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = For_kind;\n p->v.For.target = target;\n p->v.For.iter = iter;\n p->v.For.body = body;\n p->v.For.orelse = orelse;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "num_stmts(const node *n)\n{\n int i, l;\n node *ch;\n\n switch (TYPE(n)) {\n case single_input:\n if (TYPE(CHILD(n, 0)) == NEWLINE)\n return 0;\n else\n return num_stmts(CHILD(n, 0));\n case file_input:\n l = 0;\n for (i = 0; i < NCH(n); i++) {\n ch = CHILD(n, i);\n if (TYPE(ch) == stmt)\n l += num_stmts(ch);\n }\n return l;\n case stmt:\n return num_stmts(CHILD(n, 0));\n case compound_stmt:\n return 1;\n case simple_stmt:\n return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */\n case suite:\n if (NCH(n) == 1)\n return num_stmts(CHILD(n, 0));\n else {\n l = 0;\n for (i = 2; i < (NCH(n) - 1); i++)\n l += num_stmts(CHILD(n, i));\n return l;\n }\n default: {\n char buf[128];\n\n sprintf(buf, \"Non-statement found: %d %d\",\n TYPE(n), NCH(n));\n Py_FatalError(buf);\n }\n }\n Py_UNREACHABLE();\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static char *oidc_cache_get_hashed_key(request_rec *r, const char *passphrase,\n\t\tconst char *key) {\n\tchar *input = apr_psprintf(r->pool, \"%s:%s\", passphrase, key);\n\tchar *output = NULL;\n\tif (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,\n\t\t\tinput, &output) == FALSE) {\n\t\toidc_error(r,\n\t\t\t\t\"oidc_util_hash_string_and_base64url_encode returned an error\");\n\t\treturn NULL;\n\t}\n\treturn output;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-330", "cwe_name": "Use of Insufficiently Random Values", "description": "The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.", "url": "https://cwe.mitre.org/data/definitions/330.html", "label_name": "vulnerable"} {"code": "static struct mobj *alloc_ta_mem(size_t size)\n{\n#ifdef CFG_PAGED_USER_TA\n\treturn mobj_paged_alloc(size);\n#else\n\tstruct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr);\n\n\tif (mobj)\n\t\tmemset(mobj_get_va(mobj, 0), 0, size);\n\treturn mobj;\n#endif\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-189", "cwe_name": "Numeric Errors", "description": "Weaknesses in this category are related to improper calculation or conversion of numbers.", "url": "https://cwe.mitre.org/data/definitions/189.html", "label_name": "vulnerable"} {"code": "int main(int argc, const char *argv[])\n{\n\tstruct group *grent;\n\tconst char *cmd;\n\tconst char *path;\n\tint i;\n\tstruct passwd *pw;\n\n\tgrent = getgrnam(ABUILD_GROUP);\n\tif (grent == NULL)\n\t\terrx(1, \"%s: Group not found\", ABUILD_GROUP);\n\n\tchar *name = NULL;\n\tpw = getpwuid(getuid());\n\tif (pw)\n\t\tname = pw->pw_name;\n\n\tif (!is_in_group(grent->gr_gid)) {\n\t\terrx(1, \"User %s is not a member of group %s\\n\",\n\t\t\tname ? name : \"(unknown)\", ABUILD_GROUP);\n\t}\n\n\tif (name == NULL)\n\t\twarnx(\"Could not find username for uid %d\\n\", getuid());\n\tsetenv(\"USER\", name ?: \"\", 1);\n\n\tcmd = strrchr(argv[0], '/');\n\tif (cmd)\n\t\tcmd++;\n\telse\n\t\tcmd = argv[0];\n\tcmd = strchr(cmd, '-');\n\tif (cmd == NULL)\n\t\terrx(1, \"Calling command has no '-'\");\n\tcmd++;\n\n\tpath = get_command_path(cmd);\n\tif (path == NULL)\n\t\terrx(1, \"%s: Not a valid subcommand\", cmd);\n\n\t/* we dont allow --allow-untrusted option */\n\tfor (i = 1; i < argc; i++)\n\t\tif (strcmp(argv[i], \"--allow-untrusted\") == 0)\n\t\t\terrx(1, \"%s: not allowed option\", \"--allow-untrusted\");\n\n\targv[0] = path;\n\t/* set our uid to root so bbsuid --install works */\n\tsetuid(0);\n\t/* set our gid to root so apk commit hooks run with the same gid as for \"sudo apk add ...\" */\n\tsetgid(0);\n\texecv(path, (char * const*)argv);\n\tperror(path);\n\treturn 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": "do_encrypt (const RIJNDAEL_context *ctx,\n unsigned char *bx, const unsigned char *ax)\n{\n#ifdef USE_AMD64_ASM\n return _gcry_aes_amd64_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds,\n\t\t\t\t encT);\n#elif defined(USE_ARM_ASM)\n return _gcry_aes_arm_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, encT);\n#else\n return do_encrypt_fn (ctx, bx, ax);\n#endif /* !USE_ARM_ASM && !USE_AMD64_ASM*/\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-668", "cwe_name": "Exposure of Resource to Wrong Sphere", "description": "The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.", "url": "https://cwe.mitre.org/data/definitions/668.html", "label_name": "vulnerable"} {"code": "static void ssdp_recv(int sd)\n{\n\tssize_t len;\n\tstruct sockaddr sa;\n\tsocklen_t salen;\n\tchar buf[MAX_PKT_SIZE];\n\n\tmemset(buf, 0, sizeof(buf));\n\tlen = recvfrom(sd, buf, sizeof(buf), MSG_DONTWAIT, &sa, &salen);\n\tif (len > 0) {\n\t\tbuf[len] = 0;\n\n\t\tif (sa.sa_family != AF_INET)\n\t\t\treturn;\n\n\t\tif (strstr(buf, \"M-SEARCH *\")) {\n\t\t\tsize_t i;\n\t\t\tchar *ptr, *type;\n\t\t\tstruct ifsock *ifs;\n\t\t\tstruct sockaddr_in *sin = (struct sockaddr_in *)&sa;\n\n\t\t\tifs = find_outbound(&sa);\n\t\t\tif (!ifs) {\n\t\t\t\tlogit(LOG_DEBUG, \"No matching socket for client %s\", inet_ntoa(sin->sin_addr));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlogit(LOG_DEBUG, \"Matching socket for client %s\", inet_ntoa(sin->sin_addr));\n\n\t\t\ttype = strcasestr(buf, \"\\r\\nST:\");\n\t\t\tif (!type) {\n\t\t\t\tlogit(LOG_DEBUG, \"No Search Type (ST:) found in M-SEARCH *, assuming \" SSDP_ST_ALL);\n\t\t\t\ttype = SSDP_ST_ALL;\n\t\t\t\tsend_message(ifs, type, &sa);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttype = strchr(type, ':');\n\t\t\tif (!type)\n\t\t\t\treturn;\n\t\t\ttype++;\n\t\t\twhile (isspace(*type))\n\t\t\t\ttype++;\n\n\t\t\tptr = strstr(type, \"\\r\\n\");\n\t\t\tif (!ptr)\n\t\t\t\treturn;\n\t\t\t*ptr = 0;\n\n\t\t\tfor (i = 0; supported_types[i]; i++) {\n\t\t\t\tif (!strcmp(supported_types[i], type)) {\n\t\t\t\t\tlogit(LOG_DEBUG, \"M-SEARCH * ST: %s from %s port %d\", type,\n\t\t\t\t\t inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));\n\t\t\t\t\tsend_message(ifs, type, &sa);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogit(LOG_DEBUG, \"M-SEARCH * for unsupported ST: %s from %s\", type,\n\t\t\t inet_ntoa(sin->sin_addr));\n\t\t}\n\t}\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-193", "cwe_name": "Off-by-one Error", "description": "A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.", "url": "https://cwe.mitre.org/data/definitions/193.html", "label_name": "vulnerable"} {"code": "Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {\n Sfdouble_t d;\n char *last;\n\n if (*str == 0) {\n if (ptr) *ptr = (char *)str;\n return 0;\n }\n errno = 0;\n d = number(str, &last, shp->inarith ? 0 : 10, NULL);\n if (*last) {\n if (*last != '.' || last[1] != '.') {\n d = strval(shp, str, &last, arith, mode);\n Varsubscript = true;\n }\n if (!ptr && *last && mode > 0) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);\n } else if (!d && *str == '-') {\n d = -0.0;\n }\n if (ptr) *ptr = last;\n return d;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-77", "cwe_name": "Improper Neutralization of Special Elements used in a Command ('Command Injection')", "description": "The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/77.html", "label_name": "vulnerable"} {"code": "GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.\n{\n\tif (ms)\n\t{\n\t\tint32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];\n\t\tif (nestsize == 0 && ms->nest_level == 0)\n\t\t\tnestsize = ms->buffer_size_longs;\n\n\t\tif (size + 2 <= nestsize) return GPMF_OK;\n\t}\n\treturn GPMF_ERROR_BAD_STRUCTURE;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "parseuid(const char *s, uid_t *uid)\n{\n\tstruct passwd *pw;\n\tconst char *errstr;\n\n\tif ((pw = getpwnam(s)) != NULL) {\n\t\t*uid = pw->pw_uid;\n\t\treturn 0;\n\t}\n\t#if !defined(__linux__) && !defined(__NetBSD__)\n\t*uid = strtonum(s, 0, UID_MAX, &errstr);\n\t#else\n\tsscanf(s, \"%d\", uid);\n\t#endif\n\tif (errstr)\n\t\treturn -1;\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-754", "cwe_name": "Improper Check for Unusual or Exceptional Conditions", "description": "The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.", "url": "https://cwe.mitre.org/data/definitions/754.html", "label_name": "vulnerable"} {"code": "pci_emul_mem_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,\n\t\t int size, uint64_t *val, void *arg1, long arg2)\n{\n\tstruct pci_vdev *pdi = arg1;\n\tstruct pci_vdev_ops *ops = pdi->dev_ops;\n\tuint64_t offset;\n\tint bidx = (int) arg2;\n\n\tassert(bidx <= PCI_BARMAX);\n\tassert(pdi->bar[bidx].type == PCIBAR_MEM32 ||\n\t pdi->bar[bidx].type == PCIBAR_MEM64);\n\tassert(addr >= pdi->bar[bidx].addr &&\n\t addr + size <= pdi->bar[bidx].addr + pdi->bar[bidx].size);\n\n\toffset = addr - pdi->bar[bidx].addr;\n\n\tif (dir == MEM_F_WRITE) {\n\t\tif (size == 8) {\n\t\t\t(*ops->vdev_barwrite)(ctx, vcpu, pdi, bidx, offset,\n\t\t\t\t\t 4, *val & 0xffffffff);\n\t\t\t(*ops->vdev_barwrite)(ctx, vcpu, pdi, bidx, offset + 4,\n\t\t\t\t\t 4, *val >> 32);\n\t\t} else {\n\t\t\t(*ops->vdev_barwrite)(ctx, vcpu, pdi, bidx, offset,\n\t\t\t\t\t size, bar_value(size, *val));\n\t\t}\n\t} else {\n\t\tif (size == 8) {\n\t\t\tuint64_t val_lo, val_hi;\n\n\t\t\tval_lo = (*ops->vdev_barread)(ctx, vcpu, pdi, bidx,\n\t\t\t offset, 4);\n\t\t\tval_lo = bar_value(4, val_lo);\n\n\t\t\tval_hi = (*ops->vdev_barread)(ctx, vcpu, pdi, bidx,\n\t\t\t offset + 4, 4);\n\n\t\t\t*val = val_lo | (val_hi << 32);\n\t\t} else {\n\t\t\t*val = (*ops->vdev_barread)(ctx, vcpu, pdi, bidx,\n\t\t\t offset, size);\n\t\t\t*val = bar_value(size, *val);\n\t\t}\n\t}\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-617", "cwe_name": "Reachable Assertion", "description": "The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.", "url": "https://cwe.mitre.org/data/definitions/617.html", "label_name": "vulnerable"} {"code": "update_bar_address(struct vmctx *ctx, struct pci_vdev *dev, uint64_t addr,\n\tint idx, int type, bool ignore_reg_unreg)\n{\n\tbool decode = false;\n\tuint64_t orig_addr = dev->bar[idx].addr;\n\n\tif (!ignore_reg_unreg) {\n\t\tif (dev->bar[idx].type == PCIBAR_IO)\n\t\t\tdecode = porten(dev);\n\t\telse\n\t\t\tdecode = memen(dev);\n\t}\n\n\tif (decode)\n\t\tunregister_bar(dev, idx);\n\n\tswitch (type) {\n\tcase PCIBAR_IO:\n\tcase PCIBAR_MEM32:\n\t\tdev->bar[idx].addr = addr;\n\t\tbreak;\n\tcase PCIBAR_MEM64:\n\t\tdev->bar[idx].addr &= ~0xffffffffUL;\n\t\tdev->bar[idx].addr |= addr;\n\t\tbreak;\n\tcase PCIBAR_MEMHI64:\n\t\tdev->bar[idx].addr &= 0xffffffff;\n\t\tdev->bar[idx].addr |= addr;\n\t\tbreak;\n\tdefault:\n\t\tassert(0);\n\t}\n\n\tif (decode)\n\t\tregister_bar(dev, idx);\n\n\t/* update bar mapping */\n\tif (dev->dev_ops->vdev_update_bar_map && decode)\n\t\tdev->dev_ops->vdev_update_bar_map(ctx, dev, idx, orig_addr);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-617", "cwe_name": "Reachable Assertion", "description": "The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.", "url": "https://cwe.mitre.org/data/definitions/617.html", "label_name": "vulnerable"} {"code": "Ta3Tokenizer_FindEncodingFilename(int fd, PyObject *filename)\n{\n struct tok_state *tok;\n FILE *fp;\n char *p_start =NULL , *p_end =NULL , *encoding = NULL;\n\n#ifndef PGEN\n#if PY_MINOR_VERSION >= 4\n fd = _Py_dup(fd);\n#endif\n#else\n fd = dup(fd);\n#endif\n if (fd < 0) {\n return NULL;\n }\n\n fp = fdopen(fd, \"r\");\n if (fp == NULL) {\n return NULL;\n }\n tok = Ta3Tokenizer_FromFile(fp, NULL, NULL, NULL);\n if (tok == NULL) {\n fclose(fp);\n return NULL;\n }\n#ifndef PGEN\n if (filename != NULL) {\n Py_INCREF(filename);\n tok->filename = filename;\n }\n else {\n tok->filename = PyUnicode_FromString(\"\");\n if (tok->filename == NULL) {\n fclose(fp);\n Ta3Tokenizer_Free(tok);\n return encoding;\n }\n }\n#endif\n while (tok->lineno < 2 && tok->done == E_OK) {\n Ta3Tokenizer_Get(tok, &p_start, &p_end);\n }\n fclose(fp);\n if (tok->encoding) {\n encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1);\n if (encoding)\n strcpy(encoding, tok->encoding);\n }\n Ta3Tokenizer_Free(tok);\n return encoding;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "fp_readl(char *s, int size, struct tok_state *tok)\n{\n PyObject* bufobj;\n const char *buf;\n Py_ssize_t buflen;\n\n /* Ask for one less byte so we can terminate it */\n assert(size > 0);\n size--;\n\n if (tok->decoding_buffer) {\n bufobj = tok->decoding_buffer;\n Py_INCREF(bufobj);\n }\n else\n {\n bufobj = PyObject_CallObject(tok->decoding_readline, NULL);\n if (bufobj == NULL)\n goto error;\n }\n if (PyUnicode_CheckExact(bufobj))\n {\n buf = PyUnicode_AsUTF8AndSize(bufobj, &buflen);\n if (buf == NULL) {\n goto error;\n }\n }\n else\n {\n buf = PyByteArray_AsString(bufobj);\n if (buf == NULL) {\n goto error;\n }\n buflen = PyByteArray_GET_SIZE(bufobj);\n }\n\n Py_XDECREF(tok->decoding_buffer);\n if (buflen > size) {\n /* Too many chars, the rest goes into tok->decoding_buffer */\n tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size,\n buflen-size);\n if (tok->decoding_buffer == NULL)\n goto error;\n buflen = size;\n }\n else\n tok->decoding_buffer = NULL;\n\n memcpy(s, buf, buflen);\n s[buflen] = '\\0';\n if (buflen == 0) /* EOF */\n s = NULL;\n Py_DECREF(bufobj);\n return s;\n\nerror:\n Py_XDECREF(bufobj);\n return error_ret(tok);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "num_stmts(const node *n)\n{\n int i, l;\n node *ch;\n\n switch (TYPE(n)) {\n case single_input:\n if (TYPE(CHILD(n, 0)) == NEWLINE)\n return 0;\n else\n return num_stmts(CHILD(n, 0));\n case file_input:\n l = 0;\n for (i = 0; i < NCH(n); i++) {\n ch = CHILD(n, i);\n if (TYPE(ch) == stmt)\n l += num_stmts(ch);\n }\n return l;\n case stmt:\n return num_stmts(CHILD(n, 0));\n case compound_stmt:\n return 1;\n case simple_stmt:\n return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */\n case suite:\n /* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */\n if (NCH(n) == 1)\n return num_stmts(CHILD(n, 0));\n else {\n i = 2;\n l = 0;\n if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)\n i += 2;\n for (; i < (NCH(n) - 1); i++)\n l += num_stmts(CHILD(n, i));\n return l;\n }\n default: {\n char buf[128];\n\n sprintf(buf, \"Non-statement found: %d %d\",\n TYPE(n), NCH(n));\n Py_FatalError(buf);\n }\n }\n assert(0);\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "decode_bytes_with_escapes(struct compiling *c, const node *n, const char *s,\n size_t len)\n{\n return PyBytes_DecodeEscape(s, len, NULL, 0, NULL);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "choose_windows(s)\nconst char *s;\n{\n register int i;\n\n for (i = 0; winchoices[i].procs; i++) {\n if ('+' == winchoices[i].procs->name[0])\n continue;\n if ('-' == winchoices[i].procs->name[0])\n continue;\n if (!strcmpi(s, winchoices[i].procs->name)) {\n windowprocs = *winchoices[i].procs;\n\n if (last_winchoice && last_winchoice->ini_routine)\n (*last_winchoice->ini_routine)(WININIT_UNDO);\n if (winchoices[i].ini_routine)\n (*winchoices[i].ini_routine)(WININIT);\n last_winchoice = &winchoices[i];\n return;\n }\n }\n\n if (!windowprocs.win_raw_print)\n windowprocs.win_raw_print = def_raw_print;\n if (!windowprocs.win_wait_synch)\n /* early config file error processing routines call this */\n windowprocs.win_wait_synch = def_wait_synch;\n\n if (!winchoices[0].procs) {\n raw_printf(\"No window types?\");\n nh_terminate(EXIT_FAILURE);\n }\n if (!winchoices[1].procs) {\n config_error_add(\n \"Window type %s not recognized. The only choice is: %s\",\n s, winchoices[0].procs->name);\n } else {\n char buf[BUFSZ];\n boolean first = TRUE;\n\n buf[0] = '\\0';\n for (i = 0; winchoices[i].procs; i++) {\n if ('+' == winchoices[i].procs->name[0])\n continue;\n if ('-' == winchoices[i].procs->name[0])\n continue;\n Sprintf(eos(buf), \"%s%s\",\n first ? \"\" : \", \", winchoices[i].procs->name);\n first = FALSE;\n }\n config_error_add(\"Window type %s not recognized. Choices are: %s\",\n s, buf);\n }\n\n if (windowprocs.win_raw_print == def_raw_print\n || WINDOWPORT(\"safe-startup\"))\n nh_terminate(EXIT_SUCCESS);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "escapes(cp, tp)\nconst char\t*cp;\nchar *tp;\n{\n while (*cp) {\n\tint\tcval = 0, meta = 0;\n\n\tif (*cp == '\\\\' && cp[1] && index(\"mM\", cp[1]) && cp[2]) {\n\t\tmeta = 1;\n\t\tcp += 2;\n\t}\n\tif (*cp == '\\\\' && cp[1] && index(\"0123456789xXoO\", cp[1]) && cp[2]) {\n\t NEARDATA const char hex[] = \"00112233445566778899aAbBcCdDeEfF\";\n\t const char *dp;\n\t int dcount = 0;\n\n\t cp++;\n\t if (*cp == 'x' || *cp == 'X')\n\t\tfor (++cp; *cp && (dp = index(hex, *cp)) && (dcount++ < 2); cp++)\n\t\t cval = (cval * 16) + ((int)(dp - hex) / 2);\n\t else if (*cp == 'o' || *cp == 'O')\n\t\tfor (++cp; *cp && (index(\"01234567\",*cp)) && (dcount++ < 3); cp++)\n\t\t cval = (cval * 8) + (*cp - '0');\n\t else\n\t\tfor (; *cp && (index(\"0123456789\",*cp)) && (dcount++ < 3); cp++)\n\t\t cval = (cval * 10) + (*cp - '0');\n\t} else if (*cp == '\\\\' && cp[1]) {\t/* C-style character escapes */\n\t switch (*++cp) {\n\t case '\\\\': cval = '\\\\'; break;\n\t case 'n': cval = '\\n'; break;\n\t case 't': cval = '\\t'; break;\n\t case 'b': cval = '\\b'; break;\n\t case 'r': cval = '\\r'; break;\n\t default: cval = *cp;\n\t }\n\t cp++;\n\t} else if (*cp == '^' && cp[1]) { /* expand control-character syntax */\n\t cval = (*++cp & 0x1f);\n\t cp++;\n\t} else\n\t cval = *cp++;\n\n\tif (meta)\n\t cval |= 0x80;\n\t*tp++ = cval;\n }\n *tp = '\\0';\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-269", "cwe_name": "Improper Privilege Management", "description": "The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.", "url": "https://cwe.mitre.org/data/definitions/269.html", "label_name": "vulnerable"} {"code": "int secure_decrypt(void *data, unsigned int data_length, int is_signed)\n{\n\tat91_aes_key_size_t key_size;\n\tunsigned int cmac_key[8], cipher_key[8];\n\tunsigned int iv[AT91_AES_IV_SIZE_WORD];\n\tunsigned int computed_cmac[AT91_AES_BLOCK_SIZE_WORD];\n\tunsigned int fixed_length;\n\tconst unsigned int *cmac;\n\tint rc = -1;\n\n\t/* Init keys */\n\tinit_keys(&key_size, cipher_key, cmac_key, iv);\n\n\t/* Init periph */\n\tat91_aes_init();\n\n\t/* Check signature if required */\n\tif (is_signed) {\n\t\t/* Compute the CMAC */\n\t\tif (at91_aes_cmac(data_length, data, computed_cmac,\n\t\t\t\t key_size, cmac_key))\n\t\t\tgoto exit;\n\n\t\t/* Check the CMAC */\n\t\tfixed_length = at91_aes_roundup(data_length);\n\t\tcmac = (const unsigned int *)((char *)data + fixed_length);\n\t\tif (!consttime_memequal(cmac, computed_cmac, AT91_AES_BLOCK_SIZE_BYTE))\n\t\t\tgoto exit;\n\t}\n\n\t/* Decrypt the whole file */\n\tif (at91_aes_cbc(data_length, data, data, 0,\n\t\t\t key_size, cipher_key, iv))\n\t\tgoto exit;\n\n\trc = 0;\nexit:\n\t/* Reset periph */\n\tat91_aes_cleanup();\n\n\t/* Reset keys */\n\tmemset(cmac_key, 0, sizeof(cmac_key));\n\tmemset(cipher_key, 0, sizeof(cipher_key));\n\tmemset(iv, 0, sizeof(iv));\n\n\treturn rc;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-212", "cwe_name": "Improper Removal of Sensitive Information Before Storage or Transfer", "description": "The product stores, transfers, or shares a resource that contains sensitive information, but it does not properly remove that information before the product makes the resource available to unauthorized actors.", "url": "https://cwe.mitre.org/data/definitions/212.html", "label_name": "vulnerable"} {"code": "int mongo_env_read_socket( mongo *conn, void *buf, int len ) {\n char *cbuf = buf;\n\n while ( len ) {\n int sent = recv( conn->sock, cbuf, len, 0 );\n if ( sent == 0 || sent == -1 ) {\n __mongo_set_error( conn, MONGO_IO_ERROR, NULL, WSAGetLastError() );\n return MONGO_ERROR;\n }\n cbuf += sent;\n len -= sent;\n }\n\n return MONGO_OK;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "snmp_ber_encode_type(unsigned char *out, uint32_t *out_len, uint8_t type)\n{\n *out-- = type;\n (*out_len)++;\n return out;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "snmp_ber_decode_integer(unsigned char *buf, uint32_t *buff_len, uint32_t *num)\n{\n uint8_t i, len, type;\n\n buf = snmp_ber_decode_type(buf, buff_len, &type);\n\n if(buf == NULL || type != BER_DATA_TYPE_INTEGER) {\n /*\n * Sanity check\n * Invalid type in buffer\n */\n return NULL;\n }\n\n buf = snmp_ber_decode_length(buf, buff_len, &len);\n\n if(buf == NULL || len > 4) {\n /*\n * Sanity check\n * It will not fit in the uint32_t\n */\n return NULL;\n }\n\n if(*buff_len < len) {\n return NULL;\n }\n\n *num = (uint32_t)(*buf++ & 0xFF);\n (*buff_len)--;\n for(i = 1; i < len; ++i) {\n *num <<= 8;\n *num |= (uint8_t)(*buf++ & 0xFF);\n (*buff_len)--;\n }\n\n return buf;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "PJ_DEF(pj_status_t) pjsip_endpt_send_response( pjsip_endpoint *endpt,\n\t\t\t\t\t pjsip_response_addr *res_addr,\n\t\t\t\t\t pjsip_tx_data *tdata,\n\t\t\t\t\t void *token,\n\t\t\t\t\t pjsip_send_callback cb)\n{\n /* Determine which transports and addresses to send the response,\n * based on Section 18.2.2 of RFC 3261.\n */\n pjsip_send_state *send_state;\n pj_status_t status;\n\n /* Create structure to keep the sending state. */\n send_state = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_send_state);\n send_state->endpt = endpt;\n send_state->tdata = tdata;\n send_state->token = token;\n send_state->app_cb = cb;\n\n if (res_addr->transport != NULL) {\n\tsend_state->cur_transport = res_addr->transport;\n\tpjsip_transport_add_ref(send_state->cur_transport);\n\n\tstatus = pjsip_transport_send( send_state->cur_transport, tdata, \n\t\t\t\t &res_addr->addr,\n\t\t\t\t res_addr->addr_len,\n\t\t\t\t send_state,\n\t\t\t\t &send_response_transport_cb );\n\tif (status == PJ_SUCCESS) {\n\t pj_ssize_t sent = tdata->buf.cur - tdata->buf.start;\n\t send_response_transport_cb(send_state, tdata, sent);\n\t return PJ_SUCCESS;\n\t} else if (status == PJ_EPENDING) {\n\t /* Callback will be called later. */\n\t return PJ_SUCCESS;\n\t} else {\n\t pjsip_transport_dec_ref(send_state->cur_transport);\n\t return status;\n\t}\n } else {\n\t/* Copy the destination host name to TX data */\n\tpj_strdup(tdata->pool, &tdata->dest_info.name, \n\t\t &res_addr->dst_host.addr.host);\n\n\tpjsip_endpt_resolve(endpt, tdata->pool, &res_addr->dst_host, \n\t\t\t send_state, &send_response_resolver_cb);\n\treturn PJ_SUCCESS;\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-297", "cwe_name": "Improper Validation of Certificate with Host Mismatch", "description": "The software communicates with a host that provides a certificate, but the software does not properly ensure that the certificate is actually associated with that host.", "url": "https://cwe.mitre.org/data/definitions/297.html", "label_name": "vulnerable"} {"code": "static pj_status_t STATUS_FROM_SSL_ERR(char *action, pj_ssl_sock_t *ssock,\n\t\t\t\t unsigned long err)\n{\n int level = 0;\n int len = 0; //dummy\n\n ERROR_LOG(\"STATUS_FROM_SSL_ERR\", err, ssock);\n level++;\n\n /* General SSL error, dig more from OpenSSL error queue */\n if (err == SSL_ERROR_SSL) {\n\terr = ERR_get_error();\n\tERROR_LOG(\"STATUS_FROM_SSL_ERR\", err, ssock);\n }\n\n ssock->last_err = err;\n return GET_STATUS_FROM_SSL_ERR(err);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_rpsi(\n\t\t\t\t\tconst void *buf,\n\t\t\t\t\tpj_size_t length,\n\t\t\t\t\tpjmedia_rtcp_fb_rpsi *rpsi)\n{\n pjmedia_rtcp_common *hdr = (pjmedia_rtcp_common*) buf;\n pj_uint8_t *p;\n pj_uint8_t padlen;\n pj_size_t rpsi_len;\n\n PJ_ASSERT_RETURN(buf && rpsi, PJ_EINVAL);\n PJ_ASSERT_RETURN(length >= sizeof(pjmedia_rtcp_common), PJ_ETOOSMALL);\n\n /* RPSI uses pt==RTCP_PSFB and FMT==3 */\n if (hdr->pt != RTCP_PSFB || hdr->count != 3)\n\treturn PJ_ENOTFOUND;\n\n rpsi_len = (pj_ntohs((pj_uint16_t)hdr->length)-2) * 4;\n if (length < rpsi_len + 12)\n\treturn PJ_ETOOSMALL;\n\n p = (pj_uint8_t*)hdr + sizeof(*hdr);\n padlen = *p++;\n rpsi->pt = (*p++ & 0x7F);\n rpsi->rpsi_bit_len = rpsi_len*8 - 16 - padlen;\n pj_strset(&rpsi->rpsi, (char*)p, (rpsi->rpsi_bit_len + 7)/8);\n\n return PJ_SUCCESS;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "void luaT_adjustvarargs (lua_State *L, int nfixparams, CallInfo *ci,\n const Proto *p) {\n int i;\n int actual = cast_int(L->top - ci->func) - 1; /* number of arguments */\n int nextra = actual - nfixparams; /* number of extra arguments */\n ci->u.l.nextraargs = nextra;\n checkstackGC(L, p->maxstacksize + 1);\n /* copy function to the top of the stack */\n setobjs2s(L, L->top++, ci->func);\n /* move fixed parameters to the top of the stack */\n for (i = 1; i <= nfixparams; i++) {\n setobjs2s(L, L->top++, ci->func + i);\n setnilvalue(s2v(ci->func + i)); /* erase original parameter (for GC) */\n }\n ci->func += actual + 1;\n ci->top += actual + 1;\n lua_assert(L->top <= ci->top && ci->top <= L->stack_last);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted) {\n int i;\n int nextra = ci->u.l.nextraargs;\n if (wanted < 0) {\n wanted = nextra; /* get all extra arguments available */\n checkstackp(L, nextra, where); /* ensure stack space */\n L->top = where + nextra; /* next instruction will need top */\n }\n for (i = 0; i < wanted && i < nextra; i++)\n setobjs2s(L, where + i, ci->func - nextra + i);\n for (; i < wanted; i++) /* complete required results with nil */\n setnilvalue(s2v(where + i));\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted) {\n int i;\n int nextra = ci->u.l.nextraargs;\n if (wanted < 0) {\n wanted = nextra; /* get all extra arguments available */\n checkstackp(L, nextra, where); /* ensure stack space */\n L->top = where + nextra; /* next instruction will need top */\n }\n for (i = 0; i < wanted && i < nextra; i++)\n setobjs2s(L, where + i, ci->func - nextra + i);\n for (; i < wanted; i++) /* complete required results with nil */\n setnilvalue(s2v(where + i));\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "int luaG_traceexec (lua_State *L, const Instruction *pc) {\n CallInfo *ci = L->ci;\n lu_byte mask = L->hookmask;\n int counthook;\n if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */\n ci->u.l.trap = 0; /* don't need to stop again */\n return 0; /* turn off 'trap' */\n }\n pc++; /* reference is always next instruction */\n ci->u.l.savedpc = pc; /* save 'pc' */\n counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT));\n if (counthook)\n resethookcount(L); /* reset count */\n else if (!(mask & LUA_MASKLINE))\n return 1; /* no line hook and count != 0; nothing to be done now */\n if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */\n ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */\n return 1; /* do not call hook again (VM yielded, so it did not move) */\n }\n if (!isIT(*(ci->u.l.savedpc - 1)))\n L->top = ci->top; /* prepare top */\n if (counthook)\n luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */\n if (mask & LUA_MASKLINE) {\n const Proto *p = ci_func(ci)->p;\n int npci = pcRel(pc, p);\n if (npci == 0 || /* call linehook when enter a new function, */\n pc <= L->oldpc || /* when jump back (loop), or when */\n changedline(p, pcRel(L->oldpc, p), npci)) { /* enter new line */\n int newline = luaG_getfuncline(p, npci);\n luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */\n }\n L->oldpc = pc; /* 'pc' of last call to line hook */\n }\n if (L->status == LUA_YIELD) { /* did hook yield? */\n if (counthook)\n L->hookcount = 1; /* undo decrement to zero */\n ci->u.l.savedpc--; /* undo increment (resume will increment it again) */\n ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */\n luaD_throw(L, LUA_YIELD);\n }\n return 1; /* keep 'trap' on */\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) {\n if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) \n return Jsi_LogError(\"expected array\");\n Jsi_RC rc = JSI_OK;\n int curlen, i;\n Jsi_Obj *obj;\n Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1);\n\n func = Jsi_ValueArrayIndex(interp, args, 0);\n if (!Jsi_ValueIsFunction(interp, func)) \n return Jsi_LogError(\"expected function\");\n\n Jsi_Value *nrPtr = Jsi_ValueNew1(interp);\n obj = _this->d.obj;\n curlen = Jsi_ObjGetLength(interp, obj); \n if (curlen < 0)\n Jsi_ObjSetLength(interp, obj, 0);\n Jsi_ObjListifyArray(interp, obj);\n Jsi_Value *vobjs[4];\n int n, rev = (op==2);\n Jsi_Func *fptr = func->d.obj->d.fobj->func;\n int maa = (fptr->argnames?fptr->argnames->argCnt:0);\n if (maa>4)\n maa = 4;\n\n for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) {\n if (!obj->arr[i]) continue;\n if (n==0 && !ini) {\n ini = obj->arr[i];\n continue;\n }\n \n vobjs[0] = ini;\n vobjs[1] = obj->arr[i];\n vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL);\n vobjs[3] = _this;\n vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0));\n Jsi_IncrRefCount(interp, vpargs);\n rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL);\n Jsi_DecrRefCount(interp, vpargs);\n if (rc != JSI_OK)\n break;\n ini = nrPtr;\n }\n if (rc == JSI_OK && ini)\n Jsi_ValueCopy(interp, *ret, ini); \n Jsi_DecrRefCount(interp, nrPtr);\n return rc;\n\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,\n Jsi_Value **ret, Jsi_Func *funcPtr)\n{\n if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) {\n Jsi_ValueMakeNumber(interp, ret, 0);\n return JSI_OK;\n }\n Jsi_Value *v;\n Jsi_Obj *obj;\n obj = _this->d.obj;\n int i = Jsi_ObjGetLength(interp, obj) - 1;\n\n if (i < 0) {\n Jsi_ValueMakeUndef(interp, ret);\n return JSI_OK;\n }\n \n if (obj->arr) {\n if ((v = obj->arr[i])) {\n obj->arr[i] = NULL;\n obj->arrCnt--;\n }\n } else {\n v = Jsi_ValueArrayIndex(interp, _this, i);\n }\n if (v) {\n Jsi_DecrRefCount(interp, *ret);\n *ret = v;\n }\n Jsi_ObjSetLength(interp, obj, i);\n return JSI_OK;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static Jsi_RC SysGetEnvCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,\n Jsi_Value **ret, Jsi_Func *funcPtr)\n{\n extern char **environ;\n char *cp;\n int i;\n if (interp->isSafe)\n return Jsi_LogError(\"no getenv in safe mode\");\n Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);\n if (v != NULL) {\n const char *fnam = Jsi_ValueString(interp, v, NULL);\n if (!fnam) \n return Jsi_LogError(\"arg1: expected string 'name'\");\n cp = getenv(fnam);\n if (cp != NULL) {\n Jsi_ValueMakeStringDup(interp, ret, cp);\n }\n return JSI_OK;\n }\n /* Single object containing result members. */\n Jsi_Value *vres;\n Jsi_Obj *ores = Jsi_ObjNew(interp);\n Jsi_Value *nnv;\n char *val, nam[200];\n //Jsi_ObjIncrRefCount(interp, ores);\n vres = Jsi_ValueMakeObject(interp, NULL, ores);\n //Jsi_IncrRefCount(interp, vres);\n \n for (i=0; ; i++) {\n int n;\n cp = environ[i];\n if (cp == 0 || ((val = Jsi_Strchr(cp, '='))==NULL))\n break;\n n = val-cp+1;\n if (n>=(int)sizeof(nam))\n n = sizeof(nam)-1;\n Jsi_Strncpy(nam, cp, n);\n val = val+1;\n nnv = Jsi_ValueMakeStringDup(interp, NULL, val);\n Jsi_ObjInsert(interp, ores, nam, nnv, 0);\n }\n Jsi_ValueReplace(interp, ret, vres);\n return JSI_OK;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "const char *jsi_GetHomeDir(Jsi_Interp *interp) {\n const char *str = NULL;\n if (interp->homeDir)\n return interp->homeDir;\n#ifdef __WIN32\n str = getenv(\"USERPROFILE\"); /* TODO: windows home dir. */\n#else\n \n if ((str = getenv(\"HOME\")) == NULL) {\n struct passwd pwd, *pw;\n char buf[20000];\n if (getpwuid_r(getuid(), &pwd, buf, sizeof(buf), &pw) == 0 && pw->pw_dir) \n str = pw->pw_dir;\n }\n#endif\n if (!str) {\n Jsi_LogBug(\"no home dir\");\n str = \"/\";\n }\n#ifdef JSI_LITE_ONLY\n return str;\n#else\n return (interp->homeDir = Jsi_KeyAdd(interp, str));\n#endif\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "static Jsi_Value *jsi_hashFmtKey(Jsi_MapEntry* h, struct Jsi_MapOpts *opts, int flags)\n{\n Jsi_HashEntry* hPtr = (Jsi_HashEntry*)h;\n void *key = Jsi_HashKeyGet(hPtr);\n if (opts->keyType == JSI_KEYS_ONEWORD)\n return Jsi_ValueNewNumber(opts->interp, (Jsi_Number)(intptr_t)key);\n char nbuf[100];\n snprintf(nbuf, sizeof(nbuf), \"%p\", key);\n return Jsi_ValueNewStringDup(opts->interp, nbuf);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "static void dbEvalSetColumnJSON(DbEvalContext *p, int iCol, Jsi_DString *dStr) {\n Jsi_Interp *interp = p->jdb->interp;\n char nbuf[200];\n\n sqlite3_stmt *pStmt = p->pPreStmt->pStmt;\n\n switch( sqlite3_column_type(pStmt, iCol) ) {\n case SQLITE_BLOB: {\n int bytes = sqlite3_column_bytes(pStmt, iCol);\n const char *zBlob = (char*)sqlite3_column_blob(pStmt, iCol);\n if( !zBlob ) {\n Jsi_DSAppend(dStr, \"null\", NULL);\n return;\n }\n Jsi_JSONQuote(interp, zBlob, bytes, dStr);\n return;\n }\n case SQLITE_INTEGER: {\n sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);\n if (v==0 || v==1) {\n const char *dectyp = sqlite3_column_decltype(pStmt, iCol);\n if (dectyp && !Jsi_Strncasecmp(dectyp,\"bool\", 4)) {\n Jsi_DSAppend(dStr, (v?\"true\":\"false\"), NULL);\n return;\n }\n }\n#ifdef __WIN32\n snprintf(nbuf, sizeof(nbuf), \"%\" PRId64, (Jsi_Wide)v);\n#else\n snprintf(nbuf, sizeof(nbuf), \"%lld\", v);\n#endif\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case SQLITE_FLOAT: {\n Jsi_NumberToString(interp, sqlite3_column_double(pStmt, iCol), nbuf, sizeof(nbuf));\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case SQLITE_NULL: {\n Jsi_DSAppend(dStr, \"null\", NULL);\n return;\n }\n }\n const char *str = (char*)sqlite3_column_text(pStmt, iCol );\n if (!str)\n str = p->jdb->optPtr->nullvalue;\n Jsi_JSONQuote(interp, str?str:\"\", -1, dStr);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-120", "cwe_name": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')", "description": "The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.", "url": "https://cwe.mitre.org/data/definitions/120.html", "label_name": "vulnerable"} {"code": "void init_xml_schema()\n{\n VALUE nokogiri = rb_define_module(\"Nokogiri\");\n VALUE xml = rb_define_module_under(nokogiri, \"XML\");\n VALUE klass = rb_define_class_under(xml, \"Schema\", rb_cObject);\n\n cNokogiriXmlSchema = klass;\n\n rb_define_singleton_method(klass, \"read_memory\", read_memory, 1);\n rb_define_singleton_method(klass, \"from_document\", from_document, 1);\n\n rb_define_private_method(klass, \"validate_document\", validate_document, 1);\n rb_define_private_method(klass, \"validate_file\", validate_file, 1);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": "static LUA_FUNCTION(openssl_x509_check_email)\n{\n X509 * cert = CHECK_OBJECT(1, X509, \"openssl.x509\");\n if (lua_isstring(L, 2))\n {\n const char *email = lua_tostring(L, 2);\n lua_pushboolean(L, X509_check_email(cert, email, strlen(email), 0));\n }\n else\n {\n lua_pushboolean(L, 0);\n }\n return 1;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": "NOEXPORT int init_section(int eof, SERVICE_OPTIONS **section_ptr) {\n char *errstr;\n\n#ifndef USE_WIN32\n (*section_ptr)->option.log_stderr=new_global_options.option.log_stderr;\n#endif /* USE_WIN32 */\n\n if(*section_ptr==&new_service_options) {\n /* end of global options or inetd mode -> initialize globals */\n errstr=parse_global_option(CMD_INITIALIZE, NULL, NULL);\n if(errstr) {\n s_log(LOG_ERR, \"Global options: %s\", errstr);\n return 1;\n }\n }\n\n if(*section_ptr!=&new_service_options || eof) {\n /* end service section or inetd mode -> initialize service */\n if(*section_ptr==&new_service_options)\n s_log(LOG_INFO, \"Initializing inetd mode configuration\");\n else\n s_log(LOG_INFO, \"Initializing service [%s]\",\n (*section_ptr)->servname);\n errstr=parse_service_option(CMD_INITIALIZE, section_ptr, NULL, NULL);\n if(errstr) {\n if(*section_ptr==&new_service_options)\n s_log(LOG_ERR, \"Inetd mode: %s\", errstr);\n else\n s_log(LOG_ERR, \"Service [%s]: %s\",\n (*section_ptr)->servname, errstr);\n return 1;\n }\n }\n return 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": "NOEXPORT void reload_config() {\n static int delay=10; /* 10ms */\n#ifdef HAVE_CHROOT\n struct stat sb;\n#endif /* HAVE_CHROOT */\n\n if(options_parse(CONF_RELOAD)) {\n s_log(LOG_ERR, \"Failed to reload the configuration file\");\n return;\n }\n unbind_ports();\n log_flush(LOG_MODE_BUFFER);\n#ifdef HAVE_CHROOT\n /* we don't close SINK_SYSLOG if chroot is enabled and\n * there is no /dev/log inside it, which could allow\n * openlog(3) to reopen the syslog socket later */\n if(global_options.chroot_dir && stat(\"/dev/log\", &sb))\n log_close(SINK_OUTFILE);\n else\n#endif /* HAVE_CHROOT */\n log_close(SINK_SYSLOG|SINK_OUTFILE);\n /* there is no race condition here:\n * client threads are not allowed to use global options */\n options_free();\n options_apply();\n /* we hope that a sane openlog(3) implementation won't\n * attempt to reopen /dev/log if it's already open */\n log_open(SINK_SYSLOG|SINK_OUTFILE);\n log_flush(LOG_MODE_CONFIGURED);\n ui_config_reloaded();\n /* we use \"|\" instead of \"||\" to attempt initialization of both subsystems */\n if(bind_ports() | exec_connect_start()) {\n s_poll_sleep(delay/1000, delay%1000); /* sleep to avoid log trashing */\n signal_post(SIGNAL_RELOAD_CONFIG); /* retry */\n delay*=2;\n if(delay > 10000) /* 10s */\n delay=10000;\n } else {\n delay=10; /* 10ms */\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": "file_rlookup(const char *filename)\t/* I - Filename */\n{\n int\t\ti;\t\t\t/* Looping var */\n cache_t\t*wc;\t\t\t/* Current cache file */\n\n\n for (i = web_files, wc = web_cache; i > 0; i --, wc ++)\n if (!strcmp(wc->name, filename))\n return (wc->url);\n\n return (filename);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "image_load_jpeg(image_t *img,\t/* I - Image pointer */\n FILE *fp,\t/* I - File to load from */\n int gray,\t/* I - 0 = color, 1 = grayscale */\n int load_data)/* I - 1 = load image data, 0 = just info */\n{\n struct jpeg_decompress_struct\tcinfo;\t\t/* Decompressor info */\n struct jpeg_error_mgr\t\tjerr;\t\t/* Error handler info */\n JSAMPROW\t\t\trow;\t\t/* Sample row pointer */\n\n\n jpeg_std_error(&jerr);\n jerr.error_exit = jpeg_error_handler;\n\n cinfo.err = &jerr;\n jpeg_create_decompress(&cinfo);\n jpeg_stdio_src(&cinfo, fp);\n jpeg_read_header(&cinfo, (boolean)1);\n\n cinfo.quantize_colors = FALSE;\n\n if (gray || cinfo.num_components == 1)\n {\n cinfo.out_color_space = JCS_GRAYSCALE;\n cinfo.out_color_components = 1;\n cinfo.output_components = 1;\n }\n else if (cinfo.num_components != 3)\n {\n jpeg_destroy_decompress(&cinfo);\n\n progress_error(HD_ERROR_BAD_FORMAT,\n \"CMYK JPEG files are not supported! (%s)\",\n\t\t file_rlookup(img->filename));\n return (-1);\n }\n else\n {\n cinfo.out_color_space = JCS_RGB;\n cinfo.out_color_components = 3;\n cinfo.output_components = 3;\n }\n\n jpeg_calc_output_dimensions(&cinfo);\n\n img->width = (int)cinfo.output_width;\n img->height = (int)cinfo.output_height;\n img->depth = (int)cinfo.output_components;\n\n if (!load_data)\n {\n jpeg_destroy_decompress(&cinfo);\n return (0);\n }\n\n img->pixels = (uchar *)malloc((size_t)(img->width * img->height * img->depth));\n\n if (img->pixels == NULL)\n {\n jpeg_destroy_decompress(&cinfo);\n return (-1);\n }\n\n jpeg_start_decompress(&cinfo);\n\n while (cinfo.output_scanline < cinfo.output_height)\n {\n row = (JSAMPROW)(img->pixels + (size_t)cinfo.output_scanline * (size_t)cinfo.output_width * (size_t)cinfo.output_components);\n jpeg_read_scanlines(&cinfo, &row, (JDIMENSION)1);\n }\n\n jpeg_finish_decompress(&cinfo);\n jpeg_destroy_decompress(&cinfo);\n\n return (0);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "uint16_t enc624j600ReadPhyReg(NetInterface *interface, uint8_t address)\n{\n //Write the address of the PHY register to read from\n enc624j600WriteReg(interface, ENC624J600_REG_MIREGADR, MIREGADR_R8 | address);\n //Start read operation\n enc624j600WriteReg(interface, ENC624J600_REG_MICMD, MICMD_MIIRD);\n\n //Wait at least 25.6us before polling the BUSY bit\n usleep(100);\n //Wait for the read operation to complete\n while((enc624j600ReadReg(interface, ENC624J600_REG_MISTAT) & MISTAT_BUSY) != 0)\n {\n }\n\n //Clear command register\n enc624j600WriteReg(interface, ENC624J600_REG_MICMD, 0x00);\n\n //Return register contents\n return enc624j600ReadReg(interface, ENC624J600_REG_MIRD);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "error_t ksz8851SendPacket(NetInterface *interface,\n const NetBuffer *buffer, size_t offset, NetTxAncillary *ancillary)\n{\n size_t n;\n size_t length;\n Ksz8851TxHeader header;\n Ksz8851Context *context;\n\n //Point to the driver context\n context = (Ksz8851Context *) interface->nicContext;\n\n //Retrieve the length of the packet\n length = netBufferGetLength(buffer) - offset;\n\n //Check the frame length\n if(length > ETH_MAX_FRAME_SIZE)\n {\n //The transmitter can accept another packet\n osSetEvent(&interface->nicTxEvent);\n //Report an error\n return ERROR_INVALID_LENGTH;\n }\n\n //Get the amount of free memory available in the TX FIFO\n n = ksz8851ReadReg(interface, KSZ8851_REG_TXMIR) & TXMIR_TXMA_MASK;\n\n //Make sure the TX FIFO is available for writing\n if(n < (length + 8))\n {\n return ERROR_FAILURE;\n }\n\n //Copy user data\n netBufferRead(context->txBuffer, buffer, offset, length);\n\n //Format control word\n header.controlWord = htole16(TX_CTRL_TXIC | (context->frameId++ & TX_CTRL_TXFID));\n //Total number of bytes to be transmitted\n header.byteCount = htole16(length);\n\n //Enable TXQ write access\n ksz8851SetBit(interface, KSZ8851_REG_RXQCR, RXQCR_SDA);\n //Write TX packet header\n ksz8851WriteFifo(interface, (uint8_t *) &header, sizeof(Ksz8851TxHeader));\n //Write data\n ksz8851WriteFifo(interface, context->txBuffer, length);\n //End TXQ write access\n ksz8851ClearBit(interface, KSZ8851_REG_RXQCR, RXQCR_SDA);\n\n //Start transmission\n ksz8851SetBit(interface, KSZ8851_REG_TXQCR, TXQCR_METFE);\n\n //Get the amount of free memory available in the TX FIFO\n n = ksz8851ReadReg(interface, KSZ8851_REG_TXMIR) & TXMIR_TXMA_MASK;\n\n //Check whether the TX FIFO is available for writing\n if(n >= (ETH_MAX_FRAME_SIZE + 8))\n {\n //The transmitter can accept another packet\n osSetEvent(&interface->nicTxEvent);\n }\n\n //Successful processing\n return NO_ERROR;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "error_t am335xEthAddVlanAddrEntry(uint_t port, uint_t vlanId, MacAddr *macAddr)\n{\n error_t error;\n uint_t index;\n Am335xAleEntry entry;\n\n //Ensure that there are no duplicate address entries in the ALE table\n index = am335xEthFindVlanAddrEntry(vlanId, macAddr);\n\n //No matching entry found?\n if(index >= CPSW_ALE_MAX_ENTRIES)\n {\n //Find a free entry in the ALE table\n index = am335xEthFindFreeEntry();\n }\n\n //Sanity check\n if(index < CPSW_ALE_MAX_ENTRIES)\n {\n //Set up a VLAN/address table entry\n entry.word2 = 0;\n entry.word1 = CPSW_ALE_WORD1_ENTRY_TYPE_VLAN_ADDR;\n entry.word0 = 0;\n\n //Multicast address?\n if(macIsMulticastAddr(macAddr))\n {\n //Set port mask\n entry.word2 |= CPSW_ALE_WORD2_SUPER |\n CPSW_ALE_WORD2_PORT_LIST(1 << port) |\n CPSW_ALE_WORD2_PORT_LIST(1 << CPSW_CH0);\n\n //Set multicast forward state\n entry.word1 |= CPSW_ALE_WORD1_MCAST_FWD_STATE(0);\n }\n\n //Set VLAN identifier\n entry.word1 |= CPSW_ALE_WORD1_VLAN_ID(vlanId);\n\n //Copy the upper 16 bits of the unicast address\n entry.word1 |= (macAddr->b[0] << 8) | macAddr->b[1];\n\n //Copy the lower 32 bits of the unicast address\n entry.word0 |= (macAddr->b[2] << 24) | (macAddr->b[3] << 16) |\n (macAddr->b[4] << 8) | macAddr->b[5];\n\n //Add a new entry to the ALE table\n am335xEthWriteEntry(index, &entry);\n\n //Sucessful processing\n error = NO_ERROR;\n }\n else\n {\n //The ALE table is full\n error = ERROR_FAILURE;\n }\n\n //Return status code\n return error;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "void lpc546xxEthDisableIrq(NetInterface *interface)\n{\n //Disable Ethernet MAC interrupts\n NVIC_DisableIRQ(ETHERNET_IRQn);\n\n //Valid Ethernet PHY or switch driver?\n if(interface->phyDriver != NULL)\n {\n //Disable Ethernet PHY interrupts\n interface->phyDriver->disableIrq(interface);\n }\n else if(interface->switchDriver != NULL)\n {\n //Disable Ethernet switch interrupts\n interface->switchDriver->disableIrq(interface);\n }\n else\n {\n //Just for sanity\n }\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "error_t httpCheckCharset(const char_t *s, size_t length, uint_t charset)\n{\n error_t error;\n size_t i;\n uint8_t c;\n uint_t m;\n\n //Initialize status code\n error = NO_ERROR;\n\n //Parse string\n for(i = 0; i < length; i++)\n {\n //Get current character\n c = (uint8_t) s[i];\n\n //Any 8-bit sequence of data\n m = HTTP_CHARSET_OCTET;\n\n //Check if character is a control character\n if(iscntrl(c))\n m |= HTTP_CHARSET_CTL;\n\n //Check if character is printable\n if(isprint(c) && c <= 126)\n m |= HTTP_CHARSET_TEXT | HTTP_CHARSET_VCHAR;\n\n //Check if character is blank\n if(c == ' ' || c == '\\t')\n m |= HTTP_CHARSET_TEXT | HTTP_CHARSET_LWS;\n\n //Check if character is alphabetic\n if(isalpha(c))\n m |= HTTP_CHARSET_TCHAR | HTTP_CHARSET_ALPHA;\n\n //Check if character is decimal digit\n if(osIsdigit(c))\n m |= HTTP_CHARSET_TCHAR | HTTP_CHARSET_DIGIT;\n\n //Check if character is hexadecimal digit\n if(isxdigit(c))\n m |= HTTP_CHARSET_HEX;\n\n //Check if character is in the extended character set\n if(c >= 128)\n m |= HTTP_CHARSET_TEXT | HTTP_CHARSET_OBS_TEXT;\n\n //Check if character is a token character\n if(strchr(\"!#$%&'*+-.^_`|~\", c))\n m |= HTTP_CHARSET_TCHAR;\n\n //Invalid character?\n if((m & charset) == 0)\n error = ERROR_INVALID_SYNTAX;\n }\n\n //Return status code\n return error;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "void * pvPortMalloc( size_t xWantedSize )\r\n{\r\n void * pvReturn = NULL;\r\n static uint8_t * pucAlignedHeap = NULL;\r\n\r\n /* Ensure that blocks are always aligned to the required number of bytes. */\r\n #if ( portBYTE_ALIGNMENT != 1 )\r\n {\r\n if( xWantedSize & portBYTE_ALIGNMENT_MASK )\r\n {\r\n /* Byte alignment required. */\r\n xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r\n }\r\n }\r\n #endif\r\n\r\n vTaskSuspendAll();\r\n {\r\n if( pucAlignedHeap == NULL )\r\n {\r\n /* Ensure the heap starts on a correctly aligned boundary. */\r\n pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );\r\n }\r\n\r\n /* Check there is enough room left for the allocation. */\r\n if( ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) &&\r\n ( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) ) /* Check for overflow. */\r\n {\r\n /* Return the next free byte then increment the index past this\r\n * block. */\r\n pvReturn = pucAlignedHeap + xNextFreeByte;\r\n xNextFreeByte += xWantedSize;\r\n }\r\n\r\n traceMALLOC( pvReturn, xWantedSize );\r\n }\r\n ( void ) xTaskResumeAll();\r\n\r\n #if ( configUSE_MALLOC_FAILED_HOOK == 1 )\r\n {\r\n if( pvReturn == NULL )\r\n {\r\n extern void vApplicationMallocFailedHook( void );\r\n vApplicationMallocFailedHook();\r\n }\r\n }\r\n #endif\r\n\r\n return pvReturn;\r\n}\r", "label": 0, "programming_language": "C", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "Map1to1(SDL_Palette * src, SDL_Palette * dst, int *identical)\n{\n Uint8 *map;\n int i;\n\n if (identical) {\n if (src->ncolors <= dst->ncolors) {\n /* If an identical palette, no need to map */\n if (src == dst\n ||\n (SDL_memcmp\n (src->colors, dst->colors,\n src->ncolors * sizeof(SDL_Color)) == 0)) {\n *identical = 1;\n return (NULL);\n }\n }\n *identical = 0;\n }\n map = (Uint8 *) SDL_malloc(src->ncolors);\n if (map == NULL) {\n SDL_OutOfMemory();\n return (NULL);\n }\n for (i = 0; i < src->ncolors; ++i) {\n map[i] = SDL_FindColor(dst,\n src->colors[i].r, src->colors[i].g,\n src->colors[i].b, src->colors[i].a);\n }\n return (map);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "static void ram_block_add(struct uc_struct *uc, RAMBlock *new_block)\n{\n RAMBlock *block;\n RAMBlock *last_block = NULL;\n\n new_block->offset = find_ram_offset(uc, new_block->max_length);\n\n if (!new_block->host) {\n new_block->host = phys_mem_alloc(uc, new_block->max_length,\n &new_block->mr->align);\n if (!new_block->host) {\n // error_setg_errno(errp, errno,\n // \"cannot set up guest memory '%s'\",\n // memory_region_name(new_block->mr));\n return;\n }\n // memory_try_enable_merging(new_block->host, new_block->max_length);\n }\n\n /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,\n * QLIST (which has an RCU-friendly variant) does not have insertion at\n * tail, so save the last element in last_block.\n */\n RAMBLOCK_FOREACH(block) {\n last_block = block;\n if (block->max_length < new_block->max_length) {\n break;\n }\n }\n if (block) {\n QLIST_INSERT_BEFORE(block, new_block, next);\n } else if (last_block) {\n QLIST_INSERT_AFTER(last_block, new_block, next);\n } else { /* list is empty */\n QLIST_INSERT_HEAD(&uc->ram_list.blocks, new_block, next);\n }\n uc->ram_list.mru_block = NULL;\n\n /* Write list before version */\n //smp_wmb();\n\n cpu_physical_memory_set_dirty_range(new_block->offset,\n new_block->used_length,\n DIRTY_CLIENTS_ALL);\n\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "MOBI_RET mobi_parse_huff(MOBIHuffCdic *huffcdic, const MOBIPdbRecord *record) {\n MOBIBuffer *buf = mobi_buffer_init_null(record->data, record->size);\n if (buf == NULL) {\n debug_print(\"%s\\n\", \"Memory allocation failed\");\n return MOBI_MALLOC_FAILED;\n }\n char huff_magic[5];\n mobi_buffer_getstring(huff_magic, buf, 4);\n const size_t header_length = mobi_buffer_get32(buf);\n if (strncmp(huff_magic, HUFF_MAGIC, 4) != 0 || header_length < HUFF_HEADER_LEN) {\n debug_print(\"HUFF wrong magic: %s\\n\", huff_magic);\n mobi_buffer_free_null(buf);\n return MOBI_DATA_CORRUPT;\n }\n const size_t data1_offset = mobi_buffer_get32(buf);\n const size_t data2_offset = mobi_buffer_get32(buf);\n /* skip little-endian table offsets */\n mobi_buffer_setpos(buf, data1_offset);\n if (buf->offset + (256 * 4) > buf->maxlen) {\n debug_print(\"%s\", \"HUFF data1 too short\\n\");\n mobi_buffer_free_null(buf);\n return MOBI_DATA_CORRUPT;\n }\n /* read 256 indices from data1 big-endian */\n for (int i = 0; i < 256; i++) {\n huffcdic->table1[i] = mobi_buffer_get32(buf);\n }\n mobi_buffer_setpos(buf, data2_offset);\n if (buf->offset + (64 * 4) > buf->maxlen) {\n debug_print(\"%s\", \"HUFF data2 too short\\n\");\n mobi_buffer_free_null(buf);\n return MOBI_DATA_CORRUPT;\n }\n /* read 32 mincode-maxcode pairs from data2 big-endian */\n huffcdic->mincode_table[0] = 0;\n huffcdic->maxcode_table[0] = 0xFFFFFFFF;\n for (int i = 1; i < 33; i++) {\n const uint32_t mincode = mobi_buffer_get32(buf);\n const uint32_t maxcode = mobi_buffer_get32(buf);\n huffcdic->mincode_table[i] = mincode << (32 - i);\n huffcdic->maxcode_table[i] = ((maxcode + 1) << (32 - i)) - 1;\n }\n mobi_buffer_free_null(buf);\n return MOBI_SUCCESS;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static int match_func(struct libmnt_fs *fs,\n\t\t void *data __attribute__ ((__unused__)))\n{\n\tint rc = flags & FL_INVERT ? 1 : 0;\n\tconst char *m;\n\tvoid *md;\n\n\tm = get_match(COL_FSTYPE);\n\tif (m && !mnt_fs_match_fstype(fs, m))\n\t\treturn rc;\n\n\tm = get_match(COL_OPTIONS);\n\tif (m && !mnt_fs_match_options(fs, m))\n\t\treturn rc;\n\n\tmd = get_match_data(COL_MAJMIN);\n\tif (md && mnt_fs_get_devno(fs) != *((dev_t *) md))\n\t\treturn rc;\n\n\tm = get_match(COL_TARGET);\n\tif (m && !mnt_fs_match_target(fs, m, cache))\n\t\treturn rc;\n\n\tm = get_match(COL_SOURCE);\n\tif (m && !mnt_fs_match_source(fs, m, cache))\n\t\treturn rc;\n\n\tif ((flags & FL_DF) && !(flags & FL_ALL)) {\n\t\tconst char *type = mnt_fs_get_fstype(fs);\n\n\t\tif (type && strstr(type, \"tmpfs\"))\t/* tmpfs is wanted */\n\t\t\treturn !rc;\n\n\t\tif (mnt_fs_is_pseudofs(fs))\n\t\t\treturn rc;\n\t}\n\n\tif ((flags & FL_REAL) && mnt_fs_is_pseudofs(fs))\n\t return rc;\n\n\tif ((flags & FL_PSEUDO) && !mnt_fs_is_pseudofs(fs))\n\t return rc;\n\n\tif ((flags & FL_SHADOWED)) {\n\t\tstruct libmnt_table *tb = NULL;\n\n\t\tmnt_fs_get_table(fs, &tb);\n\t\tif (tb && mnt_table_over_fs(tb, fs, NULL) != 0)\n\t\t\treturn rc;\n\t}\n\n\tif ((flags & FL_DELETED) && !mnt_fs_is_deleted(fs))\n\t\treturn rc;\n\n\treturn !rc;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "find_by_thp(struct tang_keys_info* tki, const char* target)\n{\n if (!tki) {\n return NULL;\n }\n\n json_auto_t* keys = json_deep_copy(tki->m_keys);\n json_array_extend(keys, tki->m_rotated_keys);\n\n size_t idx;\n json_t* jwk;\n const char** hashes = supported_hashes();\n json_array_foreach(keys, idx, jwk) {\n for (int i = 0; hashes[i]; i++) {\n __attribute__ ((__cleanup__(cleanup_str))) char* thumbprint = jwk_thumbprint(jwk, hashes[i]);\n if (!thumbprint || strcmp(thumbprint, target) != 0) {\n continue;\n }\n\n if (jwk_valid_for_deriving_keys(jwk)) {\n return json_incref(jwk);\n } else if (jwk_valid_for_signing(jwk)) {\n json_auto_t* sign = json_deep_copy(tki->m_sign);\n if (json_array_append(sign, jwk) == -1) {\n return NULL;\n }\n json_auto_t* jws = jwk_sign(tki->m_payload, sign);\n if (!jws) {\n return NULL;\n }\n return json_incref(jws);\n }\n }\n }\n return NULL;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "add_link_ref(\n\tstruct link_ref **references,\n\tconst uint8_t *name, size_t name_size)\n{\n\tstruct link_ref *ref = calloc(1, sizeof(struct link_ref));\n\n\tif (!ref)\n\t\treturn NULL;\n\n\tref->id = hash_link_ref(name, name_size);\n\tref->next = references[ref->id % REF_TABLE_SIZE];\n\n\treferences[ref->id % REF_TABLE_SIZE] = ref;\n\treturn ref;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-327", "cwe_name": "Use of a Broken or Risky Cryptographic Algorithm", "description": "The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.", "url": "https://cwe.mitre.org/data/definitions/327.html", "label_name": "vulnerable"} {"code": "DU_getStringDOElement(DcmItem *obj, DcmTagKey t, char *s, size_t bufsize)\n{\n DcmByteString *elem;\n DcmStack stack;\n OFCondition ec = EC_Normal;\n char* aString;\n\n ec = obj->search(t, stack);\n elem = (DcmByteString*) stack.top();\n if (ec == EC_Normal && elem != NULL) {\n if (elem->getLength() == 0) {\n s[0] = '\\0';\n } else {\n ec = elem->getString(aString);\n OFStandard::strlcpy(s, aString, bufsize);\n }\n }\n return (ec == EC_Normal);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "destroyPresentationContextList(LST_HEAD ** l)\n{\n PRV_PRESENTATIONCONTEXTITEM\n * prvCtx;\n DUL_SUBITEM\n * subItem;\n\n if (*l == NULL)\n return;\n\n prvCtx = (PRV_PRESENTATIONCONTEXTITEM*)LST_Dequeue(l);\n while (prvCtx != NULL) {\n subItem = (DUL_SUBITEM*)LST_Dequeue(&prvCtx->transferSyntaxList);\n while (subItem != NULL) {\n free(subItem);\n subItem = (DUL_SUBITEM*)LST_Dequeue(&prvCtx->transferSyntaxList);\n }\n LST_Destroy(&prvCtx->transferSyntaxList);\n free(prvCtx);\n prvCtx = (PRV_PRESENTATIONCONTEXTITEM*)LST_Dequeue(l);\n }\n LST_Destroy(l);\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-415", "cwe_name": "Double Free", "description": "The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.", "url": "https://cwe.mitre.org/data/definitions/415.html", "label_name": "vulnerable"} {"code": "int main(int argc, char **argv, char **envp)\n{\n\tint opt;\n\n\twhile ((opt = getopt(argc, argv, \"b:h:k:p:q:w:z:xv\")) != -1) {\n\t\tswitch (opt) {\n\t\tcase 'b':\n\t\t\ttmate_settings->bind_addr = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\ttmate_settings->tmate_host = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\ttmate_settings->keys_dir = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\ttmate_settings->ssh_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\ttmate_settings->ssh_port_advertized = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\ttmate_settings->websocket_hostname = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\ttmate_settings->websocket_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\ttmate_settings->use_proxy_protocol = true;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\ttmate_settings->log_level++;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tinit_logging(tmate_settings->log_level);\n\n\tsetup_locale();\n\n\tif (!tmate_settings->tmate_host)\n\t\ttmate_settings->tmate_host = get_full_hostname();\n\n\tcmdline = *argv;\n\tcmdline_end = *envp;\n\n\ttmate_preload_trace_lib();\n\ttmate_catch_sigsegv();\n\ttmate_init_rand();\n\n\tif ((mkdir(TMATE_WORKDIR, 0701) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/sessions\", 0703) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/jail\", 0700) < 0 && errno != EEXIST))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\t/* The websocket server needs to access the /session dir to rename sockets */\n\tif ((chmod(TMATE_WORKDIR, 0701) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/sessions\", 0703) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/jail\", 0700) < 0))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\ttmate_ssh_server_main(tmate_session,\n\t\t\t tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port);\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "njs_function_prototype_apply(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,\n njs_index_t unused)\n{\n int64_t i, length;\n njs_int_t ret;\n njs_frame_t *frame;\n njs_value_t *this, *arr_like;\n njs_array_t *arr;\n njs_function_t *func;\n\n if (!njs_is_function(njs_argument(args, 0))) {\n njs_type_error(vm, \"\\\"this\\\" argument is not a function\");\n return NJS_ERROR;\n }\n\n func = njs_function(njs_argument(args, 0));\n this = njs_arg(args, nargs, 1);\n arr_like = njs_arg(args, nargs, 2);\n\n if (njs_is_null_or_undefined(arr_like)) {\n length = 0;\n\n goto activate;\n\n } else if (njs_is_array(arr_like)) {\n arr = arr_like->data.u.array;\n\n args = arr->start;\n length = arr->length;\n\n goto activate;\n\n } else if (njs_slow_path(!njs_is_object(arr_like))) {\n njs_type_error(vm, \"second argument is not an array-like object\");\n return NJS_ERROR;\n }\n\n ret = njs_object_length(vm, arr_like, &length);\n if (njs_slow_path(ret != NJS_OK)) {\n return ret;\n }\n\n arr = njs_array_alloc(vm, 1, length, NJS_ARRAY_SPARE);\n if (njs_slow_path(arr == NULL)) {\n return NJS_ERROR;\n }\n\n args = arr->start;\n\n for (i = 0; i < length; i++) {\n ret = njs_value_property_i64(vm, arr_like, i, &args[i]);\n if (njs_slow_path(ret == NJS_ERROR)) {\n return ret;\n }\n }\n\nactivate:\n\n /* Skip the \"apply\" method frame. */\n vm->top_frame->skip = 1;\n\n frame = (njs_frame_t *) vm->top_frame;\n\n ret = njs_function_frame(vm, func, this, args, length, 0);\n if (njs_slow_path(ret != NJS_OK)) {\n return ret;\n }\n\n ret = njs_function_frame_invoke(vm, frame->native.retval);\n if (njs_slow_path(ret != NJS_OK)) {\n return ret;\n }\n\n return NJS_DECLINED;\n}", "label": 0, "programming_language": "C", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent)\n{\n\tint inspt;\n\tint i;\n\n\tfor (i = 0; i < tab->numents; ++i) {\n\t\tif (tab->ents[i]->ind > ent->ind) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tinspt = i;\n\n\tif (tab->numents >= tab->maxents) {\n\t\tif (jpc_ppxstab_grow(tab, tab->maxents + 128)) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tfor (i = tab->numents; i > inspt; --i) {\n\t\ttab->ents[i] = tab->ents[i - 1];\n\t}\n\ttab->ents[i] = ent;\n\t++tab->numents;\n\n\treturn 0;\n}", "label": 0, "programming_language": "C", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "vulnerable"} {"code": "def call_with_ns(f, ns, arg=1):\n td = Rtd()\n # prefer 'context' to 'here'; fall back to 'None'\n this = ns.get('context', ns.get('here'))\n td.this = this\n request = ns.get('request', {})\n if hasattr(request, 'taintWrapper'):\n request = request.taintWrapper()\n td._push(request)\n td._push(InstanceDict(td.this, td))\n td._push(ns)\n try:\n if arg==2:\n return f(None, td)\n else:\n return f(td)\n finally:\n td._pop(3)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " def test_call_with_request_preserves_tainting(self):\n from Products.PageTemplates.ZRPythonExpr import call_with_ns\n class Request(dict):\n def taintWrapper(self):\n return {'tainted': 'found'}\n context = ['context']\n here = ['here']\n names = {'context' : context, 'here': here, 'request' : Request()}\n\n found = call_with_ns(lambda td: td['tainted'], names)\n self.assertEqual(found, 'found')", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " def verify_cert_against_ca(self, filename, entry):\n \"\"\"\n check that a certificate validates against the ca cert,\n and that it has not expired.\n \"\"\"\n chaincert = self.CAs[self.cert_specs[entry.get('name')]['ca']].get('chaincert')\n cert = self.data + filename\n res = Popen([\"openssl\", \"verify\", \"-CAfile\", chaincert, cert],\n stdout=PIPE, stderr=STDOUT).stdout.read()\n if res == cert + \": OK\\n\":\n return True\n return False", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def format_date(self, data):\n \"\"\"\n A hook to control how dates are formatted.\n\n Can be overridden at the ``Serializer`` level (``datetime_formatting``)\n or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``).\n\n Default is ``iso-8601``, which looks like \"2010-12-16\".\n \"\"\"\n if self.datetime_formatting == 'rfc-2822':\n return format_date(data)\n\n return data.isoformat()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def deserialize(self, content, format='application/json'):\n \"\"\"\n Given some data and a format, calls the correct method to deserialize\n the data and returns the result.\n \"\"\"\n desired_format = None\n\n format = format.split(';')[0]\n\n for short_format, long_format in self.content_types.items():\n if format == long_format:\n if hasattr(self, \"from_%s\" % short_format):\n desired_format = short_format\n break\n\n if desired_format is None:\n raise UnsupportedFormat(\"The format indicated '%s' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer.\" % format)\n\n deserialized = getattr(self, \"from_%s\" % desired_format)(content)\n return deserialized", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def test_quotas_update_as_admin(self):\n body = {'quota_class_set': {'instances': 50, 'cores': 50,\n 'ram': 51200, 'volumes': 10,\n 'gigabytes': 1000, 'floating_ips': 10,\n 'metadata_items': 128, 'injected_files': 5,\n 'injected_file_content_bytes': 10240,\n 'security_groups': 10,\n 'security_group_rules': 20,\n }}\n\n req = fakes.HTTPRequest.blank(\n '/v2/fake4/os-quota-class-sets/test_class',\n use_admin_context=True)\n res_dict = self.controller.update(req, 'test_class', body)\n\n self.assertEqual(res_dict, body)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "def quota_set(class_name):\n return {'quota_class_set': {'id': class_name, 'metadata_items': 128,\n 'volumes': 10, 'gigabytes': 1000, 'ram': 51200,\n 'floating_ips': 10, 'instances': 10, 'injected_files': 5,\n 'cores': 20, 'injected_file_content_bytes': 10240,\n 'security_groups': 10, 'security_group_rules': 20}}", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def _stub_project(self, override=False):\n def fake_quota_get_all_by_project(context, project_id):\n result = dict(project_id=project_id)\n if override:\n result.update(\n instances=2,\n cores=5,\n ram=12 * 1024,\n volumes=2,\n gigabytes=250,\n floating_ips=2,\n security_groups=5,\n security_group_rules=10,\n metadata_items=32,\n injected_files=1,\n injected_file_content_bytes=2 * 1024,\n invalid_quota=50,\n )\n return result\n\n self.stubs.Set(db, 'quota_get_all_by_project',\n fake_quota_get_all_by_project)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def setUp(self):\n super(GetQuotaTestCase, self).setUp()\n self.flags(quota_instances=10,\n quota_cores=20,\n quota_ram=50 * 1024,\n quota_volumes=10,\n quota_gigabytes=1000,\n quota_floating_ips=10,\n quota_security_groups=10,\n quota_security_group_rules=20,\n quota_metadata_items=128,\n quota_injected_files=5,\n quota_injected_file_content_bytes=10 * 1024)\n self.context = context.RequestContext('admin', 'admin', is_admin=True)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def test_class_quotas(self):\n self._stub_class()\n result = quota.get_class_quotas(self.context, 'test_class')\n self.assertEqual(result, dict(\n instances=5,\n cores=10,\n ram=25 * 1024,\n volumes=5,\n gigabytes=500,\n floating_ips=5,\n security_groups=10,\n security_group_rules=20,\n metadata_items=64,\n injected_files=2,\n injected_file_content_bytes=5 * 1024,\n ))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def test_inject_files_with_bad_path(self):\n self.assertRaises(exception.Invalid,\n disk_api._inject_file_into_fs,\n '/tmp', '/etc/../../../../etc/passwd',\n 'hax')", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def test_check_unsafe_path(self):\n self.assertRaises(exception.Invalid,\n disk_api._join_and_check_path_within_fs,\n '/foo', 'etc/../../../something.conf')", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "def _inject_net_into_fs(net, fs, execute=None):\n \"\"\"Inject /etc/network/interfaces into the filesystem rooted at fs.\n\n net is the contents of /etc/network/interfaces.\n \"\"\"\n netdir = _join_and_check_path_within_fs(fs, 'etc', 'network')\n utils.execute('mkdir', '-p', netdir, run_as_root=True)\n utils.execute('chown', 'root:root', netdir, run_as_root=True)\n utils.execute('chmod', 755, netdir, run_as_root=True)\n\n netfile = os.path.join('etc', 'network', 'interfaces')\n _inject_file_into_fs(fs, netfile, net)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " def _all_hosts(self, context):\n all_hosts = {}\n for instance in self.compute_api.get_all(context):\n all_hosts[instance['uuid']] = instance['host']\n return all_hosts", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def read(self):\n result = self.data.read()\n self.bytes_read += len(result)\n if self.bytes_read > self.limit:\n raise exception.RequestTooLarge()\n return result", "label": 1, "programming_language": "Python", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": " def fake_app(req):\n return webob.Response(req.body)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": " def test_request_too_large_no_content_length(self):\n self.request.body = \"0\" * (MAX_REQUEST_BODY_SIZE + 1)\n self.request.headers['Content-Length'] = None\n self.assertRaises(exception.RequestTooLarge,\n self.request.get_response,\n self.middleware)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": " def list_tokens(self, user_id):\n tokens = []\n now = datetime.datetime.utcnow()\n for token, user_ref in self.db.items():\n if not token.startswith('token-'):\n continue\n if 'user' not in user_ref:\n continue\n if user_ref['user'].get('id') != user_id:\n continue\n if user_ref.get('expires') and user_ref.get('expires') < now:\n continue\n tokens.append(token.split('-', 1)[1])\n return tokens", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def list_tokens(self, user_id):\n \"\"\"Returns a list of current token_id's for a user\n\n :param user_id: identity of the user\n :type user_id: string\n :returns: list of token_id's\n\n \"\"\"\n raise exception.NotImplemented()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def update_user(self, context, user_id, user):\n # NOTE(termie): this is really more of a patch than a put\n self.assert_admin(context)\n if self.identity_api.get_user(context, user_id) is None:\n raise exception.UserNotFound(user_id=user_id)\n\n user_ref = self.identity_api.update_user(context, user_id, user)\n\n # If the password was changed or the user was disabled we clear tokens\n if user.get('password') or user.get('enabled', True) == False:\n try:\n for token_id in self.token_api.list_tokens(context, user_id):\n self.token_api.delete_token(context, token_id)\n except exception.NotImplemented:\n # The users status has been changed but tokens remain valid for\n # backends that can't list tokens for users\n LOG.warning('User %s status has changed, but existing tokens '\n 'remain valid' % user_id)\n return {'user': user_ref}", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def get_user_roles(self, context, user_id, tenant_id=None):\n \"\"\"Get the roles for a user and tenant pair.\n\n Since we're trying to ignore the idea of user-only roles we're\n not implementing them in hopes that the idea will die off.\n\n \"\"\"\n self.assert_admin(context)\n if tenant_id is None:\n raise exception.NotImplemented(message='User roles not supported: '\n 'tenant ID required')\n\n user = self.identity_api.get_user(context, user_id)\n if user is None:\n raise exception.UserNotFound(user_id=user_id)\n tenant = self.identity_api.get_tenant(context, tenant_id)\n if tenant is None:\n raise exception.TenantNotFound(tenant_id=tenant_id)\n\n roles = self.identity_api.get_roles_for_user_and_tenant(\n context, user_id, tenant_id)\n return {'roles': [self.identity_api.get_role(context, x)\n for x in roles]}", "label": 1, "programming_language": "Python", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "safe"} {"code": " def aesDecrypt(data, key):\n cipher = AES.new(key, AES.MODE_CTR,\n counter=Counter.new(128, initial_value=0))\n return cipher.decrypt(data)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " def __init__(self, app, conf):\n self.app = app\n self.memcache_servers = conf.get('memcache_servers')\n serialization_format = conf.get('memcache_serialization_support')\n\n if not self.memcache_servers or serialization_format is None:\n path = os.path.join(conf.get('swift_dir', '/etc/swift'),\n 'memcache.conf')\n memcache_conf = ConfigParser()\n if memcache_conf.read(path):\n if not self.memcache_servers:\n try:\n self.memcache_servers = \\\n memcache_conf.get('memcache', 'memcache_servers')\n except (NoSectionError, NoOptionError):\n pass\n if serialization_format is None:\n try:\n serialization_format = \\\n memcache_conf.get('memcache',\n 'memcache_serialization_support')\n except (NoSectionError, NoOptionError):\n pass\n\n if not self.memcache_servers:\n self.memcache_servers = '127.0.0.1:11211'\n if serialization_format is None:\n serialization_format = 2\n\n self.memcache = MemcacheRing(\n [s.strip() for s in self.memcache_servers.split(',') if s.strip()],\n allow_pickle=(serialization_format == 0),\n allow_unpickle=(serialization_format <= 1))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "safe"} {"code": "def _is_safe_url(url, host):\n # Chrome considers any URL with more than two slashes to be absolute, but\n # urlparse is not so flexible. Treat any url with three slashes as unsafe.\n if url.startswith('///'):\n return False\n url_info = urlparse(url)\n # Forbid URLs like http:///example.com - with a scheme, but without a hostname.\n # In that URL, example.com is not the hostname but, a path component. However,\n # Chrome will still consider example.com to be the hostname, so we must not\n # allow this syntax.\n if not url_info.netloc and url_info.scheme:\n return False\n # Forbid URLs that start with control characters. Some browsers (like\n # Chrome) ignore quite a few control characters at the start of a\n # URL and might consider the URL as scheme relative.\n if unicodedata.category(url[0])[0] == 'C':\n return False\n return ((not url_info.netloc or url_info.netloc == host) and\n (not url_info.scheme or url_info.scheme in ['http', 'https']))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "def check_password(password, encoded, setter=None, preferred='default'):\n \"\"\"\n Returns a boolean of whether the raw password matches the three\n part encoded digest.\n\n If setter is specified, it'll be called when you need to\n regenerate the password.\n \"\"\"\n if password is None or not is_password_usable(encoded):\n return False\n\n preferred = get_hasher(preferred)\n hasher = identify_hasher(encoded)\n\n hasher_changed = hasher.algorithm != preferred.algorithm\n must_update = hasher_changed or preferred.must_update(encoded)\n is_correct = hasher.verify(password, encoded)\n\n # If the hasher didn't change (we don't protect against enumeration if it\n # does) and the password should get updated, try to close the timing gap\n # between the work factor of the current encoded password and the default\n # work factor.\n if not is_correct and not hasher_changed and must_update:\n hasher.harden_runtime(password, encoded)\n\n if setter and is_correct and must_update:\n setter(password)\n return is_correct", "label": 1, "programming_language": "Python", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " def __init__(self, *expressions, ordering=(), **extra):\n if not isinstance(ordering, (list, tuple)):\n ordering = [ordering]\n ordering = ordering or []\n # Transform minus sign prefixed strings into an OrderBy() expression.\n ordering = (\n (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o)\n for o in ordering\n )\n super().__init__(*expressions, **extra)\n self.ordering = self._parse_expressions(*ordering)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "def get_tests(config={}):\n tests = []\n from Crypto.SelfTest.Random import Fortuna; tests += Fortuna.get_tests(config=config)\n from Crypto.SelfTest.Random import OSRNG; tests += OSRNG.get_tests(config=config)\n from Crypto.SelfTest.Random import test_random; tests += test_random.get_tests(config=config)\n from Crypto.SelfTest.Random import test_rpoolcompat; tests += test_rpoolcompat.get_tests(config=config)\n from Crypto.SelfTest.Random import test__UserFriendlyRNG; tests += test__UserFriendlyRNG.get_tests(config=config)\n return tests", "label": 1, "programming_language": "Python", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " def _get_reseed_count(self):\n \"\"\"\n Get `FortunaAccumulator.reseed_count`, the global count of the\n number of times that the PRNG has been reseeded.\n \"\"\"\n rng_singleton = Crypto.Random._UserFriendlyRNG._get_singleton()\n rng_singleton._lock.acquire()\n try:\n return rng_singleton._fa.reseed_count\n finally:\n rng_singleton._lock.release()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " def check_permissions():\n \"\"\" If on posix, permissions should be 0700. \"\"\"\n writable = is_writable(im_dir)\n if sys.platform != 'win32':\n try:\n im_dir_stat = os.stat(im_dir)\n except OSError:\n return False\n writable &= stat.S_IMODE(im_dir_stat.st_mode) == 0o0700\n return writable", "label": 1, "programming_language": "Python", "cwe_id": "CWE-269", "cwe_name": "Improper Privilege Management", "description": "The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.", "url": "https://cwe.mitre.org/data/definitions/269.html", "label_name": "safe"} {"code": "def create_intermediate_dir(tmp_dir=None):\n py_im_dir = py_intermediate_dir()\n return create_temp_dir(intermediate_dir_prefix(), py_im_dir, tmp_dir)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-269", "cwe_name": "Improper Privilege Management", "description": "The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.", "url": "https://cwe.mitre.org/data/definitions/269.html", "label_name": "safe"} {"code": "def default_dir_posix(tmp_dir=None):\n \"\"\"\n Create or find default catalog store for posix systems\n\n purpose of 'tmp_dir' is to enable way how to test this function easily\n \"\"\"\n path_candidates = []\n python_name = \"python%d%d_compiled\" % tuple(sys.version_info[:2])\n\n if tmp_dir:\n home_dir = tmp_dir\n else:\n home_dir = os.path.expanduser('~')\n tmp_dir = tmp_dir or tempfile.gettempdir()\n\n home_temp_dir_name = '.' + python_name\n home_temp_dir = os.path.join(home_dir, home_temp_dir_name)\n path_candidates.append(home_temp_dir)\n\n temp_dir_name = repr(os.getuid()) + '_' + python_name\n temp_dir_path = os.path.join(tmp_dir, temp_dir_name)\n path_candidates.append(temp_dir_path)\n\n for path in path_candidates:\n _create_dirs(path)\n if check_dir(path):\n return path\n\n # since we got here, both dirs are not useful\n tmp_dir_path = find_valid_temp_dir(temp_dir_name, tmp_dir)\n if not tmp_dir_path:\n tmp_dir_path = create_temp_dir(temp_dir_name, tmp_dir=tmp_dir)\n return tmp_dir_path", "label": 1, "programming_language": "Python", "cwe_id": "CWE-269", "cwe_name": "Improper Privilege Management", "description": "The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.", "url": "https://cwe.mitre.org/data/definitions/269.html", "label_name": "safe"} {"code": " def tearDown(self):\n self.file.close()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "def Ghostscript(tile, size, fp, scale=1):\n \"\"\"Render an image using Ghostscript\"\"\"\n\n # Unpack decoder tile\n decoder, tile, offset, data = tile[0]\n length, bbox = data\n\n #Hack to support hi-res rendering\n scale = int(scale) or 1\n orig_size = size\n orig_bbox = bbox\n size = (size[0] * scale, size[1] * scale)\n bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]\n #print(\"Ghostscript\", scale, size, orig_size, bbox, orig_bbox)\n\n import tempfile, os, subprocess\n\n out_fd, file = tempfile.mkstemp()\n os.close(out_fd)\n\n # Build ghostscript command\n command = [\"gs\",\n \"-q\", # quite mode\n \"-g%dx%d\" % size, # set output geometry (pixels)\n \"-r%d\" % (72*scale), # set input DPI (dots per inch)\n \"-dNOPAUSE -dSAFER\", # don't pause between pages, safe mode\n \"-sDEVICE=ppmraw\", # ppm driver\n \"-sOutputFile=%s\" % file,# output file\n ]\n\n if gs_windows_binary is not None:\n if gs_windows_binary is False:\n raise WindowsError('Unable to locate Ghostscript on paths')\n command[0] = gs_windows_binary\n\n # push data through ghostscript\n try:\n gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n # adjust for image origin\n if bbox[0] != 0 or bbox[1] != 0:\n gs.stdin.write((\"%d %d translate\\n\" % (-bbox[0], -bbox[1])).encode('ascii'))\n fp.seek(offset)\n while length > 0:\n s = fp.read(8192)\n if not s:\n break\n length = length - len(s)\n gs.stdin.write(s)\n gs.stdin.close()\n status = gs.wait()\n if status:\n raise IOError(\"gs failed (status %d)\" % status)\n im = Image.core.open_ppm(file)\n finally:\n try: os.unlink(file)\n except: pass\n\n return im", "label": 1, "programming_language": "Python", "cwe_id": "CWE-59", "cwe_name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.", "url": "https://cwe.mitre.org/data/definitions/59.html", "label_name": "safe"} {"code": "def Ghostscript(tile, size, fp, scale=1):\n \"\"\"Render an image using Ghostscript\"\"\"\n\n # Unpack decoder tile\n decoder, tile, offset, data = tile[0]\n length, bbox = data\n\n #Hack to support hi-res rendering\n scale = int(scale) or 1\n orig_size = size\n orig_bbox = bbox\n size = (size[0] * scale, size[1] * scale)\n bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]\n #print(\"Ghostscript\", scale, size, orig_size, bbox, orig_bbox)\n\n import tempfile, os, subprocess\n\n out_fd, file = tempfile.mkstemp()\n os.close(out_fd)\n\n # Build ghostscript command\n command = [\"gs\",\n \"-q\", # quite mode\n \"-g%dx%d\" % size, # set output geometry (pixels)\n \"-r%d\" % (72*scale), # set input DPI (dots per inch)\n \"-dNOPAUSE -dSAFER\", # don't pause between pages, safe mode\n \"-sDEVICE=ppmraw\", # ppm driver\n \"-sOutputFile=%s\" % file,# output file\n ]\n\n if gs_windows_binary is not None:\n if gs_windows_binary is False:\n raise WindowsError('Unable to locate Ghostscript on paths')\n command[0] = gs_windows_binary\n\n # push data through ghostscript\n try:\n gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n # adjust for image origin\n if bbox[0] != 0 or bbox[1] != 0:\n gs.stdin.write((\"%d %d translate\\n\" % (-bbox[0], -bbox[1])).encode('ascii'))\n fp.seek(offset)\n while length > 0:\n s = fp.read(8192)\n if not s:\n break\n length = length - len(s)\n gs.stdin.write(s)\n gs.stdin.close()\n status = gs.wait()\n if status:\n raise IOError(\"gs failed (status %d)\" % status)\n im = Image.core.open_ppm(file)\n finally:\n try: os.unlink(file)\n except: pass\n\n return im", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def load(self):\n\n if len(self.tile) != 1 or self.tile[0][0] != \"iptc\":\n return ImageFile.ImageFile.load(self)\n\n type, tile, box = self.tile[0]\n\n encoding, offset = tile\n\n self.fp.seek(offset)\n\n # Copy image data to temporary file\n o_fd, outfile = tempfile.mkstemp(text=False)\n o = os.fdopen(o_fd)\n if encoding == \"raw\":\n # To simplify access to the extracted file,\n # prepend a PPM header\n o.write(\"P5\\n%d %d\\n255\\n\" % self.size)\n while True:\n type, size = self.field()\n if type != (8, 10):\n break\n while size > 0:\n s = self.fp.read(min(size, 8192))\n if not s:\n break\n o.write(s)\n size = size - len(s)\n o.close()\n\n try:\n try:\n # fast\n self.im = Image.core.open_ppm(outfile)\n except:\n # slightly slower\n im = Image.open(outfile)\n im.load()\n self.im = im.im\n finally:\n try: os.unlink(outfile)\n except: pass", "label": 1, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def put_file(self, in_path, out_path):\n ''' transfer a file from local to zone '''\n\n vvv(\"PUT %s TO %s\" % (in_path, out_path), host=self.zone)\n\n with open(in_path, 'rb') as in_file:\n p = self._buffered_exec_command('dd of=%s' % out_path, None, stdin=in_file)\n try:\n stdout, stderr = p.communicate()\n except:\n traceback.print_exc()\n raise errors.AnsibleError(\"failed to transfer file to %s\" % out_path)\n if p.returncode != 0:\n raise errors.AnsibleError(\"failed to transfer file to %s:\\n%s\\n%s\" % (out_path, stdout, stderr))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-59", "cwe_name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.", "url": "https://cwe.mitre.org/data/definitions/59.html", "label_name": "safe"} {"code": " def test_gravatar_xss(self):\n \"\"\"Testing {% gravatar %} doesn't allow XSS injection\"\"\"\n user = User(username='test',\n first_name='\"><\"',\n email='test@example.com')\n\n node = gravatar(self.parser, Token(TOKEN_TEXT, 'gravatar user 32'))\n context = {\n 'request': DummyRequest(),\n 'user': user,\n }\n\n self.assertEqual(\n node.render(context),\n '')", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " def test_local(self):\n '''Load a local template *.py file'''\n\n with tempfile.NamedTemporaryFile(prefix='answer_', suffix='.py') as my_template:\n my_template.write(b'''import dbus\nBUS_NAME = 'universe.Ultimate'\nMAIN_OBJ = '/'\nMAIN_IFACE = 'universe.Ultimate'\nSYSTEM_BUS = False\n\ndef load(mock, parameters):\n mock.AddMethods(MAIN_IFACE, [('Answer', '', 'i', 'ret = 42')])\n''')\n my_template.flush()\n (p_mock, dbus_ultimate) = self.spawn_server_template(\n my_template.name, stdout=subprocess.PIPE)\n self.addCleanup(p_mock.wait)\n self.addCleanup(p_mock.terminate)\n self.addCleanup(p_mock.stdout.close)\n\n # ensure that we don't use/write any .pyc files, they are dangerous\n # in a world-writable directory like /tmp\n self.assertFalse(os.path.exists(my_template.name + 'c'))\n try:\n from importlib.util import cache_from_source\n self.assertFalse(os.path.exists(cache_from_source(my_template.name)))\n except ImportError:\n # python < 3.4\n pass\n\n self.assertEqual(dbus_ultimate.Answer(), 42)\n\n # should appear in introspection\n xml = dbus_ultimate.Introspect()\n self.assertIn('', xml)\n self.assertIn('', xml)\n\n # should not have ObjectManager API by default\n self.assertRaises(dbus.exceptions.DBusException,\n dbus_ultimate.GetManagedObjects)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def test_change_due_date(self):\n url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.post(url, {\n 'student': self.user1.username,\n 'url': self.week1.location.to_deprecated_string(),\n 'due_datetime': '12/30/2013 00:00'\n })\n self.assertEqual(response.status_code, 200, response.content)\n self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc),\n get_extended_due(self.course, self.week1, self.user1))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def call_add_users_to_cohorts(self, csv_data, suffix='.csv'):\n \"\"\"\n Call `add_users_to_cohorts` with a file generated from `csv_data`.\n \"\"\"\n # this temporary file will be removed in `self.tearDown()`\n __, file_name = tempfile.mkstemp(suffix=suffix, dir=self.tempdir)\n with open(file_name, 'w') as file_pointer:\n file_pointer.write(csv_data.encode('utf-8'))\n with open(file_name, 'r') as file_pointer:\n url = reverse('add_users_to_cohorts', kwargs={'course_id': unicode(self.course.id)})\n return self.client.post(url, {'uploaded-file': file_pointer})", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def test_modify_access_with_fake_user(self):\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.post(url, {\n 'unique_student_identifier': 'GandalfTheGrey',\n 'rolename': 'staff',\n 'action': 'revoke',\n })\n self.assertEqual(response.status_code, 200)\n expected = {\n 'unique_student_identifier': 'GandalfTheGrey',\n 'userDoesNotExist': True,\n }\n res_json = json.loads(response.content)\n self.assertEqual(res_json, expected)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def test_get_students_who_may_enroll(self):\n \"\"\"\n Test whether get_students_who_may_enroll returns an appropriate\n status message when users request a CSV file of students who\n may enroll in a course.\n \"\"\"\n url = reverse(\n 'get_students_who_may_enroll',\n kwargs={'course_id': unicode(self.course.id)}\n )\n # Successful case:\n response = self.client.post(url, {})\n res_json = json.loads(response.content)\n self.assertIn('status', res_json)\n self.assertNotIn('currently being created', res_json['status'])\n # CSV generation already in progress:\n with patch('instructor_task.api.submit_calculate_may_enroll_csv') as submit_task_function:\n error = AlreadyRunningError()\n submit_task_function.side_effect = error\n response = self.client.post(url, {})\n res_json = json.loads(response.content)\n self.assertIn('status', res_json)\n self.assertIn('currently being created', res_json['status'])", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def test_list_instructor_tasks_problem_student(self, act):\n \"\"\" Test list task history for problem AND student. \"\"\"\n act.return_value = self.tasks\n url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})\n mock_factory = MockCompletionInfo()\n with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:\n mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info\n response = self.client.post(url, {\n 'problem_location_str': self.problem_urlname,\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 200)\n\n # check response\n self.assertTrue(act.called)\n expected_tasks = [ftask.to_dict() for ftask in self.tasks]\n actual_tasks = json.loads(response.content)['tasks']\n for exp_task, act_task in zip(expected_tasks, actual_tasks):\n self.assertDictEqual(exp_task, act_task)\n\n self.assertEqual(actual_tasks, expected_tasks)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def test_rescore_entrance_exam_all_student_and_single(self):\n \"\"\" Test re-scoring with both all students and single student parameters. \"\"\"\n url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})\n response = self.client.post(url, {\n 'unique_student_identifier': self.student.email,\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 400)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def test_list_background_email_tasks(self, act):\n \"\"\"Test list of background email tasks.\"\"\"\n act.return_value = self.tasks\n url = reverse('list_background_email_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})\n mock_factory = MockCompletionInfo()\n with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:\n mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info\n response = self.client.post(url, {})\n self.assertEqual(response.status_code, 200)\n\n # check response\n self.assertTrue(act.called)\n expected_tasks = [ftask.to_dict() for ftask in self.tasks]\n actual_tasks = json.loads(response.content)['tasks']\n for exp_task, act_task in zip(expected_tasks, actual_tasks):\n self.assertDictEqual(exp_task, act_task)\n self.assertEqual(actual_tasks, expected_tasks)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def test_modify_access_revoke_with_username(self):\n url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.post(url, {\n 'unique_student_identifier': self.other_staff.username,\n 'rolename': 'staff',\n 'action': 'revoke',\n })\n self.assertEqual(response.status_code, 200)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def register_with_redemption_code(self, user, code):\n \"\"\"\n enroll user using a registration code\n \"\"\"\n redeem_url = reverse('shoppingcart.views.register_code_redemption', args=[code], is_dashboard_endpoint=False)\n self.client.login(username=user.username, password='test')\n response = self.client.get(redeem_url)\n self.assertEquals(response.status_code, 200)\n # check button text\n self.assertTrue('Activate Course Enrollment' in response.content)\n\n response = self.client.post(redeem_url)\n self.assertEquals(response.status_code, 200)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def test_get_problem_responses_invalid_location(self):\n \"\"\"\n Test whether get_problem_responses returns an appropriate status\n message when users submit an invalid problem location.\n \"\"\"\n url = reverse(\n 'get_problem_responses',\n kwargs={'course_id': unicode(self.course.id)}\n )\n problem_location = ''\n\n response = self.client.post(url, {'problem_location': problem_location})\n res_json = json.loads(response.content)\n self.assertEqual(res_json, 'Could not find problem with this location.')", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": "def list_course_role_members(request, course_id):\n \"\"\"\n List instructors and staff.\n Requires instructor access.\n\n rolename is one of ['instructor', 'staff', 'beta', 'ccx_coach']\n\n Returns JSON of the form {\n \"course_id\": \"some/course/id\",\n \"staff\": [\n {\n \"username\": \"staff1\",\n \"email\": \"staff1@example.org\",\n \"first_name\": \"Joe\",\n \"last_name\": \"Shmoe\",\n }\n ]\n }\n \"\"\"\n course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)\n course = get_course_with_access(\n request.user, 'instructor', course_id, depth=None\n )\n\n rolename = request.POST.get('rolename')\n\n if rolename not in ROLES:\n return HttpResponseBadRequest()\n\n def extract_user_info(user):\n \"\"\" convert user into dicts for json view \"\"\"\n return {\n 'username': user.username,\n 'email': user.email,\n 'first_name': user.first_name,\n 'last_name': user.last_name,\n }\n\n response_payload = {\n 'course_id': course_id.to_deprecated_string(),\n rolename: map(extract_user_info, list_with_level(\n course, rolename\n )),\n }\n return JsonResponse(response_payload)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def test_dir_struct_exists(self, mopen, mock_os):\n \"\"\"\n Test that when the directory structure already exists, the write still happens.\n \"\"\"\n\n class MockException(OSError):\n pass\n\n mock_e = MockException()\n mock_e.errno = 17\n mock_os.makedirs.side_effect = mock_e\n mock_fp = open.return_value\n\n cli.write_to_location('test/loc', 'content')\n mock_os.path.dirname.assert_called_once_with('test/loc')\n mock_os.makedirs.assert_called_once_with(mock_os.path.dirname.return_value)\n open.assert_called_once_with('test/loc', 'w+')\n mock_fp.write.assert_called_once_with('content')\n mock_fp.close.assert_called_once_with()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "safe"} {"code": " def test_misc_os_err(self, mopen, mock_os):\n \"\"\"\n Test that misc errors are reraised and the write does not happen.\n \"\"\"\n\n class MockException(OSError):\n pass\n\n mock_e = MockException()\n mock_e.errno = 16\n mock_os.makedirs.side_effect = mock_e\n mock_fp = open.return_value\n\n self.assertRaises(MockException, cli.write_to_location, 'test/loc', 'content')\n self.assertEqual(mock_fp.write.call_count, 0)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "safe"} {"code": "def failed_login_count():\n denied_hosts = read_hosts_deny()\n val = denied_hosts.get(request.client, (0, 0))\n return val[0]", "label": 1, "programming_language": "Python", "cwe_id": "CWE-254", "cwe_name": "7PK - Security Features", "description": "Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.", "url": "https://cwe.mitre.org/data/definitions/254.html", "label_name": "safe"} {"code": " def is_leaf(cls, path):\n filesystem_path = pathutils.path_to_filesystem(path, FOLDER)\n return (os.path.isfile(filesystem_path) and not\n filesystem_path.endswith(\".props\"))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-21", "cwe_name": "DEPRECATED: Pathname Traversal and Equivalence Errors", "description": "This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).", "url": "https://cwe.mitre.org/data/definitions/21.html", "label_name": "safe"} {"code": " def write(self):\n self._create_dirs()\n for component in self.components:\n text = ical.serialize(\n self.tag, self.headers, [component] + self.timezones)\n name = (\n component.name if sys.version_info[0] >= 3 else\n component.name.encode(filesystem.FILESYSTEM_ENCODING))\n filesystem_path = os.path.join(self._filesystem_path, name)\n with filesystem.open(filesystem_path, \"w\") as fd:\n fd.write(text)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-21", "cwe_name": "DEPRECATED: Pathname Traversal and Equivalence Errors", "description": "This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).", "url": "https://cwe.mitre.org/data/definitions/21.html", "label_name": "safe"} {"code": " def delete(self):\n shutil.rmtree(self._filesystem_path)\n os.remove(self._props_path)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-21", "cwe_name": "DEPRECATED: Pathname Traversal and Equivalence Errors", "description": "This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).", "url": "https://cwe.mitre.org/data/definitions/21.html", "label_name": "safe"} {"code": "def extension_element_from_string(xml_string):\n element_tree = defusedxml.ElementTree.fromstring(xml_string)\n return _extension_element_from_element_tree(element_tree)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "safe"} {"code": "def class_instances_from_soap_enveloped_saml_thingies(text, modules):\n \"\"\"Parses a SOAP enveloped header and body SAML thing and returns the\n thing as a dictionary class instance.\n\n :param text: The SOAP object as XML\n :param modules: modules representing xsd schemas\n :return: The body and headers as class instances\n \"\"\"\n try:\n envelope = defusedxml.ElementTree.fromstring(text)\n except Exception as exc:\n raise XmlParseError(\"%s\" % exc)\n\n assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n env = {\"header\": [], \"body\": None}\n\n for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n env[\"body\"] = instanciate_class(part[0], modules)\n elif part.tag == \"{%s}Header\" % soapenv.NAMESPACE:\n for item in part:\n env[\"header\"].append(instanciate_class(item, modules))\n\n return env", "label": 1, "programming_language": "Python", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "safe"} {"code": "def open_soap_envelope(text):\n \"\"\"\n\n :param text: SOAP message\n :return: dictionary with two keys \"body\"/\"header\"\n \"\"\"\n try:\n envelope = defusedxml.ElementTree.fromstring(text)\n except Exception as exc:\n raise XmlParseError(\"%s\" % exc)\n\n assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n content = {\"header\": [], \"body\": None}\n\n for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n content[\"body\"] = ElementTree.tostring(part[0], encoding=\"UTF-8\")\n elif part.tag == \"{%s}Header\" % soapenv.NAMESPACE:\n for item in part:\n _str = ElementTree.tostring(item, encoding=\"UTF-8\")\n content[\"header\"].append(_str)\n\n return content", "label": 1, "programming_language": "Python", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "safe"} {"code": " def export_bookmarks(self):\n filename = choose_save_file(\n self, 'export-viewer-bookmarks', _('Export bookmarks'),\n filters=[(_('Saved bookmarks'), ['calibre-bookmarks'])], all_files=False, initial_filename='bookmarks.calibre-bookmarks')\n if filename:\n with lopen(filename, 'wb') as fileobj:\n fileobj.write(json.dumps(self.get_bookmarks(), indent=True))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "safe"} {"code": " def unwrap(self, key, bitsize, ek, headers):\n self._check_key(key)\n # Address MMA attack by implementing RFC 3218 - 2.3.2. Random Filling\n # provides a random cek that will cause the decryption engine to\n # run to the end, but will fail decryption later.\n\n # always generate a random cek so we spend roughly the\n # same time as in the exception side of the branch\n cek = _randombits(bitsize)\n try:\n cek = super(_Rsa15, self).unwrap(key, bitsize, ek, headers)\n # always raise so we always run through the exception handling\n # code in all cases\n raise Exception('Dummy')\n except Exception: # pylint: disable=broad-except\n return cek", "label": 1, "programming_language": "Python", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": "def testLegacyQuoteAttribute(c):\n input_ = [[\"StartTag\", \"http://www.w3.org/1999/xhtml\", \"span\",\n [{\"namespace\": None, \"name\": \"foo\", \"value\": c}]]]\n if c == '\"':\n output_ = [\"\" % c]\n else:\n output_ = ['' % c]\n options_ = {\"quote_attr_values\": \"legacy\"}\n runSerializerTest(input_, output_, options_)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "def _hkey(key):\n if '\\n' in key or '\\r' in key or '\\0' in key:\n raise ValueError(\"Header names must not contain control characters: %r\" % key)\n return key.title().replace('_', '-')", "label": 1, "programming_language": "Python", "cwe_id": "CWE-93", "cwe_name": "Improper Neutralization of CRLF Sequences ('CRLF Injection')", "description": "The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs.", "url": "https://cwe.mitre.org/data/definitions/93.html", "label_name": "safe"} {"code": " def write_realm_audit_log_entry(user_profile: Any,\n event_time: Any, event_type: Any,\n affected_user_type: str) -> None:", "label": 1, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " def test_email_auth_backend_empty_password(self) -> None:\n user_profile = self.example_user('hamlet')\n password = \"testpassword\"\n user_profile.set_password(password)\n user_profile.save()\n\n # First, verify authentication works with the a nonempty\n # password so we know we've set up the test correctly.\n self.assertIsNotNone(EmailAuthBackend().authenticate(username=self.example_email('hamlet'),\n password=password,\n realm=get_realm(\"zulip\")))\n\n # Now do the same test with the empty string as the password.\n password = \"\"\n user_profile.set_password(password)\n user_profile.save()\n self.assertIsNone(EmailAuthBackend().authenticate(username=self.example_email('hamlet'),\n password=password,\n realm=get_realm(\"zulip\")))", "label": 1, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "def check_prereg_key(\n request: HttpRequest, confirmation_key: str", "label": 1, "programming_language": "Python", "cwe_id": "CWE-613", "cwe_name": "Insufficient Session Expiration", "description": "According to WASC, \"Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization.\"", "url": "https://cwe.mitre.org/data/definitions/613.html", "label_name": "safe"} {"code": " def test_social_auth_registration_using_multiuse_invite_realm_validation(self) -> None:\n \"\"\"If the user doesn't exist yet, social auth can be used to register an account\"\"\"\n email = \"newuser@zulip.com\"\n name = \"Full Name\"\n subdomain = \"zulip\"\n realm = get_realm(\"zulip\")\n realm.invite_required = True\n realm.save()\n\n streams: List[Stream] = []\n\n # Generate an invitation for a different realm than the one we'll attempt to join:\n lear_realm = get_realm(\"lear\")\n multiuse_obj = MultiuseInvite.objects.create(\n realm=lear_realm, referred_by=UserProfile.objects.filter(realm=lear_realm).first()\n )\n multiuse_obj.streams.set(streams)\n validity_in_days = 2\n create_confirmation_link(\n multiuse_obj, Confirmation.MULTIUSE_INVITE, validity_in_days=validity_in_days\n )\n multiuse_confirmation = Confirmation.objects.all().last()\n assert multiuse_confirmation is not None\n multiuse_object_key = multiuse_confirmation.confirmation_key\n account_data_dict = self.get_account_data_dict(email=email, name=name)\n\n # Now we try to use the invitation for the lear realm to join the zulip realm,\n # which should fail.\n result = self.social_auth_test(\n account_data_dict,\n subdomain=subdomain,\n is_signup=True,\n expect_choose_email_screen=True,\n multiuse_object_key=multiuse_object_key,\n )\n\n result = self.client_get(result.url)\n self.assert_in_response(\n \"Whoops. We couldn't find your confirmation link in the system.\", result\n )", "label": 1, "programming_language": "Python", "cwe_id": "CWE-863", "cwe_name": "Incorrect Authorization", "description": "The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.", "url": "https://cwe.mitre.org/data/definitions/863.html", "label_name": "safe"} {"code": " def _get_concealed_token(self, token):\n \"\"\"Returns hashed token to be used as object name in Swift.\n\n Tokens are stored in auth account but object names are visible in Swift\n logs. Object names are hashed from token.\n \"\"\"\n enc_key = \"%s:%s:%s\" % (HASH_PATH_PREFIX, token, HASH_PATH_SUFFIX)\n return sha512(enc_key).hexdigest()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "safe"} {"code": " def sql_insert(self, sentence):\n if type(sentence) is str:\n \tself.cursor.execute(sentence)\n \telse:\n \tself.cursor.execute(sentence[0], sentence[1])\n self.conn.commit()\n return True", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " def test_not_pwned(self):\n fpath = os.path.join(here, 'file', 'pwned.txt')\n vault = self._makeOne('password')\n with ShouldRaise(ConstructorError):\n vault.load(open(fpath).read())", "label": 1, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "safe"} {"code": " def setUp(self):\n super().setUp()\n self.user.is_superuser = True\n self.user.full_name = \"Weblate Test\"\n self.user.save()\n self.maxDiff = None", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " def __init__(self, **kwargs):\n self.basic_auth = get_anymail_setting('webhook_secret', default=[],\n kwargs=kwargs) # no esp_name -- auth is shared between ESPs\n if not self.basic_auth:\n # Temporarily allow deprecated WEBHOOK_AUTHORIZATION setting\n self.basic_auth = get_anymail_setting('webhook_authorization', default=[], kwargs=kwargs)\n\n # Allow a single string:\n if isinstance(self.basic_auth, six.string_types):\n self.basic_auth = [self.basic_auth]\n if self.warn_if_no_basic_auth and len(self.basic_auth) < 1:\n warnings.warn(\n \"Your Anymail webhooks are insecure and open to anyone on the web. \"\n \"You should set WEBHOOK_SECRET in your ANYMAIL settings. \"\n \"See 'Securing webhooks' in the Anymail docs.\",\n AnymailInsecureWebhookWarning)\n # noinspection PyArgumentList\n super(AnymailBasicAuthMixin, self).__init__(**kwargs)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-532", "cwe_name": "Insertion of Sensitive Information into Log File", "description": "Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information.", "url": "https://cwe.mitre.org/data/definitions/532.html", "label_name": "safe"} {"code": " def test_valid(self, args):\n qutebrowser._validate_untrusted_args(args)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-641", "cwe_name": "Improper Restriction of Names for Files and Other Resources", "description": "The application constructs the name of a file or other resource using input from an upstream component, but it does not restrict or incorrectly restricts the resulting name.", "url": "https://cwe.mitre.org/data/definitions/641.html", "label_name": "safe"} {"code": " def make_homeserver(self, reactor, clock):\n hs = self.setup_test_homeserver(\"server\", federation_http_client=None)\n self.handler = hs.get_device_handler()\n self.store = hs.get_datastore()\n return hs", "label": 1, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "safe"} {"code": " def make_homeserver(self, reactor, clock):\n hs = self.setup_test_homeserver(federation_http_client=None)\n self.handler = hs.get_federation_handler()\n self.store = hs.get_datastore()\n return hs", "label": 1, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "safe"} {"code": " def make_homeserver(self, reactor, clock):\n\n self.hs = self.setup_test_homeserver(\n \"red\", federation_http_client=None, federation_client=Mock(),\n )\n\n self.hs.get_federation_handler = Mock()\n self.hs.get_federation_handler.return_value.maybe_backfill = Mock(\n return_value=make_awaitable(None)\n )\n\n async def _insert_client_ip(*args, **kwargs):\n return None\n\n self.hs.get_datastore().insert_client_ip = _insert_client_ip\n\n return self.hs", "label": 1, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "safe"} {"code": " def setUp(self):\n self.reactor = ThreadedMemoryReactorClock()\n self.hs_clock = Clock(self.reactor)\n self.homeserver = setup_test_homeserver(\n self.addCleanup,\n federation_http_client=None,\n clock=self.hs_clock,\n reactor=self.reactor,\n )", "label": 1, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "safe"} {"code": " def read_templates(\n self, filenames: List[str], custom_template_directory: Optional[str] = None,", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " def read_template(self, filename: str) -> jinja2.Template:\n \"\"\"Load a template file from disk.\n\n This function will attempt to load the given template from the default Synapse\n template directory.\n\n Files read are treated as Jinja templates. The templates is not rendered yet\n and has autoescape enabled.\n\n Args:\n filename: A template filename to read.\n\n Raises:\n ConfigError: if the file's path is incorrect or otherwise cannot be read.\n\n Returns:\n A jinja2 template.\n \"\"\"\n return self.read_templates([filename])[0]", "label": 1, "programming_language": "Python", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "def glob_to_regex(glob: str, word_boundary: bool = False) -> Pattern:\n \"\"\"Converts a glob to a compiled regex object.\n\n Args:\n glob: pattern to match\n word_boundary: If True, the pattern will be allowed to match at word boundaries\n anywhere in the string. Otherwise, the pattern is anchored at the start and\n end of the string.\n\n Returns:\n compiled regex pattern\n \"\"\"\n\n # Patterns with wildcards must be simplified to avoid performance cliffs\n # - The glob `?**?**?` is equivalent to the glob `???*`\n # - The glob `???*` is equivalent to the regex `.{3,}`\n chunks = []\n for chunk in _WILDCARD_RUN.split(glob):\n # No wildcards? re.escape()\n if not _WILDCARD_RUN.match(chunk):\n chunks.append(re.escape(chunk))\n continue\n\n # Wildcards? Simplify.\n qmarks = chunk.count(\"?\")\n if \"*\" in chunk:\n chunks.append(\".{%d,}\" % qmarks)\n else:\n chunks.append(\".{%d}\" % qmarks)\n\n res = \"\".join(chunks)\n\n if word_boundary:\n res = re_word_boundary(res)\n else:\n # \\A anchors at start of string, \\Z at end of string\n res = r\"\\A\" + res + r\"\\Z\"\n\n return re.compile(res, re.IGNORECASE)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-331", "cwe_name": "Insufficient Entropy", "description": "The software uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others.", "url": "https://cwe.mitre.org/data/definitions/331.html", "label_name": "safe"} {"code": " def test_image_data_links(self):\n data = b'123'\n data_b64 = base64.b64encode(data).decode('ASCII')\n urls = [\n \"data:image/jpeg;base64,\" + data_b64,\n \"data:image/apng;base64,\" + data_b64,\n \"data:image/png;base64,\" + data_b64,\n \"data:image/gif;base64,\" + data_b64,\n \"data:image/webp;base64,\" + data_b64,\n \"data:image/bmp;base64,\" + data_b64,\n \"data:image/tiff;base64,\" + data_b64,\n \"data:image/x-icon;base64,\" + data_b64,\n ]\n for url in urls:\n html = '' % url\n s = lxml.html.fragment_fromstring(html)\n\n cleaned = lxml.html.tostring(clean_html(s))\n self.assertEqual(\n html.encode(\"UTF-8\"),\n cleaned,\n \"%s -> %s\" % (url, cleaned))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": "def parse(source, filename='', mode='exec', *, type_comments=False):\n \"\"\"\n Parse the source into an AST node.\n Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).\n Pass type_comments=True to get back type comments where the syntax allows.\n \"\"\"\n flags = PyCF_ONLY_AST\n if type_comments:\n flags |= PyCF_TYPE_COMMENTS\n return compile(source, filename, mode, flags)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "def parse(source, filename='', mode='exec', *, type_comments=False):\n \"\"\"\n Parse the source into an AST node.\n Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).\n Pass type_comments=True to get back type comments where the syntax allows.\n \"\"\"\n flags = PyCF_ONLY_AST\n if type_comments:\n flags |= PyCF_TYPE_COMMENTS\n return compile(source, filename, mode, flags)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def test_visitor(self):\n class CustomVisitor(self.asdl.VisitorBase):\n def __init__(self):\n super().__init__()\n self.names_with_seq = []\n\n def visitModule(self, mod):\n for dfn in mod.dfns:\n self.visit(dfn)\n\n def visitType(self, type):\n self.visit(type.value)\n\n def visitSum(self, sum):\n for t in sum.types:\n self.visit(t)\n\n def visitConstructor(self, cons):\n for f in cons.fields:\n if f.seq:\n self.names_with_seq.append(cons.name)\n\n v = CustomVisitor()\n v.visit(self.types['mod'])\n self.assertEqual(v.names_with_seq,\n ['Module', 'Module', 'Interactive', 'FunctionType', 'Suite'])", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def test_level_as_none(self):\n body = [ast.ImportFrom(module='time',\n names=[ast.alias(name='sleep')],\n level=None,\n lineno=0, col_offset=0)]\n mod = ast.Module(body, [])\n code = compile(mod, 'test', 'exec')\n ns = {}\n exec(code, ns)\n self.assertIn('sleep', ns)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def expr(self, node, msg=None, *, exc=ValueError):\n mod = ast.Module([ast.Expr(node)], [])\n self.mod(mod, msg, exc=exc)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def check_both_ways(source):\n ast.parse(source, type_comments=False)\n with self.assertRaises(SyntaxError):\n ast.parse(source, type_comments=True)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def test_ignores(self):\n tree = self.parse(ignores)\n self.assertEqual([ti.lineno for ti in tree.type_ignores], [2, 5])\n tree = self.classic_parse(ignores)\n self.assertEqual(tree.type_ignores, [])", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def test_nonasciidef(self):\n tree = self.parse(nonasciidef)\n self.assertEqual(tree.body[0].type_comment, \"() -> \u00e0\u00e7\u010d\u00e9\u00f1t\")", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def test_parseaddr_multiple_domains(self):\n self.assertEqual(\n utils.parseaddr('a@b@c'),\n ('', '')\n )\n self.assertEqual(\n utils.parseaddr('a@b.c@c'),\n ('', '')\n )\n self.assertEqual(\n utils.parseaddr('a@172.17.0.1@c'),\n ('', '')\n )", "label": 1, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "inline bool AveragePool(const float* input_data, const Dims<4>& input_dims,\n int stride_width, int stride_height, int pad_width,\n int pad_height, int kwidth, int kheight,\n float output_activation_min,\n float output_activation_max, float* output_data,\n const Dims<4>& output_dims) {\n tflite::PoolParams params;\n params.stride_height = stride_height;\n params.stride_width = stride_width;\n params.filter_height = kheight;\n params.filter_width = kwidth;\n params.padding_values.height = pad_height;\n params.padding_values.width = pad_width;\n params.float_activation_min = output_activation_min;\n params.float_activation_max = output_activation_max;\n return AveragePool(params, DimsToShape(input_dims), input_data,\n DimsToShape(output_dims), output_data);\n}", "label": 1, "programming_language": "Python", "cwe_id": "CWE-835", "cwe_name": "Loop with Unreachable Exit Condition ('Infinite Loop')", "description": "The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.", "url": "https://cwe.mitre.org/data/definitions/835.html", "label_name": "safe"} {"code": " def testRaggedMapWithIncorrectFnOutputSignature(self):\n x = ragged_factory_ops.constant([[1, 2, 3, 4], [1]])\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n 'All flat_values must have compatible shapes'):\n y = map_fn_lib.map_fn(lambda r: map_fn_lib.map_fn(lambda y: r, r), x)\n self.evaluate(y)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-681", "cwe_name": "Incorrect Conversion between Numeric Types", "description": "When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur.", "url": "https://cwe.mitre.org/data/definitions/681.html", "label_name": "safe"} {"code": "def model_from_yaml(yaml_string, custom_objects=None):\n \"\"\"Parses a yaml model configuration file and returns a model instance.\n\n Note: Since TF 2.6, this method is no longer supported and will raise a\n RuntimeError.\n\n Args:\n yaml_string: YAML string or open file encoding a model configuration.\n custom_objects: Optional dictionary mapping names\n (strings) to custom classes or functions to be\n considered during deserialization.\n\n Returns:\n A Keras model instance (uncompiled).\n\n Raises:\n RuntimeError: announces that the method poses a security risk\n \"\"\"\n raise RuntimeError(\n 'Method `model_from_yaml()` has been removed due to security risk of '\n 'arbitrary code execution. Please use `Model.to_json()` and '\n '`model_from_json()` instead.'\n )", "label": 1, "programming_language": "Python", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "safe"} {"code": " def testBadSplitSizes(self):\n x = constant_op.constant([1, 2], dtypes.float32)\n with self.assertRaisesRegex((ValueError, errors_impl.InvalidArgumentError),\n \"Determined shape must either match input\"\n \"|can't split axis\"):\n splits = [1, 2]\n self.evaluate(array_ops.split(x, splits, axis=0))", "label": 1, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " def recursive_fn2(n, x):\n if n <= 1:\n return 2 * x\n return n * recursive_fn1(n - 1, x)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-667", "cwe_name": "Improper Locking", "description": "The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.", "url": "https://cwe.mitre.org/data/definitions/667.html", "label_name": "safe"} {"code": " def test_recursive_python_function(self):\n\n def recursive_py_fn(n):\n if n > 0:\n return recursive_py_fn(n - 1)\n return 1\n\n @def_function.function\n def recursive_fn(n):\n return recursive_py_fn(n)\n\n self.assertEqual(recursive_fn(5).numpy(), 1)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-667", "cwe_name": "Improper Locking", "description": "The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.", "url": "https://cwe.mitre.org/data/definitions/667.html", "label_name": "safe"} {"code": " def test_recursive_tf_function(self):\n\n @def_function.function\n def recursive_fn(n):\n if n > 0:\n return recursive_fn(n - 1)\n return 1\n\n self.assertEqual(recursive_fn(5).numpy(), 1)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-667", "cwe_name": "Improper Locking", "description": "The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.", "url": "https://cwe.mitre.org/data/definitions/667.html", "label_name": "safe"} {"code": " def testInvalidShapesEagerGpu(self):\n if not test.is_gpu_available():\n self.skipTest('Test requires GPU')\n self._testErrorWithShapesEager('Input must have rank >= 2, but got ',\n [2], [2], [2], [2])\n self._testErrorWithShapesEager(\n 'superdiag must have same rank as rhs, but got 3 and 2',\n [2, 1, 2], [2, 1], [2, 1], [2, 2])\n self._testErrorWithShapesEager(\n 'maindiag must have same outer dimensions as rhs, but for index 0, got '\n '3 and 2',\n [2, 1, 2], [3, 1, 2], [2, 1, 2], [2, 2, 2])\n self._testErrorWithShapesEager(\n \"subdiag's second-to-last dimension must be 1, but got 3\",\n [2, 1, 2], [2, 1, 2], [2, 3, 2], [2, 2, 2])\n self._testErrorWithShapesEager(\n \"subdiag's last dimension size must be rhs's second-to-last dimension \"\n \"size, but got 3 and 2\",\n [2, 1, 2], [2, 1, 2], [2, 1, 3], [2, 2, 2])", "label": 1, "programming_language": "Python", "cwe_id": "CWE-354", "cwe_name": "Improper Validation of Integrity Check Value", "description": "The software does not validate or incorrectly validates the integrity check values or \"checksums\" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.", "url": "https://cwe.mitre.org/data/definitions/354.html", "label_name": "safe"} {"code": " def testMaxPoolGradEagerShapeErrors(self):\n with context.eager_mode():\n orig_in = array_ops.ones((1, 1, 1, 1))\n\n # Test invalid orig_out shape\n orig_out = array_ops.ones((1, 1, 1, 2))\n grad = array_ops.ones((1, 1, 1, 1))\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected orig_output shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected orig_output shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n\n # Test invalid grad shape\n orig_out = array_ops.ones((1, 1, 1, 1))\n grad = array_ops.ones((1, 1, 1, 2))\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")", "label": 1, "programming_language": "Python", "cwe_id": "CWE-354", "cwe_name": "Improper Validation of Integrity Check Value", "description": "The software does not validate or incorrectly validates the integrity check values or \"checksums\" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.", "url": "https://cwe.mitre.org/data/definitions/354.html", "label_name": "safe"} {"code": " def testBoostedTreesAggregateStatsSecurity(self):\n node_ids = [1, 2]\n gradients = [[]]\n hessians = [[100.0]]\n feature = [[0, 0, 0]]\n max_splits = 100\n num_buckets = 100\n with self.assertRaises((errors.InvalidArgumentError, ValueError)):\n gen_boosted_trees_ops.boosted_trees_aggregate_stats(\n node_ids=node_ids,\n gradients=gradients,\n hessians=hessians,\n feature=feature,\n max_splits=max_splits,\n num_buckets=num_buckets)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": " def testBoostedTreesSparseCalculateBestFeatureSplitSecurity2(self):\n with self.assertRaises((errors.InvalidArgumentError, ValueError)):\n gen_boosted_trees_ops.boosted_trees_sparse_calculate_best_feature_split(\n node_id_range=[0, 1],\n stats_summary_indices=[[0, -1, -1, -1], [1, 0, -1, 0], [1, 0, 0, -1]],\n stats_summary_values=[0.1, 0.2, 0.3],\n stats_summary_shape=[1, 1, 1, 1],\n l1=[0.5],\n l2=[0.5],\n tree_complexity=[0.1],\n min_node_weight=[1.0],\n logits_dimension=1)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": " def testBoostedTreesMakeStatsSummarySecurity2(self):\n node_ids = [1, 2, 3]\n gradients = [[0.1], [0.2]]\n hessians = [[0.2], [0.1]]\n bucketized_features_list = [[1], [2]]\n max_splits = 3\n num_buckets = 3\n with self.assertRaises((errors.InvalidArgumentError, ValueError)):\n gen_boosted_trees_ops.boosted_trees_make_stats_summary(\n node_ids=node_ids,\n gradients=gradients,\n hessians=hessians,\n bucketized_features_list=bucketized_features_list,\n max_splits=max_splits,\n num_buckets=num_buckets)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": " def testEmptySparseTensorSlicesInvalid2(self):\n \"\"\"Test a dataset based on invalid `tf.sparse.SparseTensor`.\"\"\"\n st = array_ops.sparse_placeholder(dtypes.float64)\n iterator = dataset_ops.make_initializable_iterator(\n dataset_ops.Dataset.from_sparse_tensor_slices(st))\n init_op = iterator.initializer\n\n with self.cached_session() as sess:\n # Test with an empty sparse tensor but with non empty values.\n empty_indices = [[]]\n empty_values = []\n dense_shape = [1, 1]\n sparse_feed = sparse_tensor.SparseTensorValue(empty_indices, empty_values,\n dense_shape)\n # Here, we expect the test to fail when running the feed.\n with self.assertRaises(errors.InvalidArgumentError):\n sess.run(init_op, feed_dict={st: sparse_feed})", "label": 1, "programming_language": "Python", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": " def testFlushFunction_disallowsInvalidWriterInput(self):\n with context.eager_mode():\n with self.assertRaisesRegex(ValueError, 'Invalid argument to flush'):\n summary_ops.flush(writer=())", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "def legacy_raw_flush(writer=None, name=None):\n \"\"\"Legacy version of flush() that accepts a raw resource tensor for `writer`.\n\n Do not use this function in any new code. Not supported and not part of the\n public TF APIs.\n\n Args:\n writer: The `tf.summary.SummaryWriter` to flush. If None, the current\n default writer will be used instead; if there is no current writer, this\n returns `tf.no_op`. For this legacy version only, also accepts a raw\n resource tensor pointing to the underlying C++ writer resource.\n name: Ignored legacy argument for a name for the operation.\n\n Returns:\n The created `tf.Operation`.\n \"\"\"\n if writer is None or isinstance(writer, SummaryWriter):\n # Forward to the TF2 implementation of flush() when possible.\n return flush(writer, name)\n else:\n # Legacy fallback in case we were passed a raw resource tensor.\n with ops.device(\"cpu:0\"):\n return gen_summary_ops.flush_summary_writer(writer, name=name)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "def flush(writer=None, name=None):\n \"\"\"Forces summary writer to send any buffered data to storage.\n\n This operation blocks until that finishes.\n\n Args:\n writer: The `tf.summary.SummaryWriter` to flush. If None, the current\n default writer will be used instead; if there is no current writer, this\n returns `tf.no_op`.\n name: Ignored legacy argument for a name for the operation.\n\n Returns:\n The created `tf.Operation`.\n \"\"\"\n del name # unused\n if writer is None:\n writer = _summary_state.writer\n if writer is None:\n return control_flow_ops.no_op()\n if isinstance(writer, SummaryWriter):\n return writer.flush()\n raise ValueError(\"Invalid argument to flush(): %r\" % (writer,))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-475", "cwe_name": "Undefined Behavior for Input to API", "description": "The behavior of this function is undefined unless its control parameter is set to a specific value.", "url": "https://cwe.mitre.org/data/definitions/475.html", "label_name": "safe"} {"code": " def testBadInputSizes(self):\n self._testBadInputSize(\n tin=math_ops.cast(\n constant_op.constant(1, shape=[1, 2]), dtype=dtypes.quint8),\n error_regex=\"must be rank 4\")\n self._testBadInputSize(\n tfilter=math_ops.cast(\n constant_op.constant(1, shape=[1, 2]), dtype=dtypes.quint8),\n error_regex=\"must be rank 4\")\n self._testBadInputSize(\n min_input=constant_op.constant(0, shape=[1], dtype=dtypes.float32),\n error_regex=\"must be rank 0\")\n self._testBadInputSize(\n max_input=constant_op.constant(0, shape=[1], dtype=dtypes.float32),\n error_regex=\"must be rank 0\")\n self._testBadInputSize(\n min_filter=constant_op.constant(0, shape=[1], dtype=dtypes.float32),\n error_regex=\"must be rank 0\")\n self._testBadInputSize(\n max_filter=constant_op.constant(0, shape=[1], dtype=dtypes.float32),\n error_regex=\"must be rank 0\")", "label": 1, "programming_language": "Python", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": " def testValuesInVariable(self):\n indices = constant_op.constant([[0]], dtype=dtypes.int64)\n values = variables.Variable([1], trainable=False, dtype=dtypes.float32)\n shape = constant_op.constant([1], dtype=dtypes.int64)\n\n sp_input = sparse_tensor.SparseTensor(indices, values, shape)\n sp_output = sparse_ops.sparse_add(sp_input, sp_input)\n\n with test_util.force_cpu():\n self.evaluate(variables.global_variables_initializer())\n output = self.evaluate(sp_output)\n self.assertAllEqual(output.values, [2])", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def testValuesInVariable(self):\n indices = constant_op.constant([[0]], dtype=dtypes.int64)\n values = variables.Variable([1], trainable=False, dtype=dtypes.float32)\n shape = constant_op.constant([1], dtype=dtypes.int64)\n\n sp_input = sparse_tensor.SparseTensor(indices, values, shape)\n sp_output = sparse_ops.sparse_add(sp_input, sp_input)\n\n with test_util.force_cpu():\n self.evaluate(variables.global_variables_initializer())\n output = self.evaluate(sp_output)\n self.assertAllEqual(output.values, [2])", "label": 1, "programming_language": "Python", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": " def testRaggedCountSparseOutputBadSplitsEnd(self):\n splits = [0, 5]\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6, 7]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Splits must end with the number of values\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def testRaggedCountSparseOutputBadSplitsEnd(self):\n splits = [0, 5]\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6, 7]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Splits must end with the number of values\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": " def testRaggedCountSparseOutputBadWeightsShape(self):\n splits = [0, 4, 7]\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Weights and values must have the same shape\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def testRaggedCountSparseOutputBadWeightsShape(self):\n splits = [0, 4, 7]\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Weights and values must have the same shape\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def testSparseCountSparseOutputBadIndicesShape(self):\n indices = [[[0], [0]], [[0], [1]], [[1], [0]], [[1], [2]]]\n values = [1, 1, 1, 10]\n weights = [1, 2, 4, 6]\n dense_shape = [2, 3]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Input indices must be a 2-dimensional tensor\"):\n self.evaluate(\n gen_count_ops.SparseCountSparseOutput(\n indices=indices,\n values=values,\n dense_shape=dense_shape,\n weights=weights,\n binary_output=False))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " def testSparseCountSparseOutputBadIndicesShape(self):\n indices = [[[0], [0]], [[0], [1]], [[1], [0]], [[1], [2]]]\n values = [1, 1, 1, 10]\n weights = [1, 2, 4, 6]\n dense_shape = [2, 3]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Input indices must be a 2-dimensional tensor\"):\n self.evaluate(\n gen_count_ops.SparseCountSparseOutput(\n indices=indices,\n values=values,\n dense_shape=dense_shape,\n weights=weights,\n binary_output=False))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def testRaggedCountSparseOutputEmptySplits(self):\n splits = []\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6, 7]\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n \"Must provide at least 2 elements for the splits argument\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def save(self, request, login_code_url='login_code', domain_override=None, extra_context=None):\n login_code = models.LoginCode.create_code_for_user(\n user=self.cleaned_data['user'],\n next=self.cleaned_data['next'],\n )\n\n if not domain_override:\n current_site = get_current_site(request)\n site_name = current_site.name\n domain = current_site.domain\n else:\n site_name = domain = domain_override\n\n url = '{}://{}{}?user={}&code={}'.format(\n 'https' if request.is_secure() else 'http',\n domain,\n resolve_url(login_code_url),\n login_code.user.pk,\n login_code.code,\n )\n\n context = {\n 'domain': domain,\n 'site_name': site_name,\n 'code': login_code.code,\n 'url': url,\n }\n\n if extra_context:\n context.update(extra_context)\n\n self.send_login_code(login_code, context)\n\n return login_code", "label": 1, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "safe"} {"code": " def save(self):\n if self.get_user().login_code:\n self.get_user().login_code.delete()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "safe"} {"code": " def code(self):\n hash_algorithm = getattr(settings, 'NOPASSWORD_HASH_ALGORITHM', 'sha256')\n m = getattr(hashlib, hash_algorithm)()\n m.update(getattr(settings, 'SECRET_KEY', None).encode('utf-8'))\n m.update(str(self.id).encode())\n if getattr(settings, 'NOPASSWORD_NUMERIC_CODES', False):\n hashed = str(int(m.hexdigest(), 16))\n else:\n hashed = m.hexdigest()\n return hashed", "label": 1, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "safe"} {"code": " def test_login(self):\n login_code = LoginCode.objects.create(user=self.user, next='/private/')\n\n response = self.client.post('/accounts-rest/login/code/', {\n 'user': login_code.user.pk,\n 'code': login_code.code,\n })\n\n self.assertEqual(response.status_code, 200)\n self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists())\n\n token = Token.objects.filter(user=self.user).first()\n\n self.assertIsNotNone(token)\n self.assertEqual(response.data, {\n 'key': token.key,\n 'next': '/private/',\n })", "label": 1, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "safe"} {"code": " def test_login_inactive_user(self):\n self.user.is_active = False\n self.user.save()\n\n login_code = LoginCode.objects.create(user=self.user)\n\n response = self.client.post('/accounts-rest/login/code/', {\n 'code': login_code.code,\n })\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json(), {\n '__all__': ['Unable to log in with provided login code.'],\n 'user': ['This field is required.']\n })", "label": 1, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "safe"} {"code": " def test_logout_post(self):\n login_code = LoginCode.objects.create(user=self.user)\n\n self.client.login(username=self.user.username, code=login_code.code)\n\n response = self.client.post('/accounts/logout/?next=/accounts/login/')\n\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response['Location'], '/accounts/login/')\n self.assertTrue(response.wsgi_request.user.is_anonymous)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "safe"} {"code": " def dataReceived(self, data) -> None:\n self._maybe_fail()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "safe"} {"code": " def connectionLost(self, reason) -> None:\n self._maybe_fail()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "safe"} {"code": " def test_can_read_token_from_headers(self):\n \"\"\"Tests that Sydent correctly extracts an auth token from request headers\"\"\"\n self.sydent.run()\n\n request, _ = make_request(\n self.sydent.reactor, \"GET\", \"/_matrix/identity/v2/hash_details\"\n )\n request.requestHeaders.addRawHeader(\n b\"Authorization\", b\"Bearer \" + self.test_token.encode(\"ascii\")\n )\n\n token = tokenFromRequest(request)\n\n self.assertEqual(token, self.test_token)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def test_sydent_rejects_invalid_hostname(self):\n \"\"\"Tests that the /register endpoint rejects an invalid hostname passed as matrix_server_name\"\"\"\n self.sydent.run()\n\n bad_hostname = \"example.com#\"\n\n request, channel = make_request(\n self.sydent.reactor,\n \"POST\",\n \"/_matrix/identity/v2/account/register\",\n content={\n \"matrix_server_name\": bad_hostname,\n \"access_token\": \"foo\"\n })\n\n request.render(self.sydent.servlets.registerServlet)\n\n self.assertEqual(channel.code, 400)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "def is_valid_matrix_server_name(string: str) -> bool:\n \"\"\"Validate that the given string is a valid Matrix server name.\n\n A string is a valid Matrix server name if it is one of the following, plus\n an optional port:\n\n a. IPv4 address\n b. IPv6 literal (`[IPV6_ADDRESS]`)\n c. A valid hostname\n\n :param string: The string to validate\n :type string: str\n\n :return: Whether the input is a valid Matrix server name\n :rtype: bool\n \"\"\"\n\n try:\n host, port = parse_server_name(string)\n except ValueError:\n return False\n\n valid_ipv4_addr = isIPAddress(host)\n valid_ipv6_literal = host[0] == \"[\" and host[-1] == \"]\" and isIPv6Address(host[1:-1])\n\n return valid_ipv4_addr or valid_ipv6_literal or is_valid_hostname(host)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "safe"} {"code": " def test_is_valid_matrix_server_name(self):\n \"\"\"Tests that the is_valid_matrix_server_name function accepts only\n valid hostnames (or domain names), with optional port number.\n \"\"\"\n self.assertTrue(is_valid_matrix_server_name(\"9.9.9.9\"))\n self.assertTrue(is_valid_matrix_server_name(\"9.9.9.9:4242\"))\n self.assertTrue(is_valid_matrix_server_name(\"[::]\"))\n self.assertTrue(is_valid_matrix_server_name(\"[::]:4242\"))\n self.assertTrue(is_valid_matrix_server_name(\"[a:b:c::]:4242\"))\n\n self.assertTrue(is_valid_matrix_server_name(\"example.com\"))\n self.assertTrue(is_valid_matrix_server_name(\"EXAMPLE.COM\"))\n self.assertTrue(is_valid_matrix_server_name(\"ExAmPlE.CoM\"))\n self.assertTrue(is_valid_matrix_server_name(\"example.com:4242\"))\n self.assertTrue(is_valid_matrix_server_name(\"localhost\"))\n self.assertTrue(is_valid_matrix_server_name(\"localhost:9000\"))\n self.assertTrue(is_valid_matrix_server_name(\"a.b.c.d:1234\"))\n\n self.assertFalse(is_valid_matrix_server_name(\"[:::]\"))\n self.assertFalse(is_valid_matrix_server_name(\"a:b:c::\"))\n\n self.assertFalse(is_valid_matrix_server_name(\"example.com:65536\"))\n self.assertFalse(is_valid_matrix_server_name(\"example.com:0\"))\n self.assertFalse(is_valid_matrix_server_name(\"example.com:-1\"))\n self.assertFalse(is_valid_matrix_server_name(\"example.com:a\"))\n self.assertFalse(is_valid_matrix_server_name(\"example.com: \"))\n self.assertFalse(is_valid_matrix_server_name(\"example.com:04242\"))\n self.assertFalse(is_valid_matrix_server_name(\"example.com: 4242\"))\n self.assertFalse(is_valid_matrix_server_name(\"example.com/example.com\"))\n self.assertFalse(is_valid_matrix_server_name(\"example.com#example.com\"))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def resolutionComplete() -> None:\n _callback()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "safe"} {"code": "def _6to4(network: IPNetwork) -> IPNetwork:\n \"\"\"Convert an IPv4 network into a 6to4 IPv6 network per RFC 3056.\"\"\"\n\n # 6to4 networks consist of:\n # * 2002 as the first 16 bits\n # * The first IPv4 address in the network hex-encoded as the next 32 bits\n # * The new prefix length needs to include the bits from the 2002 prefix.\n hex_network = hex(network.first)[2:]\n hex_network = (\"0\" * (8 - len(hex_network))) + hex_network\n return IPNetwork(\n \"2002:%s:%s::/%d\"\n % (\n hex_network[:4],\n hex_network[4:],\n 16 + network.prefixlen,\n )\n )", "label": 1, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def test_federation_client_safe_ip(self, resolver):\n self.sydent.run()\n\n request, channel = make_request(\n self.sydent.reactor,\n \"POST\",\n \"/_matrix/identity/v2/account/register\",\n {\n \"access_token\": \"foo\",\n \"expires_in\": 300,\n \"matrix_server_name\": \"example.com\",\n \"token_type\": \"Bearer\",\n },\n )\n\n resolver.return_value = defer.succeed(\n [\n Server(\n host=self.safe_domain,\n port=443,\n priority=1,\n weight=1,\n expires=100,\n )\n ]\n )\n\n request.render(self.sydent.servlets.registerServlet)\n\n transport, protocol = self._get_http_request(self.safe_ip.decode(\"ascii\"), 443)\n\n self.assertRegex(\n transport.value(), b\"^GET /_matrix/federation/v1/openid/userinfo\"\n )\n self.assertRegex(transport.value(), b\"Host: example.com\")\n\n # Send it the HTTP response\n res_json = '{ \"sub\": \"@test:example.com\" }'.encode(\"ascii\")\n protocol.dataReceived(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Server: Fake\\r\\n\"\n b\"Content-Type: application/json\\r\\n\"\n b\"Content-Length: %i\\r\\n\"\n b\"\\r\\n\"\n b\"%s\" % (len(res_json), res_json)\n )\n\n self.assertEqual(channel.code, 200)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "safe"} {"code": " def attemptRequestWithMaliciousMethod(self, method):\n \"\"\"\n Attempt to send a request with the given method. This should\n synchronously raise a L{ValueError} if either is invalid.\n\n @param method: the method (e.g. C{GET\\x00})\n\n @param uri: the URI\n\n @type method:\n \"\"\"\n raise NotImplementedError()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " def attemptRequestWithMaliciousURI(self, method):\n \"\"\"\n Attempt to send a request with the given URI. This should\n synchronously raise a L{ValueError} if either is invalid.\n\n @param uri: the URI.\n\n @type method:\n \"\"\"\n raise NotImplementedError()", "label": 1, "programming_language": "Python", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " def attemptRequestWithMaliciousURI(self, uri):\n \"\"\"\n Attempt a request with the provided URI.\n\n @param uri: see L{URIInjectionTestsMixin}\n \"\"\"\n client.getPage(uri)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "def test_siblings_cant_talk_remote(econtext):\n mitogen.parent.upgrade_router(econtext)\n test_siblings_cant_talk(econtext.router)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-254", "cwe_name": "7PK - Security Features", "description": "Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.", "url": "https://cwe.mitre.org/data/definitions/254.html", "label_name": "safe"} {"code": " def test_device_update_view_for_other_user_raises_error(self, user, verified_user, rf):\n with override_settings(WAGTAIL_2FA_REQUIRED=True):\n other_device = TOTPDevice.objects.create(name='Initial', user=user, confirmed=True)\n\n device = TOTPDevice.objects.devices_for_user(verified_user, confirmed=True).first()\n request = rf.get('foo')\n request.user = verified_user\n\n with pytest.raises(Http404):\n response = DeviceUpdateView.as_view()(request, pk=other_device.id)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-863", "cwe_name": "Incorrect Authorization", "description": "The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.", "url": "https://cwe.mitre.org/data/definitions/863.html", "label_name": "safe"} {"code": "def test_not_specifiying_wagtail_mount_point_does_not_prepend_allowed_paths_with_wagtail_mount_path(settings):\n settings.WAGTAIL_MOUNT_PATH = ''\n allowed_paths = VerifyUserMiddleware()._get_allowed_paths(has_device=False)\n\n for allowed_path in allowed_paths:\n assert allowed_path.startswith('/cms')", "label": 1, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "def get_header_lines(header):\n \"\"\"\n Splits the header into lines, putting multi-line headers together.\n \"\"\"\n r = []\n lines = header.split(b\"\\r\\n\")\n for line in lines:\n if b\"\\r\" in line or b\"\\n\" in line:\n raise ParsingError('Bare CR or LF found in header line \"%s\"' % tostr(line))\n\n if line.startswith((b\" \", b\"\\t\")):\n if not r:\n # https://corte.si/posts/code/pathod/pythonservers/index.html\n raise ParsingError('Malformed header line \"%s\"' % tostr(line))\n r[-1] += line\n else:\n r.append(line)\n return r", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_received(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n self.assertEqual(inst.server.tasks, [inst])\n self.assertTrue(inst.requests)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_request_body_too_large_with_no_cl_http10_keepalive(self):\n body = \"a\" * self.toobig\n to_send = \"GET / HTTP/1.0\\r\\nConnection: Keep-Alive\\r\\n\\r\\n\"\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (assumed zero)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n line, headers, response_body = read_http(fp)\n # next response overruns because the extra data appears to be\n # header data\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_filelike_shortcl_http11(self):\n to_send = \"GET /filelike_shortcl HTTP/1.1\\r\\n\\r\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\n for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 1)\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\" in response_body)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_notfilelike_iobase_http11(self):\n to_send = \"GET /notfilelike_iobase HTTP/1.1\\r\\n\\r\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\n for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_notfilelike_http11(self):\n to_send = \"GET /notfilelike HTTP/1.1\\r\\n\\r\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\n for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_filelike_longcl_http11(self):\n to_send = \"GET /filelike_longcl HTTP/1.1\\r\\n\\r\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\n for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_http10_generator(self):\n body = string.ascii_letters\n to_send = (\n \"GET / HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: %d\\r\\n\\r\\n\" % len(body)\n )\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"content-length\"), None)\n self.assertEqual(headers.get(\"connection\"), \"close\")\n self.assertEqual(response_body, tobytes(body))\n # remote closed connection (despite keepalive header), because\n # generators cannot have a content-length divined\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def testComplexGET(self):\n data = (\n b\"GET /foo/a+%2B%2F%C3%A4%3D%26a%3Aint?d=b+%2B%2F%3D%26b%3Aint&c+%2B%2F%3D%26c%3Aint=6 HTTP/8.4\\r\\n\"\n b\"FirstName: mickey\\r\\n\"\n b\"lastname: Mouse\\r\\n\"\n b\"content-length: 10\\r\\n\"\n b\"\\r\\n\"\n b\"Hello mickey.\"\n )\n parser = self.parser\n self.feed(data)\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)\n self.assertEqual(\n parser.headers,\n {\"FIRSTNAME\": \"mickey\", \"LASTNAME\": \"Mouse\", \"CONTENT_LENGTH\": \"10\"},\n )\n # path should be utf-8 encoded\n self.assertEqual(\n tobytes(parser.path).decode(\"utf-8\"),\n text_(b\"/foo/a++/\\xc3\\xa4=&a:int\", \"utf-8\"),\n )\n self.assertEqual(\n parser.query, \"d=b+%2B%2F%3D%26b%3Aint&c+%2B%2F%3D%26c%3Aint=6\"\n )\n self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello mick\")", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_received_cl_too_large(self):\n from waitress.utilities import RequestEntityTooLarge\n\n self.parser.adj.max_request_body_size = 2\n data = b\"GET /foobar HTTP/8.4\\r\\nContent-Length: 10\\r\\n\\r\\n\"\n result = self.parser.received(data)\n self.assertEqual(result, 44)\n self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_parse_header_lf_only(self):\n from waitress.parser import ParsingError\n\n data = b\"GET /foobar HTTP/8.4\\nfoo: bar\"\n\n try:\n self.parser.parse_header(data)\n except ParsingError:\n pass\n else: # pragma: nocover\n self.assertTrue(False)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def test_received_control_line_finished_all_chunks_received(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n result = inst.received(b\"0;discard\\r\\n\")\n self.assertEqual(inst.control_line, b\"\")\n self.assertEqual(inst.all_chunks_received, True)\n self.assertEqual(result, 11)\n self.assertEqual(inst.completed, False)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " def _convert_num(self, x):\n \"\"\"Converts numbers to complex if ints are not allowed.\"\"\"\n if self._allow_ints:\n return x\n else:\n x = complex(x)\n if x.imag == 0:\n x = x.real\n # Need to use string-formatting here instead of str() because\n # use of str() on large numbers loses information:\n # str(float(33333333333333)) => '3.33333333333e+13'\n # float('3.33333333333e+13') => 33333333333300.0\n return float('%.16f' % x)\n else:\n return x", "label": 1, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "safe"} {"code": " def emit(self, s, depth, reflow=True):\n # XXX reflow long lines?\n if reflow:\n lines = reflow_lines(s, depth)\n else:\n lines = [s]\n for line in lines:\n if line:\n line = (\" \" * TABSIZE * depth) + line\n self.file.write(line + \"\\n\")", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "def parse(source, filename='', mode='exec', feature_version=LATEST_MINOR_VERSION):\n \"\"\"\n Parse the source into an AST node including type comments.\n Similar to compile(source, filename, mode, PyCF_ONLY_AST).\n\n Set feature_version to limit the syntax parsed to that minor version of\n Python 3. For example, feature_version=5 will prevent new syntax features\n from Python 3.6+ from being used, such as fstrings. Currently only\n fully supported for Python 3.5+ with partial support for Python 3.4.\n So, feature_version=3 or less are all equivalent to feature_version=4.\n\n When feature_version=4, the parser will forbid the use of the async/await\n keywords and the '@' operator, but will not forbid the use of PEP 448\n additional unpacking generalizations, which were also added in Python 3.5.\n\n When feature_version>=7, 'async' and 'await' are always keywords.\n \"\"\"\n return _ast3._parse(source, filename, mode, feature_version)", "label": 1, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "def test_download_http_url__no_directory_traversal(tmpdir):\n \"\"\"\n Test that directory traversal doesn't happen on download when the\n Content-Disposition header contains a filename with a \"..\" path part.\n \"\"\"\n mock_url = 'http://www.example.com/whatever.tgz'\n contents = b'downloaded'\n link = Link(mock_url)\n\n session = Mock()\n resp = MockResponse(contents)\n resp.url = mock_url\n resp.headers = {\n # Set the content-type to a random value to prevent\n # mimetypes.guess_extension from guessing the extension.\n 'content-type': 'random',\n 'content-disposition': 'attachment;filename=\"../out_dir_file\"'\n }\n session.get.return_value = resp\n\n download_dir = tmpdir.join('download')\n os.mkdir(download_dir)\n file_path, content_type = _download_http_url(\n link,\n session,\n download_dir,\n hashes=None,\n progress_bar='on',\n )\n # The file should be downloaded to download_dir.\n actual = os.listdir(download_dir)\n assert actual == ['out_dir_file']", "label": 1, "programming_language": "Python", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " def authenticate(self, username, password):\n child = None\n\n if PY3:\n from shlex import quote\n else:\n from pipes import quote\n\n try:\n child = pexpect.spawn('/bin/sh', ['-c', '/bin/su -c \"/bin/echo SUCCESS\" - %s' % quote(username)], timeout=5)\n child.expect('.*:')\n child.sendline(password)\n result = child.expect(['su: .*', 'SUCCESS'])\n except Exception as err:\n if child and child.isalive():\n child.close()\n logging.error('Error checking password: %s', err)\n return False\n if result == 0:\n return False\n else:\n return True", "label": 1, "programming_language": "Python", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " def traverse(cls, base, request, path_items):\n \"\"\"See ``zope.app.pagetemplate.engine``.\"\"\"\n\n path_items = list(path_items)\n path_items.reverse()\n\n while path_items:\n name = path_items.pop()\n if ITraversable.providedBy(base):\n base = getattr(base, cls.traverseMethod)(name)\n else:\n base = traversePathElement(base, name, path_items,\n request=request)\n\n return base", "label": 0, "programming_language": "Python", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " def test_underscore_traversal(self):\n # Prevent traversal to names starting with an underscore (_)\n ec = self._makeContext()\n\n with self.assertRaises(NotFound):\n ec.evaluate(\"context/__class__\")\n\n with self.assertRaises(NotFound):\n ec.evaluate(\"nocall: random/_itertools/repeat\")\n\n with self.assertRaises(NotFound):\n ec.evaluate(\"random/_itertools/repeat/foobar\")", "label": 0, "programming_language": "Python", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " def build_cert(self, key_filename, entry, metadata):\n \"\"\"\n creates a new certificate according to the specification\n \"\"\"\n req_config = self.build_req_config(entry, metadata)\n req = self.build_request(key_filename, req_config, entry)\n ca = self.cert_specs[entry.get('name')]['ca']\n ca_config = self.CAs[ca]['config']\n days = self.cert_specs[entry.get('name')]['days']\n passphrase = self.CAs[ca].get('passphrase')\n if passphrase:\n cmd = \"openssl ca -config %s -in %s -days %s -batch -passin pass:%s\" % (ca_config,\n req,\n days,\n passphrase)\n else:\n cmd = \"openssl ca -config %s -in %s -days %s -batch\" % (ca_config,\n req,\n days)\n cert = Popen(cmd, shell=True, stdout=PIPE).stdout.read()\n try:\n os.unlink(req_config)\n os.unlink(req)\n except OSError:\n self.logger.error(\"Failed to unlink temporary files\")\n return cert", "label": 0, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def from_plist(self, content):\n \"\"\"\n Given some binary plist data, returns a Python dictionary of the decoded data.\n \"\"\"\n if biplist is None:\n raise ImproperlyConfigured(\"Usage of the plist aspects requires biplist.\")\n \n return biplist.readPlistFromString(content)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "def _inject_metadata_into_fs(metadata, fs, execute=None):\n metadata_path = os.path.join(fs, \"meta.js\")\n metadata = dict([(m.key, m.value) for m in metadata])\n\n utils.execute('tee', metadata_path,\n process_input=jsonutils.dumps(metadata), run_as_root=True)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": " def test_check_unsafe_path(self):\n self.assertRaises(exception.Invalid,\n disk_api._join_and_check_path_within_fs,\n '/foo', 'etc/../../../something.conf')", "label": 0, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": "def _join_and_check_path_within_fs(fs, *args):\n '''os.path.join() with safety check for injected file paths.\n\n Join the supplied path components and make sure that the\n resulting path we are injecting into is within the\n mounted guest fs. Trying to be clever and specifying a\n path with '..' in it will hit this safeguard.\n '''\n absolute_path = os.path.realpath(os.path.join(fs, *args))\n if not absolute_path.startswith(os.path.realpath(fs) + '/'):\n raise exception.Invalid(_('injected file path not valid'))\n return absolute_path", "label": 0, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": " def __init__(self, servers, connect_timeout=CONN_TIMEOUT,\n io_timeout=IO_TIMEOUT, tries=TRY_COUNT):", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " def __init__(self, app, conf):\n self.app = app\n self.memcache_servers = conf.get('memcache_servers')\n if not self.memcache_servers:\n path = os.path.join(conf.get('swift_dir', '/etc/swift'),\n 'memcache.conf')\n memcache_conf = ConfigParser()\n if memcache_conf.read(path):\n try:\n self.memcache_servers = \\\n memcache_conf.get('memcache', 'memcache_servers')\n except (NoSectionError, NoOptionError):\n pass\n if not self.memcache_servers:\n self.memcache_servers = '127.0.0.1:11211'\n self.memcache = MemcacheRing(\n [s.strip() for s in self.memcache_servers.split(',') if s.strip()])", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": "def check_password(password, encoded, setter=None, preferred='default'):\n \"\"\"\n Returns a boolean of whether the raw password matches the three\n part encoded digest.\n\n If setter is specified, it'll be called when you need to\n regenerate the password.\n \"\"\"\n if password is None or not is_password_usable(encoded):\n return False\n\n preferred = get_hasher(preferred)\n hasher = identify_hasher(encoded)\n\n must_update = hasher.algorithm != preferred.algorithm\n if not must_update:\n must_update = preferred.must_update(encoded)\n is_correct = hasher.verify(password, encoded)\n if setter and is_correct and must_update:\n setter(password)\n return is_correct", "label": 0, "programming_language": "Python", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " def CreateID(self):\n \"\"\"Create a packet ID. All RADIUS requests have a ID which is used to\n identify a request. This is used to detect retries and replay attacks.\n This function returns a suitable random number that can be used as ID.\n\n :return: ID number\n :rtype: integer\n\n \"\"\"\n return random.randrange(0, 256)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def CreateAuthenticator():\n \"\"\"Create a packet autenticator. All RADIUS packets contain a sixteen\n byte authenticator which is used to authenticate replies from the\n RADIUS server and in the password hiding algorithm. This function\n returns a suitable random string that can be used as an authenticator.\n\n :return: valid packet authenticator\n :rtype: binary string\n \"\"\"\n\n data = []\n for i in range(16):\n data.append(random.randrange(0, 256))\n if six.PY3:\n return bytes(data)\n else:\n return ''.join(chr(b) for b in data)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-330", "cwe_name": "Use of Insufficiently Random Values", "description": "The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.", "url": "https://cwe.mitre.org/data/definitions/330.html", "label_name": "vulnerable"} {"code": " def build(self):\n g = Grammar(self.tokens)\n\n for level, (assoc, terms) in enumerate(self.precedence, 1):\n for term in terms:\n g.set_precedence(term, assoc, level)\n\n for prod_name, syms, func, precedence in self.productions:\n g.add_production(prod_name, syms, func, precedence)\n\n g.set_start()\n\n for unused_term in g.unused_terminals():\n warnings.warn(\n \"Token %r is unused\" % unused_term,\n ParserGeneratorWarning,\n stacklevel=2\n )\n for unused_prod in g.unused_productions():\n warnings.warn(\n \"Production %r is not reachable\" % unused_prod,\n ParserGeneratorWarning,\n stacklevel=2\n )\n\n g.build_lritems()\n g.compute_first()\n g.compute_follow()\n\n cache_file = os.path.join(\n tempfile.gettempdir(),\n \"rply-%s-%s-%s.json\" % (self.VERSION, self.cache_id, self.compute_grammar_hash(g))\n )\n table = None\n if os.path.exists(cache_file):\n with open(cache_file) as f:\n data = json.load(f)\n if self.data_is_valid(g, data):\n table = LRTable.from_cache(g, data)\n if table is None:\n table = LRTable.from_grammar(g)\n with open(cache_file, \"w\") as f:\n json.dump(self.serialize_table(table), f)\n if table.sr_conflicts:\n warnings.warn(\n \"%d shift/reduce conflict%s\" % (len(table.sr_conflicts), \"s\" if len(table.sr_conflicts) > 1 else \"\"),\n ParserGeneratorWarning,\n stacklevel=2,\n )\n if table.rr_conflicts:\n warnings.warn(\n \"%d reduce/reduce conflict%s\" % (len(table.rr_conflicts), \"s\" if len(table.rr_conflicts) > 1 else \"\"),\n ParserGeneratorWarning,\n stacklevel=2,\n )\n return LRParser(table, self.error_handler)", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": " def test_roundtrip_file(self):\n f = open(self.filename, 'wb')\n self.x.tofile(f)\n f.close()\n # NB. doesn't work with flush+seek, due to use of C stdio\n f = open(self.filename, 'rb')\n y = np.fromfile(f, dtype=self.dtype)\n f.close()\n assert_array_equal(y, self.x.flat)\n os.unlink(self.filename)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "def Ghostscript(tile, size, fp, scale=1):\n \"\"\"Render an image using Ghostscript\"\"\"\n\n # Unpack decoder tile\n decoder, tile, offset, data = tile[0]\n length, bbox = data\n\n #Hack to support hi-res rendering\n scale = int(scale) or 1\n orig_size = size\n orig_bbox = bbox\n size = (size[0] * scale, size[1] * scale)\n bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]\n #print(\"Ghostscript\", scale, size, orig_size, bbox, orig_bbox)\n\n import tempfile, os, subprocess\n\n file = tempfile.mktemp()\n\n # Build ghostscript command\n command = [\"gs\",\n \"-q\", # quite mode\n \"-g%dx%d\" % size, # set output geometry (pixels)\n \"-r%d\" % (72*scale), # set input DPI (dots per inch)\n \"-dNOPAUSE -dSAFER\", # don't pause between pages, safe mode\n \"-sDEVICE=ppmraw\", # ppm driver\n \"-sOutputFile=%s\" % file,# output file\n ]\n\n if gs_windows_binary is not None:\n if gs_windows_binary is False:\n raise WindowsError('Unable to locate Ghostscript on paths')\n command[0] = gs_windows_binary\n\n # push data through ghostscript\n try:\n gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n # adjust for image origin\n if bbox[0] != 0 or bbox[1] != 0:\n gs.stdin.write((\"%d %d translate\\n\" % (-bbox[0], -bbox[1])).encode('ascii'))\n fp.seek(offset)\n while length > 0:\n s = fp.read(8192)\n if not s:\n break\n length = length - len(s)\n gs.stdin.write(s)\n gs.stdin.close()\n status = gs.wait()\n if status:\n raise IOError(\"gs failed (status %d)\" % status)\n im = Image.core.open_ppm(file)\n finally:\n try: os.unlink(file)\n except: pass\n\n return im", "label": 0, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": " def _dump(self, file=None, format=None):\n import tempfile\n if not file:\n file = tempfile.mktemp()\n self.load()\n if not format or format == \"PPM\":\n self.im.save_ppm(file)\n else:\n file = file + \".\" + format\n self.save(file, format)\n return file", "label": 0, "programming_language": "Python", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": " def load(self):\n\n if len(self.tile) != 1 or self.tile[0][0] != \"iptc\":\n return ImageFile.ImageFile.load(self)\n\n type, tile, box = self.tile[0]\n\n encoding, offset = tile\n\n self.fp.seek(offset)\n\n # Copy image data to temporary file\n outfile = tempfile.mktemp()\n o = open(outfile, \"wb\")\n if encoding == \"raw\":\n # To simplify access to the extracted file,\n # prepend a PPM header\n o.write(\"P5\\n%d %d\\n255\\n\" % self.size)\n while True:\n type, size = self.field()\n if type != (8, 10):\n break\n while size > 0:\n s = self.fp.read(min(size, 8192))\n if not s:\n break\n o.write(s)\n size = size - len(s)\n o.close()\n\n try:\n try:\n # fast\n self.im = Image.core.open_ppm(outfile)\n except:\n # slightly slower\n im = Image.open(outfile)\n im.load()\n self.im = im.im\n finally:\n try: os.unlink(outfile)\n except: pass", "label": 0, "programming_language": "Python", "cwe_id": "CWE-59", "cwe_name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.", "url": "https://cwe.mitre.org/data/definitions/59.html", "label_name": "vulnerable"} {"code": "def clean_id(id_):\n '''\n Returns if the passed id is clean.\n '''\n if re.search(r'\\.\\.\\{sep}'.format(sep=os.sep), id_):\n return False\n return True", "label": 0, "programming_language": "Python", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " def test_show_student_extensions(self):\n self.test_change_due_date()\n url = reverse('show_student_extensions',\n kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {'student': self.user1.username})\n self.assertEqual(response.status_code, 200, response.content)\n self.assertEqual(json.loads(response.content), {\n u'data': [{u'Extended Due Date': u'2013-12-30 00:00',\n u'Unit': self.week1.display_name}],\n u'header': [u'Unit', u'Extended Due Date'],\n u'title': u'Due date extensions for %s (%s)' % (\n self.user1.profile.name, self.user1.username)})", "label": 0, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " def test_rescore_problem_all(self, act):\n \"\"\" Test rescoring for all students. \"\"\"\n url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': self.problem_urlname,\n 'all_students': True,\n })\n self.assertEqual(response.status_code, 200)\n self.assertTrue(act.called)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " def test_list_instructor_tasks_problem(self, act):\n \"\"\" Test list task history for problem. \"\"\"\n act.return_value = self.tasks\n url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})\n mock_factory = MockCompletionInfo()\n with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:\n mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info\n response = self.client.get(url, {\n 'problem_location_str': self.problem_urlname,\n })\n self.assertEqual(response.status_code, 200)\n\n # check response\n self.assertTrue(act.called)\n expected_tasks = [ftask.to_dict() for ftask in self.tasks]\n actual_tasks = json.loads(response.content)['tasks']\n for exp_task, act_task in zip(expected_tasks, actual_tasks):\n self.assertDictEqual(exp_task, act_task)\n self.assertEqual(actual_tasks, expected_tasks)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " def register_with_redemption_code(self, user, code):\n \"\"\"\n enroll user using a registration code\n \"\"\"\n redeem_url = reverse('register_code_redemption', args=[code])\n self.client.login(username=user.username, password='test')\n response = self.client.get(redeem_url)\n self.assertEquals(response.status_code, 200)\n # check button text\n self.assertTrue('Activate Course Enrollment' in response.content)\n\n response = self.client.post(redeem_url)\n self.assertEquals(response.status_code, 200)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " def test_list_report_downloads(self):\n url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()})\n with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for:\n mock_links_for.return_value = [\n ('mock_file_name_1', 'https://1.mock.url'),\n ('mock_file_name_2', 'https://2.mock.url'),\n ]\n response = self.client.get(url, {})\n\n expected_response = {\n \"downloads\": [\n {\n \"url\": \"https://1.mock.url\",\n \"link\": \"mock_file_name_1\",\n \"name\": \"mock_file_name_1\"\n },\n {\n \"url\": \"https://2.mock.url\",\n \"link\": \"mock_file_name_2\",\n \"name\": \"mock_file_name_2\"\n }\n ]\n }\n res_json = json.loads(response.content)\n self.assertEqual(res_json, expected_response)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " def get_email_content_response(self, num_emails, task_history_request, with_failures=False):\n \"\"\" Calls the list_email_content endpoint and returns the repsonse \"\"\"\n self.setup_fake_email_info(num_emails, with_failures)\n task_history_request.return_value = self.tasks.values()\n url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})\n with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:\n mock_email_info.side_effect = self.get_matching_mock_email\n response = self.client.get(url, {})\n self.assertEqual(response.status_code, 200)\n return response", "label": 0, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": "def rescore_problem(request, course_id):\n \"\"\"\n Starts a background process a students attempts counter. Optionally deletes student state for a problem.\n Limited to instructor access.\n\n Takes either of the following query paremeters\n - problem_to_reset is a urlname of a problem\n - unique_student_identifier is an email or username\n - all_students is a boolean\n\n all_students and unique_student_identifier cannot both be present.\n \"\"\"\n course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)\n problem_to_reset = strip_if_string(request.GET.get('problem_to_reset'))\n student_identifier = request.GET.get('unique_student_identifier', None)\n student = None\n if student_identifier is not None:\n student = get_student_from_identifier(student_identifier)\n\n all_students = request.GET.get('all_students') in ['true', 'True', True]\n\n if not (problem_to_reset and (all_students or student)):\n return HttpResponseBadRequest(\"Missing query parameters.\")\n\n if all_students and student:\n return HttpResponseBadRequest(\n \"Cannot rescore with all_students and unique_student_identifier.\"\n )\n\n try:\n module_state_key = course_id.make_usage_key_from_deprecated_string(problem_to_reset)\n except InvalidKeyError:\n return HttpResponseBadRequest(\"Unable to parse problem id\")\n\n response_payload = {}\n response_payload['problem_to_reset'] = problem_to_reset\n\n if student:\n response_payload['student'] = student_identifier\n instructor_task.api.submit_rescore_problem_for_student(request, module_state_key, student)\n response_payload['task'] = 'created'\n elif all_students:\n instructor_task.api.submit_rescore_problem_for_all_students(request, module_state_key)\n response_payload['task'] = 'created'\n else:\n return HttpResponseBadRequest()\n\n return JsonResponse(response_payload)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": "def reset_due_date(request, course_id):\n \"\"\"\n Rescinds a due date extension for a student on a particular unit.\n \"\"\"\n course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))\n student = require_student_from_identifier(request.GET.get('student'))\n unit = find_unit(course, request.GET.get('url'))\n set_due_date_extension(course, unit, student, None)\n if not getattr(unit, \"due\", None):\n # It's possible the normal due date was deleted after an extension was granted:\n return JsonResponse(\n _(\"Successfully removed invalid due date extension (unit has no due date).\")\n )\n\n original_due_date_str = unit.due.strftime('%Y-%m-%d %H:%M')\n return JsonResponse(_(\n 'Successfully reset due date for student {0} for {1} '\n 'to {2}').format(student.profile.name, _display_unit(unit),\n original_due_date_str))", "label": 0, "programming_language": "Python", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " def PUT(self, path, body, ensure_encoding=True, log_request_body=True):\n return self._request('PUT', path, body=body, ensure_encoding=ensure_encoding,\n log_request_body=log_request_body)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": " def update(self, **kwargs):\n consumer_id = load_consumer_id(self.context)\n if not consumer_id:\n self.prompt.render_failure_message(\"This consumer is not registered to the Pulp server.\")\n return\n\n delta = dict([(k, v) for k, v in kwargs.items() if v is not None])\n if 'note' in delta.keys():\n if delta['note']:\n delta['notes'] = args_to_notes_dict(kwargs['note'], include_none=False)\n delta.pop('note')\n # convert display-name to display_name\n key = 'display-name'\n if key in delta:\n v = delta.pop(key)\n key = key.replace('-', '_')\n delta[key] = v\n\n if kwargs.get(OPTION_EXCHANGE_KEYS.keyword):\n path = self.context.config['authentication']['rsa_pub']\n fp = open(path)\n try:\n delta['rsa_pub'] = fp.read()\n finally:\n fp.close()\n\n try:\n self.context.server.consumer.update(consumer_id, delta)\n self.prompt.render_success_message('Consumer [%s] successfully updated' % consumer_id)\n if not kwargs.get(OPTION_EXCHANGE_KEYS.keyword):\n return\n try:\n update_server_key(self.context.config)\n except Exception, e:\n msg = _('Download server RSA key failed [%(e)s]' % {'e': e})\n self.prompt.render_failure_message(msg)\n except NotFoundException:\n self.prompt.write('Consumer [%s] does not exist on the server' % consumer_id, tag='not-found')", "label": 0, "programming_language": "Python", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": "def index():\n \"\"\" Index handler \"\"\"\n\n send = request.vars.send\n if DEMO_MODE:\n session.authorized = True\n session.last_time = t0\n if not send:\n send = URL('site')\n if session.authorized:\n redirect(send)\n elif failed_login_count() >= allowed_number_of_attempts:\n time.sleep(2 ** allowed_number_of_attempts)\n raise HTTP(403)\n elif request.vars.password:\n if verify_password(request.vars.password[:1024]):\n session.authorized = True\n login_record(True)\n\n if CHECK_VERSION:\n session.check_version = True\n else:\n session.check_version = False\n\n session.last_time = t0\n if isinstance(send, list): # ## why does this happen?\n send = str(send[0])\n\n redirect(send)\n else:\n times_denied = login_record(False)\n if times_denied >= allowed_number_of_attempts:\n response.flash = \\\n T('admin disabled because too many invalid login attempts')\n elif times_denied == allowed_number_of_attempts - 1:\n response.flash = \\\n T('You have one more login attempt before you are locked out')\n else:\n response.flash = T('invalid password.')\n return dict(send=send)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "vulnerable"} {"code": "def class_instances_from_soap_enveloped_saml_thingies(text, modules):\n \"\"\"Parses a SOAP enveloped header and body SAML thing and returns the\n thing as a dictionary class instance.\n\n :param text: The SOAP object as XML\n :param modules: modules representing xsd schemas\n :return: The body and headers as class instances\n \"\"\"\n try:\n envelope = ElementTree.fromstring(text)\n except Exception as exc:\n raise XmlParseError(\"%s\" % exc)\n\n assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n env = {\"header\": [], \"body\": None}\n\n for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n env[\"body\"] = instanciate_class(part[0], modules)\n elif part.tag == \"{%s}Header\" % soapenv.NAMESPACE:\n for item in part:\n env[\"header\"].append(instanciate_class(item, modules))\n\n return env", "label": 0, "programming_language": "Python", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " def append(self, key, value):\n self.dict.setdefault(_hkey(key), []).append(\n value if isinstance(value, unicode) else str(value))", "label": 0, "programming_language": "Python", "cwe_id": "CWE-93", "cwe_name": "Improper Neutralization of CRLF Sequences ('CRLF Injection')", "description": "The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs.", "url": "https://cwe.mitre.org/data/definitions/93.html", "label_name": "vulnerable"} {"code": " def get(cls, uuid):\n \"\"\"Return a `Resource` instance of this class identified by\n the given code or UUID.\n\n Only `Resource` classes with specified `member_path` attributes\n can be directly requested with this method.\n\n \"\"\"\n url = urljoin(recurly.base_uri(), cls.member_path % (uuid,))\n resp, elem = cls.element_for_url(url)\n return cls.from_element(elem)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def _keyify(key):\n return _key_pattern.sub(' ', key.lower())", "label": 0, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": "def home_get_preview():\n vId = request.form['vId']\n d = db.sentences_stats('get_preview', vId)\n n = db.sentences_stats('id_networks', vId)\n return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n});", "label": 0, "programming_language": "Python", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "def home_get_preview():\n vId = request.form['vId']\n d = db.sentences_stats('get_preview', vId)\n n = db.sentences_stats('id_networks', vId)\n return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n});", "label": 0, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " def test_credits_view_json(self):\n response = self.get_credits(\"json\")\n self.assertEqual(response.status_code, 200)\n self.assertJSONEqual(\n response.content.decode(),\n [{\"Czech\": [[\"weblate@example.org\", \"Weblate Test\", 1]]}],\n )", "label": 0, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " def __init__(self, hs):\n self.hs = hs\n self.auth = hs.get_auth()\n self.client = hs.get_http_client()\n self.clock = hs.get_clock()\n self.server_name = hs.hostname\n self.store = hs.get_datastore()\n self.max_upload_size = hs.config.max_upload_size\n self.max_image_pixels = hs.config.max_image_pixels\n\n self.primary_base_path = hs.config.media_store_path\n self.filepaths = MediaFilePaths(self.primary_base_path)\n\n self.dynamic_thumbnails = hs.config.dynamic_thumbnails\n self.thumbnail_requirements = hs.config.thumbnail_requirements\n\n self.remote_media_linearizer = Linearizer(name=\"media_remote\")\n\n self.recently_accessed_remotes = set()\n self.recently_accessed_locals = set()\n\n self.federation_domain_whitelist = hs.config.federation_domain_whitelist\n\n # List of StorageProviders where we should search for media and\n # potentially upload to.\n storage_providers = []\n\n for clz, provider_config, wrapper_config in hs.config.media_storage_providers:\n backend = clz(hs, provider_config)\n provider = StorageProviderWrapper(\n backend,\n store_local=wrapper_config.store_local,\n store_remote=wrapper_config.store_remote,\n store_synchronous=wrapper_config.store_synchronous,\n )\n storage_providers.append(provider)\n\n self.media_storage = MediaStorage(\n self.hs, self.primary_base_path, self.filepaths, storage_providers\n )\n\n self.clock.looping_call(\n self._start_update_recently_accessed, UPDATE_RECENTLY_ACCESSED_TS\n )", "label": 0, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "vulnerable"} {"code": " def test_stopped_typing(self):\n self.room_members = [U_APPLE, U_BANANA, U_ONION]\n\n # Gut-wrenching\n from synapse.handlers.typing import RoomMember\n\n member = RoomMember(ROOM_ID, U_APPLE.to_string())\n self.handler._member_typing_until[member] = 1002000\n self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()}\n\n self.assertEquals(self.event_source.get_current_key(), 0)\n\n self.get_success(\n self.handler.stopped_typing(\n target_user=U_APPLE,\n requester=create_requester(U_APPLE),\n room_id=ROOM_ID,\n )\n )\n\n self.on_new_event.assert_has_calls([call(\"typing_key\", 1, rooms=[ROOM_ID])])\n\n put_json = self.hs.get_http_client().put_json\n put_json.assert_called_once_with(\n \"farm\",\n path=\"/_matrix/federation/v1/send/1000000\",\n data=_expect_edu_transaction(\n \"m.typing\",\n content={\n \"room_id\": ROOM_ID,\n \"user_id\": U_APPLE.to_string(),\n \"typing\": False,\n },\n ),\n json_data_callback=ANY,\n long_retries=True,\n backoff_on_404=True,\n try_trailing_slash_on_400=True,\n )\n\n self.assertEquals(self.event_source.get_current_key(), 1)\n events = self.get_success(\n self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)\n )\n self.assertEquals(\n events[0],\n [{\"type\": \"m.typing\", \"room_id\": ROOM_ID, \"content\": {\"user_ids\": []}}],\n )", "label": 0, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "vulnerable"} {"code": " def make_homeserver(self, reactor, clock):\n self.http_client = Mock()\n return self.setup_test_homeserver(http_client=self.http_client)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "vulnerable"} {"code": " async def on_send_join_request(\n self, origin: str, content: JsonDict, room_id: str", "label": 0, "programming_language": "Python", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " def read_config(self, config, **kwargs):\n consent_config = config.get(\"user_consent\")\n self.terms_template = self.read_templates([\"terms.html\"], autoescape=True)[0]\n\n if consent_config is None:\n return\n self.user_consent_version = str(consent_config[\"version\"])\n self.user_consent_template_dir = self.abspath(consent_config[\"template_dir\"])\n if not path.isdir(self.user_consent_template_dir):\n raise ConfigError(\n \"Could not find template directory '%s'\"\n % (self.user_consent_template_dir,)\n )\n self.user_consent_server_notice_content = consent_config.get(\n \"server_notice_content\"\n )\n self.block_events_without_consent_error = consent_config.get(\n \"block_events_error\"\n )\n self.user_consent_server_notice_to_guests = bool(\n consent_config.get(\"send_server_notice_to_guests\", False)\n )\n self.user_consent_at_registration = bool(\n consent_config.get(\"require_at_registration\", False)\n )\n self.user_consent_policy_name = consent_config.get(\n \"policy_name\", \"Privacy Policy\"\n )", "label": 0, "programming_language": "Python", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": " def test_bad_integer(self):\n # issue13436: Bad error message with invalid numeric values\n body = [ast.ImportFrom(module='time',\n names=[ast.alias(name='sleep')],\n level=None,\n lineno=None, col_offset=None)]\n mod = ast.Module(body)\n with self.assertRaises(ValueError) as cm:\n compile(mod, 'test', 'exec')\n self.assertIn(\"invalid integer value: None\", str(cm.exception))", "label": 0, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "def model_from_config(config, custom_objects=None):\n \"\"\"Instantiates a Keras model from its config.\n \n Usage:\n ```\n # for a Functional API model\n tf.keras.Model().from_config(model.get_config())\n\n # for a Sequential model\n tf.keras.Sequential().from_config(model.get_config())\n ```\n\n Args:\n config: Configuration dictionary.\n custom_objects: Optional dictionary mapping names\n (strings) to custom classes or functions to be\n considered during deserialization.\n\n Returns:\n A Keras model instance (uncompiled).\n\n Raises:\n TypeError: if `config` is not a dictionary.\n \"\"\"\n if isinstance(config, list):\n raise TypeError('`model_from_config` expects a dictionary, not a list. '\n 'Maybe you meant to use '\n '`Sequential.from_config(config)`?')\n from tensorflow.python.keras.layers import deserialize # pylint: disable=g-import-not-at-top\n return deserialize(config, custom_objects=custom_objects)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "vulnerable"} {"code": " def testDictionary(self):\n with ops.Graph().as_default() as G:\n with ops.device('/cpu:0'):\n x = array_ops.placeholder(dtypes.float32)\n pi = array_ops.placeholder(dtypes.int64)\n gi = array_ops.placeholder(dtypes.int64)\n v = 2. * (array_ops.zeros([128, 128]) + x)\n with ops.device(test.gpu_device_name()):\n stager = data_flow_ops.MapStagingArea(\n [dtypes.float32, dtypes.float32],\n shapes=[[], [128, 128]],\n names=['x', 'v'])\n stage = stager.put(pi, {'x': x, 'v': v})\n key, ret = stager.get(gi)\n z = ret['x']\n y = ret['v']\n y = math_ops.reduce_max(z * math_ops.matmul(y, y))\n\n G.finalize()\n\n with self.session(graph=G) as sess:\n sess.run(stage, feed_dict={x: -1, pi: 0})\n for i in range(10):\n _, yval = sess.run([stage, y], feed_dict={x: i, pi: i + 1, gi: i})\n self.assertAllClose(\n 4 * (i - 1) * (i - 1) * (i - 1) * 128, yval, rtol=1e-4)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-843", "cwe_name": "Access of Resource Using Incompatible Type ('Type Confusion')", "description": "The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.", "url": "https://cwe.mitre.org/data/definitions/843.html", "label_name": "vulnerable"} {"code": " def testSimple(self):\n with ops.Graph().as_default() as G:\n with ops.device('/cpu:0'):\n x = array_ops.placeholder(dtypes.float32)\n pi = array_ops.placeholder(dtypes.int64)\n gi = array_ops.placeholder(dtypes.int64)\n v = 2. * (array_ops.zeros([128, 128]) + x)\n with ops.device(test.gpu_device_name()):\n stager = data_flow_ops.MapStagingArea([dtypes.float32])\n stage = stager.put(pi, [v], [0])\n k, y = stager.get(gi)\n y = math_ops.reduce_max(math_ops.matmul(y, y))\n\n G.finalize()\n\n with self.session(graph=G) as sess:\n sess.run(stage, feed_dict={x: -1, pi: 0})\n for i in range(10):\n _, yval = sess.run([stage, y], feed_dict={x: i, pi: i + 1, gi: i})\n self.assertAllClose(4 * (i - 1) * (i - 1) * 128, yval, rtol=1e-4)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-843", "cwe_name": "Access of Resource Using Incompatible Type ('Type Confusion')", "description": "The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.", "url": "https://cwe.mitre.org/data/definitions/843.html", "label_name": "vulnerable"} {"code": " def testRunCommandInvalidSignature(self, use_tfrt):\n self.parser = saved_model_cli.create_parser()\n base_path = test.test_src_dir_path(SAVED_MODEL_PATH)\n args = self.parser.parse_args([\n 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def',\n 'INVALID_SIGNATURE', '--input_exprs', 'x2=np.ones((3,1))'\n ] + (['--use_tfrt'] if use_tfrt else []))\n with self.assertRaisesRegex(ValueError,\n 'Could not find signature \"INVALID_SIGNATURE\"'):\n saved_model_cli.run(args)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " def testRunCommandInvalidInputKeyError(self, use_tfrt):\n self.parser = saved_model_cli.create_parser()\n base_path = test.test_src_dir_path(SAVED_MODEL_PATH)\n args = self.parser.parse_args([\n 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def',\n 'regress_x2_to_y3', '--input_exprs', 'x2=np.ones((3,1))'\n ] + (['--use_tfrt'] if use_tfrt else []))\n with self.assertRaises(ValueError):\n saved_model_cli.run(args)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " def testInputParserBothDuplicate(self):\n x0 = np.array([[1], [2]])\n input_path = os.path.join(test.get_temp_dir(), 'input.npz')\n np.savez(input_path, a=x0)\n x1 = np.ones([2, 10])\n input_str = 'x0=' + input_path + '[a]'\n input_expr_str = 'x0=np.ones([2,10])'\n feed_dict = saved_model_cli.load_inputs_from_input_arg_string(\n input_str, input_expr_str, '')\n self.assertTrue(np.all(feed_dict['x0'] == x1))", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " def test_template_render_with_noautoescape(self):\n \"\"\"\n Test if the autoescape value is getting passed to urlize_quoted_links filter.\n \"\"\"\n template = Template(\"{% load rest_framework %}\"\n \"{% autoescape off %}{{ content|urlize_quoted_links }}\"\n \"{% endautoescape %}\")\n rendered = template.render(Context({'content': '\"http://example.com\"'}))\n assert rendered == '\"http://example.com\"'", "label": 0, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " def generate_code(cls):\n hash_algorithm = getattr(settings, 'NOPASSWORD_HASH_ALGORITHM', 'sha256')\n m = getattr(hashlib, hash_algorithm)()\n m.update(getattr(settings, 'SECRET_KEY', None).encode('utf-8'))\n m.update(os.urandom(16))\n if getattr(settings, 'NOPASSWORD_NUMERIC_CODES', False):\n hashed = str(int(m.hexdigest(), 16))\n else:\n hashed = m.hexdigest()\n return hashed", "label": 0, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "vulnerable"} {"code": " def test_logout_unknown_token(self):\n login_code = LoginCode.objects.create(user=self.user, code='foobar')\n\n self.client.login(username=self.user.username, code=login_code.code)\n\n response = self.client.post(\n '/accounts-rest/logout/',\n HTTP_AUTHORIZATION='Token unknown',\n )\n\n self.assertEqual(response.status_code, 200)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "vulnerable"} {"code": " def test_login_inactive_user(self):\n self.user.is_active = False\n self.user.save()\n\n login_code = LoginCode.objects.create(user=self.user, code='foobar')\n\n response = self.client.post('/accounts/login/code/', {\n 'code': login_code.code,\n })\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context['form'].errors, {\n 'code': ['Unable to log in with provided login code.'],\n })", "label": 0, "programming_language": "Python", "cwe_id": "CWE-312", "cwe_name": "Cleartext Storage of Sensitive Information", "description": "The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.", "url": "https://cwe.mitre.org/data/definitions/312.html", "label_name": "vulnerable"} {"code": "def manipulate(root, strblock):\n \"\"\"\n Maliciously manipulates the structure to create a crafted FIT file\n \"\"\"\n # locate /images/kernel@1 (frankly, it just expects it to be the first one)\n kernel_node = root[0][0]\n # clone it to save time filling all the properties\n fake_kernel = kernel_node.clone()\n # rename the node\n fake_kernel.name = b'kernel@2'\n # get rid of signatures/hashes\n fake_kernel.children = []\n # NOTE: this simply replaces the first prop... either description or data\n # should be good for testing purposes\n fake_kernel.props[0].value = b'Super 1337 kernel\\x00'\n # insert the new kernel node under /images\n root[0].children.append(fake_kernel)\n\n # modify the default configuration\n root[1].props[0].value = b'conf@2\\x00'\n # clone the first (only?) configuration\n fake_conf = root[1][0].clone()\n # rename and change kernel and fdt properties to select the crafted kernel\n fake_conf.name = b'conf@2'\n fake_conf.props[0].value = b'kernel@2\\x00'\n fake_conf.props[1].value = b'fdt@1\\x00'\n # insert the new configuration under /configurations\n root[1].children.append(fake_conf)\n\n return root, strblock", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " def test_can_read_token_from_query_parameters(self):\n \"\"\"Tests that Sydent correct extracts an auth token from query parameters\"\"\"\n self.sydent.run()\n\n request, _ = make_request(\n self.sydent.reactor, \"GET\",\n \"/_matrix/identity/v2/hash_details?access_token=\" + self.test_token\n )\n\n token = tokenFromRequest(request)\n\n self.assertEqual(token, self.test_token)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "def is_valid_hostname(string: str) -> bool:\n \"\"\"Validate that a given string is a valid hostname or domain name, with an\n optional port number.\n\n For domain names, this only validates that the form is right (for\n instance, it doesn't check that the TLD is valid). If a port is\n specified, it has to be a valid port number.\n\n :param string: The string to validate\n :type string: str\n\n :return: Whether the input is a valid hostname\n :rtype: bool\n \"\"\"\n\n host_parts = string.split(\":\", 1)\n\n if len(host_parts) == 1:\n return hostname_regex.match(string) is not None\n else:\n host, port = host_parts\n valid_hostname = hostname_regex.match(host) is not None\n\n try:\n port_num = int(port)\n valid_port = (\n port == str(port_num) # exclude things like '08090' or ' 8090'\n and 1 <= port_num < 65536)\n except ValueError:\n valid_port = False\n\n return valid_hostname and valid_port", "label": 0, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def test_is_valid_hostname(self):\n \"\"\"Tests that the is_valid_hostname function accepts only valid\n hostnames (or domain names), with optional port number.\n \"\"\"\n\n self.assertTrue(is_valid_hostname(\"example.com\"))\n self.assertTrue(is_valid_hostname(\"EXAMPLE.COM\"))\n self.assertTrue(is_valid_hostname(\"ExAmPlE.CoM\"))\n self.assertTrue(is_valid_hostname(\"example.com:4242\"))\n self.assertTrue(is_valid_hostname(\"localhost\"))\n self.assertTrue(is_valid_hostname(\"localhost:9000\"))\n self.assertTrue(is_valid_hostname(\"a.b:1234\"))\n\n self.assertFalse(is_valid_hostname(\"example.com:65536\"))\n self.assertFalse(is_valid_hostname(\"example.com:0\"))\n self.assertFalse(is_valid_hostname(\"example.com:a\"))\n self.assertFalse(is_valid_hostname(\"example.com:04242\"))\n self.assertFalse(is_valid_hostname(\"example.com: 4242\"))\n self.assertFalse(is_valid_hostname(\"example.com/example.com\"))\n self.assertFalse(is_valid_hostname(\"example.com#example.com\"))", "label": 0, "programming_language": "Python", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def skip(self, type):\n if type == TType.STOP:\n return\n elif type == TType.BOOL:\n self.readBool()\n elif type == TType.BYTE:\n self.readByte()\n elif type == TType.I16:\n self.readI16()\n elif type == TType.I32:\n self.readI32()\n elif type == TType.I64:\n self.readI64()\n elif type == TType.DOUBLE:\n self.readDouble()\n elif type == TType.FLOAT:\n self.readFloat()\n elif type == TType.STRING:\n self.readString()\n elif type == TType.STRUCT:\n name = self.readStructBegin()\n while True:\n (name, type, id) = self.readFieldBegin()\n if type == TType.STOP:\n break\n self.skip(type)\n self.readFieldEnd()\n self.readStructEnd()\n elif type == TType.MAP:\n (ktype, vtype, size) = self.readMapBegin()\n for _ in range(size):\n self.skip(ktype)\n self.skip(vtype)\n self.readMapEnd()\n elif type == TType.SET:\n (etype, size) = self.readSetBegin()\n for _ in range(size):\n self.skip(etype)\n self.readSetEnd()\n elif type == TType.LIST:\n (etype, size) = self.readListBegin()\n for _ in range(size):\n self.skip(etype)\n self.readListEnd()", "label": 0, "programming_language": "Python", "cwe_id": "CWE-755", "cwe_name": "Improper Handling of Exceptional Conditions", "description": "The software does not handle or incorrectly handles an exceptional condition.", "url": "https://cwe.mitre.org/data/definitions/755.html", "label_name": "vulnerable"} {"code": " def test_send_with_body(self):\n to_send = \"GET / HTTP/1.0\\n\" \"Content-Length: 5\\n\\n\"\n to_send += \"hello\"\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(echo.content_length, \"5\")\n self.assertEqual(echo.body, b\"hello\")", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def test_keepalive_http_10(self):\n # Handling of Keep-Alive within HTTP 1.0\n data = \"Default: Don't keep me alive\"\n s = tobytes(\n \"GET / HTTP/1.0\\n\" \"Content-Length: %d\\n\" \"\\n\" \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n connection = response.getheader(\"Connection\", \"\")\n # We sent no Connection: Keep-Alive header\n # Connection: close (or no header) is default.\n self.assertTrue(connection != \"Keep-Alive\")", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def test_request_body_too_large_with_no_cl_http11(self):\n body = \"a\" * self.toobig\n to_send = \"GET / HTTP/1.1\\n\\n\"\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # server trusts the content-length header (assumed 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # server assumes pipelined requests due to http/1.1, and the first\n # request was assumed c-l 0 because it had no content-length header,\n # so entire body looks like the header of the subsequent request\n # second response is an error response\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def test_filelike_shortcl_http11(self):\n to_send = \"GET /filelike_shortcl HTTP/1.1\\n\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\n for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 1)\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\" in response_body)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def test_request_body_too_large_with_wrong_cl_http11_connclose(self):\n body = \"a\" * self.toobig\n to_send = \"GET / HTTP/1.1\\nContent-Length: 5\\nConnection: close\\n\\n\"\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (5)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def test_without_crlf(self):\n data = \"Echo\\nthis\\r\\nplease\"\n s = tobytes(\n \"GET / HTTP/1.0\\n\"\n \"Connection: close\\n\"\n \"Content-Length: %d\\n\"\n \"\\n\"\n \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(int(echo.content_length), len(data))\n self.assertEqual(len(echo.body), len(data))\n self.assertEqual(echo.body, tobytes(data))", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def test_filelike_nocl_http11(self):\n to_send = \"GET /filelike_nocl HTTP/1.1\\n\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\n for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def test_chunking_request_with_content(self):\n control_line = b\"20;\\r\\n\" # 20 hex = 32 dec\n s = b\"This string has 32 characters.\\r\\n\"\n expected = s * 12\n header = tobytes(\"GET / HTTP/1.1\\n\" \"Transfer-Encoding: chunked\\n\\n\")\n self.connect()\n self.sock.send(header)\n fp = self.sock.makefile(\"rb\", 0)\n for n in range(12):\n self.sock.send(control_line)\n self.sock.send(s)\n self.sock.send(b\"0\\r\\n\\r\\n\")\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(echo.body, expected)\n self.assertEqual(echo.content_length, str(len(expected)))\n self.assertFalse(\"transfer-encoding\" in headers)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def testSimpleGET(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\nFirstName: mickey\nlastname: Mouse\ncontent-length: 7\n\nHello.\n\"\"\"\n parser = self.parser\n self.feed(data)\n self.assertTrue(parser.completed)\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)\n self.assertEqual(\n parser.headers,\n {\"FIRSTNAME\": \"mickey\", \"LASTNAME\": \"Mouse\", \"CONTENT_LENGTH\": \"7\",},\n )\n self.assertEqual(parser.path, \"/foobar\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.query, \"\")\n self.assertEqual(parser.proxy_scheme, \"\")\n self.assertEqual(parser.proxy_netloc, \"\")\n self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello.\\n\")", "label": 0, "programming_language": "Python", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": "def main(srcfile, dump_module=False):\n argv0 = sys.argv[0]\n components = argv0.split(os.sep)\n argv0 = os.sep.join(components[-2:])\n auto_gen_msg = common_msg % argv0\n mod = asdl.parse(srcfile)\n if dump_module:\n print('Parsed Module:')\n print(mod)\n if not asdl.check(mod):\n sys.exit(1)\n if INC_DIR:\n p = \"%s/%s-ast.h\" % (INC_DIR, mod.name)\n f = open(p, \"w\")\n f.write(auto_gen_msg)\n f.write('#include \"asdl.h\"\\n\\n')\n c = ChainOfVisitors(TypeDefVisitor(f),\n StructVisitor(f),\n PrototypeVisitor(f),\n )\n c.visit(mod)\n f.write(\"PyObject* Ta3AST_mod2obj(mod_ty t);\\n\")\n f.write(\"mod_ty Ta3AST_obj2mod(PyObject* ast, PyArena* arena, int mode);\\n\")\n f.write(\"int Ta3AST_Check(PyObject* obj);\\n\")\n f.close()\n\n if SRC_DIR:\n p = os.path.join(SRC_DIR, str(mod.name) + \"-ast.c\")\n f = open(p, \"w\")\n f.write(auto_gen_msg)\n f.write('#include \\n')\n f.write('\\n')\n f.write('#include \"Python.h\"\\n')\n f.write('#include \"%s-ast.h\"\\n' % mod.name)\n f.write('\\n')\n f.write(\"static PyTypeObject AST_type;\\n\")\n v = ChainOfVisitors(\n PyTypesDeclareVisitor(f),\n PyTypesVisitor(f),\n Obj2ModPrototypeVisitor(f),\n FunctionVisitor(f),\n ObjVisitor(f),\n Obj2ModVisitor(f),\n ASTModuleVisitor(f),\n PartingShots(f),\n )\n v.visit(mod)\n f.close()", "label": 0, "programming_language": "Python", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "def mysql_insensitive_ends_with(field: Field, value: str) -> Criterion:\n return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f\"%{value}\"))", "label": 0, "programming_language": "Python", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def __init__(\n self, credentials, host, request_uri, headers, response, content, http", "label": 0, "programming_language": "Python", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "def http_parse_auth(s):\n \"\"\"https://tools.ietf.org/html/rfc7235#section-2.1\n \"\"\"\n scheme, rest = s.split(\" \", 1)\n result = {}\n while True:\n m = httplib2.WWW_AUTH_RELAXED.search(rest)\n if not m:\n break\n if len(m.groups()) == 3:\n key, value, rest = m.groups()\n result[key.lower()] = httplib2.UNQUOTE_PAIRS.sub(r\"\\1\", value)\n return result", "label": 0, "programming_language": "Python", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "def test_spinal_case():\n assert utils.spinal_case(\"keep_alive\") == \"keep-alive\"", "label": 0, "programming_language": "Python", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "async def get_user_list(\n *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]:\n a_camel_date_time: Union[datetime, date]\n try:\n a_camel_date_time = datetime.fromisoformat(d[\"aCamelDateTime\"])\n\n return a_camel_date_time\n except:\n pass\n a_camel_date_time = date.fromisoformat(d[\"aCamelDateTime\"])\n\n return a_camel_date_time", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " def values_from_list(values: List[str]) -> Dict[str, str]:\n \"\"\" Convert a list of values into dict of {name: value} \"\"\"\n output: Dict[str, str] = {}\n\n for i, value in enumerate(values):\n if value[0].isalpha():\n key = value.upper()\n else:\n key = f\"VALUE_{i}\"\n if key in output:\n raise ValueError(f\"Duplicate key {key} in Enum\")\n output[key] = value\n\n return output", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " def test_get_imports(self, mocker):\n from openapi_python_client.parser.properties import DateTimeProperty\n\n name = mocker.MagicMock()\n mocker.patch(\"openapi_python_client.utils.snake_case\")\n p = DateTimeProperty(name=name, required=True, default=None)\n assert p.get_imports(prefix=\"\") == {\n \"from datetime import datetime\",\n \"from typing import cast\",\n }\n\n p.required = False\n assert p.get_imports(prefix=\"\") == {\n \"from typing import Optional\",\n \"from datetime import datetime\",\n \"from typing import cast\",\n }", "label": 0, "programming_language": "Python", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " async def customize_global(self, ctx, command: str.lower, *, response: str = None):\r\n \"\"\"\r\n Globally customize the response to an action.\r\n\r\n You can use {0} or {user} to dynamically replace with the specified target of the action.\r\n Formats like {0.name} or {0.mention} can also be used.\r\n \"\"\"\r\n if not response:\r\n await self.config.clear_raw(\"custom\", command)\r\n else:\r\n await self.config.set_raw(\"custom\", command, value=response)\r\n await ctx.tick()\r", "label": 0, "programming_language": "Python", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "vulnerable"} {"code": "def project_create(request):\n \"\"\"\n create a configurable project\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n data['configurable'] = 1\n project, result = Project.objects.update_or_create(**data)\n # generate a single project folder\n path = join(os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER)), data['name'])\n os.mkdir(path)\n return JsonResponse(model_to_dict(project))", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "def project_parse(request, project_name):\n \"\"\"\n parse project\n :param request: request object\n :param project_name: project name\n :return: requests, items, response\n \"\"\"\n if request.method == 'POST':\n project_path = join(PROJECTS_FOLDER, project_name)\n data = json.loads(request.body)\n logger.debug('post data %s', data)\n spider_name = data.get('spider')\n args = {\n 'start': data.get('start', False),\n 'method': data.get('method', 'GET'),\n 'url': data.get('url'),\n 'callback': data.get('callback'),\n 'cookies': \"'\" + json.dumps(data.get('cookies', {}), ensure_ascii=False) + \"'\",\n 'headers': \"'\" + json.dumps(data.get('headers', {}), ensure_ascii=False) + \"'\",\n 'meta': \"'\" + json.dumps(data.get('meta', {}), ensure_ascii=False) + \"'\",\n 'dont_filter': data.get('dont_filter', False),\n 'priority': data.get('priority', 0),\n }\n # set request body\n body = data.get('body', '')\n if args.get('method').lower() != 'get':\n args['body'] = \"'\" + json.dumps(body, ensure_ascii=False) + \"'\"\n \n args_cmd = ' '.join(\n ['--{arg} {value}'.format(arg=arg, value=value) for arg, value in args.items()])\n logger.debug('args cmd %s', args_cmd)\n cmd = 'gerapy parse {args_cmd} {project_path} {spider_name}'.format(\n args_cmd=args_cmd,\n project_path=project_path,\n spider_name=spider_name\n )\n logger.debug('parse cmd %s', cmd)\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)\n stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())\n logger.debug('stdout %s, stderr %s', stdout, stderr)\n if not stderr:\n return JsonResponse({'status': True, 'result': json.loads(stdout)})\n else:\n return JsonResponse({'status': False, 'message': stderr})", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "def task_update(request, task_id):\n \"\"\"\n update task info\n :param request: request object\n :param task_id: task id\n :return: json\n \"\"\"\n if request.method == 'POST':\n task = Task.objects.filter(id=task_id)\n data = json.loads(request.body)\n data['clients'] = json.dumps(data.get('clients'), ensure_ascii=False)\n data['configuration'] = json.dumps(data.get('configuration'), ensure_ascii=False)\n data['modified'] = 1\n task.update(**data)\n return JsonResponse(model_to_dict(Task.objects.get(id=task_id)))", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " def test_challenge_with_vhm(self):\n rc, root, folder, object = self._makeTree()\n response = FauxCookieResponse()\n vhm = 'http://localhost/VirtualHostBase/http/test/VirtualHostRoot/xxx'\n actualURL = 'http://test/xxx'\n\n request = FauxRequest(RESPONSE=response, URL=vhm,\n ACTUAL_URL=actualURL)\n root.REQUEST = request\n\n helper = self._makeOne().__of__(root)\n\n helper.challenge(request, response)\n self.assertEqual(response.status, 302)\n self.assertEqual(len(response.headers), 3)\n loc = response.headers['Location']\n self.assertTrue(loc.endswith(quote(actualURL)))\n self.assertFalse(loc.endswith(quote(vhm)))\n self.assertEqual(response.headers['Cache-Control'], 'no-cache')\n self.assertEqual(response.headers['Expires'],\n 'Sat, 01 Jan 2000 00:00:00 GMT')", "label": 0, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "vulnerable"} {"code": " def run(self, stat_name, criticity, commands, repeat, mustache_dict=None):\n \"\"\"Run the commands (in background).\n\n - stats_name: plugin_name (+ header)\n - criticity: criticity of the trigger\n - commands: a list of command line with optional {{mustache}}\n - If True, then repeat the action\n - mustache_dict: Plugin stats (can be use within {{mustache}})\n\n Return True if the commands have been ran.\n \"\"\"\n if (self.get(stat_name) == criticity and not repeat) or \\\n not self.start_timer.finished():\n # Action already executed => Exit\n return False\n\n logger.debug(\"{} action {} for {} ({}) with stats {}\".format(\n \"Repeat\" if repeat else \"Run\",\n commands, stat_name, criticity, mustache_dict))\n\n # Run all actions in background\n for cmd in commands:\n # Replace {{arg}} by the dict one (Thk to {Mustache})\n if chevron_tag:\n cmd_full = chevron.render(cmd, mustache_dict)\n else:\n cmd_full = cmd\n # Execute the action\n logger.info(\"Action triggered for {} ({}): {}\".format(stat_name,\n criticity,\n cmd_full))\n logger.debug(\"Action will be executed with the following command: \\\n subprocess.Popen({}, shell=False)\".format(cmd_full.split(' ')))\n try:\n Popen(cmd_full.split(' '), shell=False)\n except OSError as e:\n logger.error(\"Can't execute the action ({})\".format(e))\n\n self.set(stat_name, criticity)\n\n return True", "label": 0, "programming_language": "Python", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": "def load(doc):\n code = config.retrieveBoilerplateFile(doc, \"bs-extensions\")\n exec(code, globals())", "label": 0, "programming_language": "Python", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "vulnerable"} {"code": "def store_user_session():\n if flask_session.get('_user_id', \"\"):\n try:\n if not check_user_session(flask_session.get('_user_id', \"\"), flask_session.get('_id', \"\")):\n user_session = User_Sessions(flask_session.get('_user_id', \"\"), flask_session.get('_id', \"\"))\n session.add(user_session)\n session.commit()\n log.info(\"Login and store session : \" + flask_session.get('_id', \"\"))\n else:\n log.info(\"Found stored session : \" + flask_session.get('_id', \"\"))\n except (exc.OperationalError, exc.InvalidRequestError) as e:\n session.rollback()\n log.exception(e)\n else:\n log.error(\"No user id in session\")", "label": 0, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": "def generate_auth_token(user_id):\n host_list = request.host.rsplit(':')\n if len(host_list) == 1:\n host = ':'.join(host_list)\n else:\n host = ':'.join(host_list[0:-1])\n if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f'):\n warning = _('PLease access calibre-web from non localhost to get valid api_endpoint for kobo device')\n return render_title_template(\n \"generate_kobo_auth_url.html\",\n title=_(u\"Kobo Setup\"),\n warning = warning\n )\n else:\n # Invalidate any prevously generated Kobo Auth token for this user.\n auth_token = ub.session.query(ub.RemoteAuthToken).filter(\n ub.RemoteAuthToken.user_id == user_id\n ).filter(ub.RemoteAuthToken.token_type==1).first()\n\n if not auth_token:\n auth_token = ub.RemoteAuthToken()\n auth_token.user_id = user_id\n auth_token.expiration = datetime.max\n auth_token.auth_token = (hexlify(urandom(16))).decode(\"utf-8\")\n auth_token.token_type = 1\n\n ub.session.add(auth_token)\n ub.session_commit()\n\n books = calibre_db.session.query(db.Books).join(db.Data).all()\n\n for book in books:\n formats = [data.format for data in book.data]\n if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats:\n helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name)\n\n return render_title_template(\n \"generate_kobo_auth_url.html\",\n title=_(u\"Kobo Setup\"),\n kobo_auth_url=url_for(\n \"kobo.TopLevelEndpoint\", auth_token=auth_token.auth_token, _external=True\n ),\n warning = False\n )", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def edit_user_table():\n visibility = current_user.view_settings.get('useredit', {})\n languages = calibre_db.speaking_language()\n translations = babel.list_translations() + [LC('en')]\n allUser = ub.session.query(ub.User)\n tags = calibre_db.session.query(db.Tags)\\\n .join(db.books_tags_link)\\\n .join(db.Books)\\\n .filter(calibre_db.common_filters()) \\\n .group_by(text('books_tags_link.tag'))\\\n .order_by(db.Tags.name).all()\n if config.config_restricted_column:\n custom_values = calibre_db.session.query(db.cc_classes[config.config_restricted_column]).all()\n else:\n custom_values = []\n if not config.config_anonbrowse:\n allUser = allUser.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS)\n kobo_support = feature_support['kobo'] and config.config_kobo_sync\n return render_title_template(\"user_table.html\",\n users=allUser.all(),\n tags=tags,\n custom_values=custom_values,\n translations=translations,\n languages=languages,\n visiblility=visibility,\n all_roles=constants.ALL_ROLES,\n kobo_support=kobo_support,\n sidebar_settings=constants.sidebar_settings,\n title=_(u\"Edit Users\"),\n page=\"usertable\")", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def _configuration_oauth_helper(to_save):\n active_oauths = 0\n reboot_required = False\n for element in oauthblueprints:\n if to_save[\"config_\" + str(element['id']) + \"_oauth_client_id\"] != element['oauth_client_id'] \\\n or to_save[\"config_\" + str(element['id']) + \"_oauth_client_secret\"] != element['oauth_client_secret']:\n reboot_required = True\n element['oauth_client_id'] = to_save[\"config_\" + str(element['id']) + \"_oauth_client_id\"]\n element['oauth_client_secret'] = to_save[\"config_\" + str(element['id']) + \"_oauth_client_secret\"]\n if to_save[\"config_\" + str(element['id']) + \"_oauth_client_id\"] \\\n and to_save[\"config_\" + str(element['id']) + \"_oauth_client_secret\"]:\n active_oauths += 1\n element[\"active\"] = 1\n else:\n element[\"active\"] = 0\n ub.session.query(ub.OAuthProvider).filter(ub.OAuthProvider.id == element['id']).update(\n {\"oauth_client_id\": to_save[\"config_\" + str(element['id']) + \"_oauth_client_id\"],\n \"oauth_client_secret\": to_save[\"config_\" + str(element['id']) + \"_oauth_client_secret\"],\n \"active\": element[\"active\"]})\n return reboot_required", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def _configuration_oauth_helper(to_save):\n active_oauths = 0\n reboot_required = False\n for element in oauthblueprints:\n if to_save[\"config_\" + str(element['id']) + \"_oauth_client_id\"] != element['oauth_client_id'] \\\n or to_save[\"config_\" + str(element['id']) + \"_oauth_client_secret\"] != element['oauth_client_secret']:\n reboot_required = True\n element['oauth_client_id'] = to_save[\"config_\" + str(element['id']) + \"_oauth_client_id\"]\n element['oauth_client_secret'] = to_save[\"config_\" + str(element['id']) + \"_oauth_client_secret\"]\n if to_save[\"config_\" + str(element['id']) + \"_oauth_client_id\"] \\\n and to_save[\"config_\" + str(element['id']) + \"_oauth_client_secret\"]:\n active_oauths += 1\n element[\"active\"] = 1\n else:\n element[\"active\"] = 0\n ub.session.query(ub.OAuthProvider).filter(ub.OAuthProvider.id == element['id']).update(\n {\"oauth_client_id\": to_save[\"config_\" + str(element['id']) + \"_oauth_client_id\"],\n \"oauth_client_secret\": to_save[\"config_\" + str(element['id']) + \"_oauth_client_secret\"],\n \"active\": element[\"active\"]})\n return reboot_required", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def list_users():\n off = int(request.args.get(\"offset\") or 0)\n limit = int(request.args.get(\"limit\") or 10)\n search = request.args.get(\"search\")\n sort = request.args.get(\"sort\", \"id\")\n state = None\n if sort == \"state\":\n state = json.loads(request.args.get(\"state\", \"[]\"))\n else:\n if sort not in ub.User.__table__.columns.keys():\n sort = \"id\"\n order = request.args.get(\"order\", \"\").lower()\n\n if sort != \"state\" and order:\n order = text(sort + \" \" + order)\n elif not state:\n order = ub.User.id.asc()\n\n all_user = ub.session.query(ub.User)\n if not config.config_anonbrowse:\n all_user = all_user.filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS)\n\n total_count = filtered_count = all_user.count()\n\n if search:\n all_user = all_user.filter(or_(func.lower(ub.User.name).ilike(\"%\" + search + \"%\"),\n func.lower(ub.User.kindle_mail).ilike(\"%\" + search + \"%\"),\n func.lower(ub.User.email).ilike(\"%\" + search + \"%\")))\n if state:\n users = calibre_db.get_checkbox_sorted(all_user.all(), state, off, limit, request.args.get(\"order\", \"\").lower())\n else:\n users = all_user.order_by(order).offset(off).limit(limit).all()\n if search:\n filtered_count = len(users)\n\n for user in users:\n if user.default_language == \"all\":\n user.default = _(\"All\")\n else:\n user.default = LC.parse(user.default_language).get_language_name(get_locale())\n\n table_entries = {'totalNotFiltered': total_count, 'total': filtered_count, \"rows\": users}\n js_list = json.dumps(table_entries, cls=db.AlchemyEncoder)\n response = make_response(js_list)\n response.headers[\"Content-Type\"] = \"application/json; charset=utf-8\"\n return response", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": " def __init__(self, text, book):\n self.text = text\n self.book = book", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def add_objects(db_book_object, db_object, db_session, db_type, add_elements):\n changed = False\n if db_type == 'languages':\n db_filter = db_object.lang_code\n elif db_type == 'custom':\n db_filter = db_object.value\n else:\n db_filter = db_object.name\n for add_element in add_elements:\n # check if a element with that name exists\n db_element = db_session.query(db_object).filter(db_filter == add_element).first()\n # if no element is found add it\n if db_type == 'author':\n new_element = db_object(add_element, helper.get_sorted_author(add_element.replace('|', ',')), \"\")\n elif db_type == 'series':\n new_element = db_object(add_element, add_element)\n elif db_type == 'custom':\n new_element = db_object(value=add_element)\n elif db_type == 'publisher':\n new_element = db_object(add_element, None)\n else: # db_type should be tag or language\n new_element = db_object(add_element)\n if db_element is None:\n changed = True\n db_session.add(new_element)\n db_book_object.append(new_element)\n else:\n db_element = create_objects_for_addition(db_element, add_element, db_type)\n changed = True\n # add element to book\n changed = True\n db_book_object.append(db_element)\n return changed", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def edit_all_cc_data(book_id, book, to_save):\n cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()\n return edit_cc_data(book_id, book, to_save, cc)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def upload_cover(request, book):\n if 'btn-upload-cover' in request.files:\n requested_file = request.files['btn-upload-cover']\n # check for empty request\n if requested_file.filename != '':\n if not current_user.role_upload():\n abort(403)\n ret, message = helper.save_cover(requested_file, book.path)\n if ret is True:\n return True\n else:\n flash(message, category=\"error\")\n return False\n return None", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def create_book_on_upload(modif_date, meta):\n title = meta.title\n authr = meta.author\n sort_authors, input_authors, db_author, renamed_authors = prepare_authors_on_upload(title, authr)\n\n title_dir = helper.get_valid_filename(title, chars=96)\n author_dir = helper.get_valid_filename(db_author.name, chars=96)\n\n # combine path and normalize path from windows systems\n path = os.path.join(author_dir, title_dir).replace('\\\\', '/')\n\n # Calibre adds books with utc as timezone\n db_book = db.Books(title, \"\", sort_authors, datetime.utcnow(), datetime(101, 1, 1),\n '1', datetime.utcnow(), path, meta.cover, db_author, [], \"\")\n\n modif_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session,\n 'author')\n\n # Add series_index to book\n modif_date |= edit_book_series_index(meta.series_id, db_book)\n\n # add languages\n invalid=[]\n modif_date |= edit_book_languages(meta.languages, db_book, upload=True, invalid=invalid)\n if invalid:\n for l in invalid:\n flash(_(u\"'%(langname)s' is not a valid language\", langname=l), category=\"warning\")\n\n # handle tags\n modif_date |= edit_book_tags(meta.tags, db_book)\n\n # handle publisher\n modif_date |= edit_book_publisher(meta.publisher, db_book)\n\n # handle series\n modif_date |= edit_book_series(meta.series, db_book)\n\n # Add file to book\n file_size = os.path.getsize(meta.file_path)\n db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir)\n db_book.data.append(db_data)\n calibre_db.session.add(db_book)\n\n # flush content, get db_book.id available\n calibre_db.session.flush()\n return db_book, input_authors, title_dir, renamed_authors", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def edit_single_cc_data(book_id, book, column_id, to_save):\n cc = (calibre_db.session.query(db.Custom_Columns)\n .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions))\n .filter(db.Custom_Columns.id == column_id)\n .all())\n return edit_cc_data(book_id, book, to_save, cc)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def do_download_file(book, book_format, client, data, headers):\n if config.config_use_google_drive:\n #startTime = time.time()\n df = gd.getFileFromEbooksFolder(book.path, data.name + \".\" + book_format)\n #log.debug('%s', time.time() - startTime)\n if df:\n return gd.do_gdrive_download(df, headers)\n else:\n abort(404)\n else:\n filename = os.path.join(config.config_calibre_dir, book.path)\n if not os.path.isfile(os.path.join(filename, data.name + \".\" + book_format)):\n # ToDo: improve error handling\n log.error('File not found: %s', os.path.join(filename, data.name + \".\" + book_format))\n\n if client == \"kobo\" and book_format == \"kepub\":\n headers[\"Content-Disposition\"] = headers[\"Content-Disposition\"].replace(\".kepub\", \".kepub.epub\")\n\n response = make_response(send_from_directory(filename, data.name + \".\" + book_format))\n # ToDo Check headers parameter\n for element in headers:\n response.headers[element[0]] = element[1]\n log.info('Downloading file: {}'.format(os.path.join(filename, data.name + \".\" + book_format)))\n return response", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def check_unrar(unrarLocation):\n if not unrarLocation:\n return\n\n if not os.path.exists(unrarLocation):\n return _('Unrar binary file not found')\n\n try:\n unrarLocation = [unrarLocation]\n value = process_wait(unrarLocation, pattern='UNRAR (.*) freeware')\n if value:\n version = value.group(1)\n log.debug(\"unrar version %s\", version)\n\n except (OSError, UnicodeDecodeError) as err:\n log.error_or_exception(err)\n return _('Error excecuting UnRar')", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def rename_all_authors(first_author, renamed_author, calibre_path=\"\", localbook=None, gdrive=False):\n # Create new_author_dir from parameter or from database\n # Create new title_dir from database and add id\n if first_author:\n new_authordir = get_valid_filename(first_author, chars=96)\n for r in renamed_author:\n new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first()\n old_author_dir = get_valid_filename(r, chars=96)\n new_author_rename_dir = get_valid_filename(new_author.name, chars=96)\n if gdrive:\n gFile = gd.getFileFromEbooksFolder(None, old_author_dir)\n if gFile:\n gd.moveGdriveFolderRemote(gFile, new_author_rename_dir)\n else:\n if os.path.isdir(os.path.join(calibre_path, old_author_dir)):\n try:\n old_author_path = os.path.join(calibre_path, old_author_dir)\n new_author_path = os.path.join(calibre_path, new_author_rename_dir)\n shutil.move(os.path.normcase(old_author_path), os.path.normcase(new_author_path))\n except (OSError) as ex:\n log.error(\"Rename author from: %s to %s: %s\", old_author_path, new_author_path, ex)\n log.debug(ex, exc_info=True)\n return _(\"Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s\",\n src=old_author_path, dest=new_author_path, error=str(ex))\n else:\n new_authordir = get_valid_filename(localbook.authors[0].name, chars=96)\n return new_authordir", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def feed_publisher(book_id):\n off = request.args.get(\"offset\") or 0\n entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,\n db.Books,\n db.Books.publishers.any(db.Publishers.id == book_id),\n [db.Books.timestamp.desc()])\n return render_xml_template('feed.xml', entries=entries, pagination=pagination)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def feed_seriesindex():\n shift = 0\n off = int(request.args.get(\"offset\") or 0)\n entries = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('id'))\\\n .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters())\\\n .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()\n elements = []\n if off == 0:\n elements.append({'id': \"00\", 'name':_(\"All\")})\n shift = 1\n for entry in entries[\n off + shift - 1:\n int(off + int(config.config_books_per_page) - shift)]:\n elements.append({'id': entry.id, 'name': entry.id})\n pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,\n len(entries) + 1)\n return render_xml_template('feed.xml',\n letterelements=elements,\n folder='opds.feed_letter_series',\n pagination=pagination)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def opds_download_link(book_id, book_format):\n # I gave up with this: With enabled ldap login, the user doesn't get logged in, therefore it's always guest\n # workaround, loading the user from the request and checking it's download rights here\n # in case of anonymous browsing user is None\n user = load_user_from_request(request) or current_user\n if not user.role_download():\n return abort(403)\n if \"Kobo\" in request.headers.get('User-Agent'):\n client = \"kobo\"\n else:\n client = \"\"\n return get_download_link(book_id, book_format.lower(), client)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def feed_booksindex():\n shift = 0\n off = int(request.args.get(\"offset\") or 0)\n entries = calibre_db.session.query(func.upper(func.substr(db.Books.sort, 1, 1)).label('id'))\\\n .filter(calibre_db.common_filters()).group_by(func.upper(func.substr(db.Books.sort, 1, 1))).all()\n\n elements = []\n if off == 0:\n elements.append({'id': \"00\", 'name':_(\"All\")})\n shift = 1\n for entry in entries[\n off + shift - 1:\n int(off + int(config.config_books_per_page) - shift)]:\n elements.append({'id': entry.id, 'name': entry.id})\n\n pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,\n len(entries) + 1)\n return render_xml_template('feed.xml',\n letterelements=elements,\n folder='opds.feed_letter_books',\n pagination=pagination)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def adv_search_extension(q, include_extension_inputs, exclude_extension_inputs):\n for extension in include_extension_inputs:\n q = q.filter(db.Books.data.any(db.Data.format == extension))\n for extension in exclude_extension_inputs:\n q = q.filter(not_(db.Books.data.any(db.Data.format == extension)))\n return q", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def category_list():\n if current_user.check_visibility(constants.SIDEBAR_CATEGORY):\n if current_user.get_view_property('category', 'dir') == 'desc':\n order = db.Tags.name.desc()\n order_no = 0\n else:\n order = db.Tags.name.asc()\n order_no = 1\n entries = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \\\n .join(db.books_tags_link).join(db.Books).order_by(order).filter(calibre_db.common_filters()) \\\n .group_by(text('books_tags_link.tag')).all()\n charlist = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('char')) \\\n .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters()) \\\n .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all()\n return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,\n title=_(u\"Categories\"), page=\"catlist\", data=\"category\", order=order_no)\n else:\n abort(404)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def adv_search_serie(q, include_series_inputs, exclude_series_inputs):\n for serie in include_series_inputs:\n q = q.filter(db.Books.series.any(db.Series.id == serie))\n for serie in exclude_series_inputs:\n q = q.filter(not_(db.Books.series.any(db.Series.id == serie)))\n return q", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs):\n q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\\\n .filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs)))\n if len(include_shelf_inputs) > 0:\n q = q.filter(ub.BookShelf.shelf.in_(include_shelf_inputs))\n return q", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": " def strip_illegal_bytes_parser(xml):\n return parse(BytesIO(re_xml_illegal_bytes.sub(b'', xml)))", "label": 0, "programming_language": "Python", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " def builtin_roles(self):\n return self._builtin_roles", "label": 0, "programming_language": "Python", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " def auth_ldap_use_tls(self):\n return self.appbuilder.get_app.config[\"AUTH_LDAP_USE_TLS\"]", "label": 0, "programming_language": "Python", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " def auth_role_public(self):\n return self.appbuilder.get_app.config[\"AUTH_ROLE_PUBLIC\"]", "label": 0, "programming_language": "Python", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": "def configure_local_ssh_key():\n \"\"\"\n Configure ssh rsa key locally\n\n If /root/.ssh/id_rsa not exist, generate a new one\n Add /root/.ssh/id_rsa.pub to /root/.ssh/authorized_keys anyway, make sure itself authorized\n \"\"\"\n if not os.path.exists(RSA_PRIVATE_KEY):\n status(\"Generating SSH key\")\n invoke(\"ssh-keygen -q -f {} -C 'Cluster Internal on {}' -N ''\".format(RSA_PRIVATE_KEY, utils.this_node()))\n if not os.path.exists(AUTHORIZED_KEYS_FILE):\n open(AUTHORIZED_KEYS_FILE, 'w').close()\n append_unique(RSA_PUBLIC_KEY, AUTHORIZED_KEYS_FILE)", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " async def check_credentials(username: str, password: str) -> bool:\n return (username, password) == credentials", "label": 0, "programming_language": "Python", "cwe_id": "CWE-203", "cwe_name": "Observable Discrepancy", "description": "The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.", "url": "https://cwe.mitre.org/data/definitions/203.html", "label_name": "vulnerable"} {"code": " async def check_credentials(username, password):\n return password == \"iloveyou\"", "label": 0, "programming_language": "Python", "cwe_id": "CWE-203", "cwe_name": "Observable Discrepancy", "description": "The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.", "url": "https://cwe.mitre.org/data/definitions/203.html", "label_name": "vulnerable"} {"code": " def kill_container(self):\n '''\n Internal method to terminate a container being used for job isolation\n '''\n container_name = self.config.container_name\n if container_name:\n container_cli = self.config.process_isolation_executable\n cmd = '{} kill {}'.format(container_cli, container_name)\n proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)\n _, stderr = proc.communicate()\n if proc.returncode:\n logger.info('Error from {} kill {} command:\\n{}'.format(container_cli, container_name, stderr))\n else:\n logger.info(\"Killed container {}\".format(container_name))", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "def test_basic(settings):\n items, url, crawler = yield crawl_items(ResponseSpider, HelloWorld,\n settings)\n assert len(items) == 1\n resp = items[0]['response']\n assert resp.url == url\n assert resp.css('body::text').extract_first().strip() == \"hello world!\"", "label": 0, "programming_language": "Python", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "def test_basic_lua(settings):\n\n class LuaScriptSpider(ResponseSpider):\n \"\"\" Make a request using a Lua script similar to the one from README\n \"\"\"\n def start_requests(self):\n yield SplashRequest(self.url + \"#foo\", endpoint='execute',\n args={'lua_source': DEFAULT_SCRIPT, 'foo': 'bar'})\n\n\n items, url, crawler = yield crawl_items(LuaScriptSpider, HelloWorld,\n settings)\n assert len(items) == 1\n resp = items[0]['response']\n assert resp.url == url + \"/#foo\"\n assert resp.status == resp.splash_response_status == 200\n assert resp.css('body::text').extract_first().strip() == \"hello world!\"\n assert resp.data['jsvalue'] == 3\n assert resp.headers['X-MyHeader'] == b'my value'\n assert resp.headers['Content-Type'] == b'text/html'\n assert resp.splash_response_headers['Content-Type'] == b'application/json'\n assert resp.data['args']['foo'] == 'bar'", "label": 0, "programming_language": "Python", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " def render_GET(self, request):\n request.setHeader(b'content-type', to_bytes(self.content_type))\n for name, value in self.extra_headers.items():\n request.setHeader(to_bytes(name), to_bytes(value))\n request.setResponseCode(self.status_code)\n return to_bytes(self.html)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "def crawl_items(spider_cls, resource_cls, settings, spider_kwargs=None):\n \"\"\" Use spider_cls to crawl resource_cls. URL of the resource is passed\n to the spider as ``url`` argument.\n Return ``(items, resource_url, crawler)`` tuple.\n \"\"\"\n spider_kwargs = {} if spider_kwargs is None else spider_kwargs\n crawler = make_crawler(spider_cls, settings)\n with MockServer(resource_cls) as s:\n root_url = s.root_url\n yield crawler.crawl(url=root_url, **spider_kwargs)\n result = crawler.spider.collected_items, s.root_url, crawler\n returnValue(result)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "def load_hparams_from_yaml(config_yaml: str, use_omegaconf: bool = True) -> Dict[str, Any]:\n \"\"\"Load hparams from a file.\n\n Args:\n config_yaml: Path to config yaml file\n use_omegaconf: If omegaconf is available and ``use_omegaconf=True``,\n the hparams will be converted to ``DictConfig`` if possible.\n\n >>> hparams = Namespace(batch_size=32, learning_rate=0.001, data_root='./any/path/here')\n >>> path_yaml = './testing-hparams.yaml'\n >>> save_hparams_to_yaml(path_yaml, hparams)\n >>> hparams_new = load_hparams_from_yaml(path_yaml)\n >>> vars(hparams) == hparams_new\n True\n >>> os.remove(path_yaml)\n \"\"\"\n fs = get_filesystem(config_yaml)\n if not fs.exists(config_yaml):\n rank_zero_warn(f\"Missing Tags: {config_yaml}.\", category=RuntimeWarning)\n return {}\n\n with fs.open(config_yaml, \"r\") as fp:\n hparams = yaml.load(fp, Loader=yaml.UnsafeLoader)\n\n if _OMEGACONF_AVAILABLE:\n if use_omegaconf:\n try:\n return OmegaConf.create(hparams)\n except (UnsupportedValueType, ValidationError):\n pass\n return hparams", "label": 0, "programming_language": "Python", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "vulnerable"} {"code": "def test_unicorn_render_context_variable():\n token = Token(\n TokenType.TEXT,\n \"unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg=test_var.nested\",\n )\n unicorn_node = unicorn(None, token)\n context = {\"test_var\": {\"nested\": \"variable!\"}}\n actual = unicorn_node.render(context)\n\n assert \"->variable!<-\" in actual", "label": 0, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " def cookies(self, jar: RequestsCookieJar):\n # \n stored_attrs = ['value', 'path', 'secure', 'expires']\n self['cookies'] = {}\n for cookie in jar:\n self['cookies'][cookie.name] = {\n attname: getattr(cookie, attname)\n for attname in stored_attrs\n }", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " def test_session_with_cookie_followed_by_another_header(self, httpbin):\n \"\"\"\n Make sure headers don\u2019t get mutated \u2014 \n \"\"\"\n self.start_session(httpbin)\n session_data = {\n \"headers\": {\n \"cookie\": \"...\",\n \"zzz\": \"...\"\n }\n }\n session_path = self.config_dir / 'session-data.json'\n session_path.write_text(json.dumps(session_data))\n r = http('--session', str(session_path), 'GET', httpbin.url + '/get',\n env=self.env())\n assert HTTP_OK in r\n assert 'Zzz' in r", "label": 0, "programming_language": "Python", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "def publish(request, topic_id, pk=None):\n initial = None\n if pk: # todo: move to form\n comment = get_object_or_404(\n Comment.objects.for_access(user=request.user), pk=pk)\n quote = markdown.quotify(comment.comment, comment.user.st.nickname)\n initial = {'comment': quote}\n\n user = request.user\n topic = get_object_or_404(\n Topic.objects.opened().for_access(user),\n pk=topic_id)\n form = CommentForm(\n user=user,\n topic=topic,\n data=post_data(request),\n initial=initial)\n\n if is_post(request) and not request.is_limited() and form.is_valid():\n if not user.st.update_post_hash(form.get_comment_hash()):\n # Hashed comment may have not been saved yet\n return redirect(\n request.POST.get('next', None) or\n Comment\n .get_last_for_topic(topic_id)\n .get_absolute_url())\n\n comment = form.save()\n comment_posted(comment=comment, mentions=form.mentions)\n return redirect(request.POST.get('next', comment.get_absolute_url()))\n\n return render(\n request=request,\n template_name='spirit/comment/publish.html',\n context={\n 'form': form,\n 'topic': topic})", "label": 0, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "vulnerable"} {"code": "def delete_access(request, pk):\n topic_private = TopicPrivate.objects.for_delete_or_404(pk, request.user)\n\n if request.method == 'POST':\n topic_private.delete()\n\n if request.user.pk == topic_private.user_id:\n return redirect(reverse(\"spirit:topic:private:index\"))\n\n return redirect(request.POST.get('next', topic_private.get_absolute_url()))\n\n return render(\n request=request,\n template_name='spirit/topic/private/delete.html',\n context={'topic_private': topic_private})", "label": 0, "programming_language": "Python", "cwe_id": "CWE-601", "cwe_name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.", "url": "https://cwe.mitre.org/data/definitions/601.html", "label_name": "vulnerable"} {"code": "def run_custom_method(doctype, name, custom_method):\n\t\"\"\"cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}\"\"\"\n\tdoc = frappe.get_doc(doctype, name)\n\tif getattr(doc, custom_method, frappe._dict()).is_whitelisted:\n\t\tfrappe.call(getattr(doc, custom_method), **frappe.local.form_dict)\n\telse:\n\t\tfrappe.throw(_(\"Not permitted\"), frappe.PermissionError)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " def image(self, request, pk):\n obj = self.get_object()\n\n if obj.get_space() != request.space:\n raise PermissionDenied(detail='You do not have the required permission to perform this action', code=403)\n\n serializer = self.serializer_class(obj, data=request.data, partial=True)\n\n if serializer.is_valid():\n serializer.save()\n image = None\n filetype = \".jpeg\" # fall-back to .jpeg, even if wrong, at least users will know it's an image and most image viewers can open it correctly anyways\n\n if 'image' in serializer.validated_data:\n image = obj.image\n filetype = mimetypes.guess_extension(serializer.validated_data['image'].content_type) or filetype\n elif 'image_url' in serializer.validated_data:\n try:\n response = requests.get(serializer.validated_data['image_url'])\n image = File(io.BytesIO(response.content))\n filetype = mimetypes.guess_extension(response.headers['content-type']) or filetype\n except UnidentifiedImageError as e:\n print(e)\n pass\n except MissingSchema as e:\n print(e)\n pass\n except Exception as e:\n print(e)\n pass\n\n if image is not None:\n img = handle_image(request, image, filetype)\n obj.image = File(img, name=f'{uuid.uuid4()}_{obj.pk}{filetype}')\n obj.save()\n return Response(serializer.data)\n\n return Response(serializer.errors, 400)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "def _get_index_absolute_path(index):\n return os.path.join(INDEXDIR, index)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "def _get_obj_absolute_path(obj_path):\n return os.path.join(DATAROOT, obj_path)", "label": 0, "programming_language": "Python", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "void add_interrupt_randomness(int irq, int irq_flags)\n{\n\tstruct entropy_store\t*r;\n\tstruct fast_pool\t*fast_pool = this_cpu_ptr(&irq_randomness);\n\tstruct pt_regs\t\t*regs = get_irq_regs();\n\tunsigned long\t\tnow = jiffies;\n\tcycles_t\t\tcycles = random_get_entropy();\n\t__u32\t\t\tc_high, j_high;\n\t__u64\t\t\tip;\n\tunsigned long\t\tseed;\n\tint\t\t\tcredit = 0;\n\n\tif (cycles == 0)\n\t\tcycles = get_reg(fast_pool, regs);\n\tc_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;\n\tj_high = (sizeof(now) > 4) ? now >> 32 : 0;\n\tfast_pool->pool[0] ^= cycles ^ j_high ^ irq;\n\tfast_pool->pool[1] ^= now ^ c_high;\n\tip = regs ? instruction_pointer(regs) : _RET_IP_;\n\tfast_pool->pool[2] ^= ip;\n\tfast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :\n\t\tget_reg(fast_pool, regs);\n\n\tfast_mix(fast_pool);\n\tadd_interrupt_bench(cycles);\n\tthis_cpu_add(net_rand_state.s1, fast_pool->pool[cycles & 3]);\n\n\tif (unlikely(crng_init == 0)) {\n\t\tif ((fast_pool->count >= 64) &&\n\t\t crng_fast_load((char *) fast_pool->pool,\n\t\t\t\t sizeof(fast_pool->pool))) {\n\t\t\tfast_pool->count = 0;\n\t\t\tfast_pool->last = now;\n\t\t}\n\t\treturn;\n\t}\n\n\tif ((fast_pool->count < 64) &&\n\t !time_after(now, fast_pool->last + HZ))\n\t\treturn;\n\n\tr = &input_pool;\n\tif (!spin_trylock(&r->lock))\n\t\treturn;\n\n\tfast_pool->last = now;\n\t__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));\n\n\t/*\n\t * If we have architectural seed generator, produce a seed and\n\t * add it to the pool. For the sake of paranoia don't let the\n\t * architectural seed generator dominate the input from the\n\t * interrupt noise.\n\t */\n\tif (arch_get_random_seed_long(&seed)) {\n\t\t__mix_pool_bytes(r, &seed, sizeof(seed));\n\t\tcredit = 1;\n\t}\n\tspin_unlock(&r->lock);\n\n\tfast_pool->count = 0;\n\n\t/* award one bit for the contents of the fast pool */\n\tcredit_entropy_bits(r, credit + 1);\n}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-330", "cwe_name": "Use of Insufficiently Random Values", "description": "The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.", "url": "https://cwe.mitre.org/data/definitions/330.html", "label_name": "safe"} {"code": "\tpublic Class resolve(\n\t\t\tString className, Environment environment, Template template)\n\t\tthrows TemplateException {\n\n\t\tif (className.equals(ObjectConstructor.class.getName())) {\n\t\t\tthrow new TemplateException(\n\t\t\t\t\"Instantiating \" + className + \" is not allowed in the \" +\n\t\t\t\t\t\"template for security reasons\",\n\t\t\t\tenvironment);\n\t\t}\n\n\t\tfor (String restrictedClassName :\n\t\t\t\tPropsValues.FREEMARKER_ENGINE_RESTRICTED_CLASSES) {\n\n\t\t\tif (className.equals(restrictedClassName)) {\n\t\t\t\tthrow new TemplateException(\n\t\t\t\t\t\"Instantiating \" + className + \" is not allowed in the \" +\n\t\t\t\t\t\t\"template for security reasons\",\n\t\t\t\t\tenvironment);\n\t\t\t}\n\t\t}\n\n\t\tfor (String restrictedPackageName :\n\t\t\t\tPropsValues.FREEMARKER_ENGINE_RESTRICTED_PACKAGES) {\n\n\t\t\tif (className.startsWith(restrictedPackageName)) {\n\t\t\t\tthrow new TemplateException(\n\t\t\t\t\t\"Instantiating \" + className + \" is not allowed in the \" +\n\t\t\t\t\t\t\"template for security reasons\",\n\t\t\t\t\tenvironment);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\treturn Class.forName(\n\t\t\t\tclassName, true, PACLClassLoaderUtil.getContextClassLoader());\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new TemplateException(e, environment);\n\t\t}\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "\tpublic boolean processTemplate(Writer writer) throws TemplateException {\n\t\tPACLPolicy initialPolicy =\n\t\t\tPortalSecurityManagerThreadLocal.getPACLPolicy();\n\n\t\ttry {\n\t\t\tPortalSecurityManagerThreadLocal.setPACLPolicy(_paclPolicy);\n\n\t\t\treturn super.processTemplate(writer);\n\t\t}\n\t\tfinally {\n\t\t\tPortalSecurityManagerThreadLocal.setPACLPolicy(initialPolicy);\n\t\t}\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " private ConsoleAnnotator createAnnotator(StaplerRequest req) throws IOException {\n try {\n String base64 = req!=null ? req.getHeader(\"X-ConsoleAnnotator\") : null;\n if (base64!=null) {\n Cipher sym = PASSING_ANNOTATOR.decrypt();\n\n ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream(\n new CipherInputStream(new ByteArrayInputStream(Base64.decode(base64.toCharArray())),sym)),\n Jenkins.getInstance().pluginManager.uberClassLoader);\n try {\n long timestamp = ois.readLong();\n if (TimeUnit2.HOURS.toMillis(1) > abs(System.currentTimeMillis()-timestamp))\n // don't deserialize something too old to prevent a replay attack\n return (ConsoleAnnotator)ois.readObject();\n } finally {\n ois.close();\n }\n }\n } catch (ClassNotFoundException e) {\n throw new IOException2(e);\n }\n // start from scratch\n return ConsoleAnnotator.initial(context==null ? null : context.getClass());\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " public ApiTokenProperty newInstance(User user) {\n return new ApiTokenProperty(API_KEY_SEED.mac(user.getId()));\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " protected abstract void store(ConfidentialKey key, byte[] payload) throws IOException;\n\n /**\n * Reverse operation of {@link #store(ConfidentialKey, byte[])}\n *\n * @return\n * null the data has not been previously persisted, or if the data was tampered.\n */\n protected abstract @CheckForNull byte[] load(ConfidentialKey key) throws IOException;\n\n /**\n * Works like {@link SecureRandom#nextBytes(byte[])}.\n *\n * This enables implementations to consult other entropy sources, if it's available.\n */\n public abstract byte[] randomBytes(int size);\n\n /**\n * Retrieves the currently active singleton instance of {@link ConfidentialStore}.\n */\n public static @Nonnull ConfidentialStore get() {\n if (TEST!=null) return TEST.get();\n return Jenkins.getInstance().getExtensionList(ConfidentialStore.class).get(0);\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " public Mac createMac() {\n try {\n Mac mac = Mac.getInstance(ALGORITHM);\n mac.init(getKey());\n return mac;\n } catch (GeneralSecurityException e) {\n // Javadoc says HmacSHA256 must be supported by every Java implementation.\n throw new Error(ALGORITHM+\" not supported?\",e);\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " public byte[] mac(byte[] message) {\n return chop(createMac().doFinal(message));\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " protected void before() throws Throwable {\n tmp = Util.createTempDir();\n store = new DefaultConfidentialStore(tmp);\n ConfidentialStore.TEST.set(store);\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " public void test() throws Exception {\n jenkins.setNodes(Collections.singletonList(createNewJnlpSlave(\"test\")));\n HudsonTestCase.WebClient wc = new WebClient();\n HtmlPage p = wc.login(\"alice\").goTo(\"computer/test/\");\n\n // this fresh WebClient doesn't have a login cookie and represent JNLP launcher\n HudsonTestCase.WebClient jnlpAgent = new WebClient();\n\n // parse the JNLP page into DOM to list up the jars.\n XmlPage jnlp = (XmlPage) wc.goTo(\"computer/test/slave-agent.jnlp\",\"application/x-java-jnlp-file\");\n URL baseUrl = jnlp.getWebResponse().getUrl();\n Document dom = new DOMReader().read(jnlp.getXmlDocument());\n for( Element jar : (List)dom.selectNodes(\"//jar\") ) {\n URL url = new URL(baseUrl,jar.attributeValue(\"href\"));\n System.out.println(url);\n \n // now make sure that these URLs are unprotected\n Page jarResource = jnlpAgent.getPage(url);\n assertTrue(jarResource.getWebResponse().getContentType().toLowerCase(Locale.ENGLISH).startsWith(\"application/\"));\n }\n\n\n try {\n jnlp = (XmlPage) jnlpAgent.goTo(\"computer/test/slave-agent.jnlp\", \"application/x-java-jnlp-file\");\n fail(\"anonymous users must not be able to get secrets\");\n } catch (FailingHttpStatusCodeException x) {\n assertEquals(HttpURLConnection.HTTP_FORBIDDEN, x.getStatusCode());\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " /*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException {\n String secret = SECRET;\n if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();\n return Util.toAes128Key(secret);\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " protected boolean isIgnoredDir(File dir) {\n // ignoring the workspace and the artifacts directories. Both of them\n // are potentially large and they do not store any secrets.\n String n = dir.getName();\n return n.equals(\"workspace\") || n.equals(\"artifacts\")\n || n.equals(\"plugins\") // no mutable data here\n || n.equals(\"jenkins.security.RekeySecretAdminMonitor\") // we don't want to rewrite backups\n || n.equals(\".\") || n.equals(\"..\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " public static File getLogFile() {\n return new File(getBaseDir(),\"rekey.log\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " private UserCause(String userId, String message) {\n super(hudson.slaves.Messages._SlaveComputer_DisconnectedBy(userId, message));\n this.userId = userId;\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " /*package*/ Secret(String value) {\n this.value = value;\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "safe"} {"code": " public String getEncryptedValue() {\n try {\n synchronized (this) {\n if (iv == null) { //if we were created from plain text or other reason without iv\n iv = KEY.newIv();\n }\n }\n Cipher cipher = KEY.encrypt(iv);\n byte[] encrypted = cipher.doFinal(this.value.getBytes(UTF_8));\n byte[] payload = new byte[1 + 8 + iv.length + encrypted.length];\n int pos = 0;\n // For PAYLOAD_V1 we use this byte shifting model, V2 probably will need DataOutput\n payload[pos++] = PAYLOAD_V1;\n payload[pos++] = (byte)(iv.length >> 24);\n payload[pos++] = (byte)(iv.length >> 16);\n payload[pos++] = (byte)(iv.length >> 8);\n payload[pos++] = (byte)(iv.length);\n payload[pos++] = (byte)(encrypted.length >> 24);\n payload[pos++] = (byte)(encrypted.length >> 16);\n payload[pos++] = (byte)(encrypted.length >> 8);\n payload[pos++] = (byte)(encrypted.length);\n System.arraycopy(iv, 0, payload, pos, iv.length);\n pos+=iv.length;\n System.arraycopy(encrypted, 0, payload, pos, encrypted.length);\n return \"{\"+new String(Base64.encode(payload))+\"}\";\n } catch (GeneralSecurityException e) {\n throw new Error(e); // impossible\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "safe"} {"code": " public Cipher encrypt(byte[] iv) {\n try {\n Cipher cipher = Secret.getCipher(ALGORITHM);\n cipher.init(Cipher.ENCRYPT_MODE, getKey(), new IvParameterSpec(iv));\n return cipher;\n } catch (GeneralSecurityException e) {\n throw new AssertionError(e);\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "safe"} {"code": " public JenkinsRule j = new JenkinsRule() {\n @Override\n public void before() throws Throwable {\n Secret.resetKeyForTest(); //As early as possible\n super.before();\n }\n };", "label": 1, "programming_language": "Java", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "safe"} {"code": " public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n String qs = req.getQueryString();\n if(qs==null)\n throw new ServletException();\n Cookie cookie = new Cookie(\"iconSize\", Functions.validateIconSize(qs));\n cookie.setMaxAge(/* ~4 mo. */9999999); // #762\n rsp.addCookie(cookie);\n String ref = req.getHeader(\"Referer\");\n if(ref==null) ref=\".\";\n rsp.sendRedirect2(ref);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " static void loadWhitelist() {\n Properties whitelistProperties = new Properties();\n InputStream stream = null;\n try {\n stream = LookAheadObjectInputStream.class.getResourceAsStream(\"resource-serialization.properties\");\n whitelistProperties.load(stream);\n } catch (IOException e) {\n throw new RuntimeException(\"Error loading the ResourceBuilder.properties file\", e);\n } finally {\n if (stream != null) {\n try {\n stream.close();\n } catch (IOException e) {\n throw new RuntimeException(\"Error closing the ResourceBuilder.properties file\", e);\n }\n }\n }\n for (String baseClassName : whitelistProperties.getProperty(\"whitelist\").split(\",\")) {\n try {\n Class baseClass = Class.forName(baseClassName);\n whitelistBaseClasses.add(baseClass);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(\"Unable to load whiteList class \" + baseClassName, e);\n }\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "safe"} {"code": " public void handle(HttpServletRequest request, final HttpServletResponse response)\n throws Exception\n {\n // We're sending an XML response, so set the response content type to text/xml\n response.setContentType(\"text/xml\");\n\n // Parse the incoming request as XML\n SAXReader xmlReader = XML.getSafeSaxReader();\n Document doc = xmlReader.read(request.getInputStream());\n Element env = doc.getRootElement();\n\n final List polls = unmarshalRequests(env);\n\n new ContextualHttpServletRequest(request)\n {\n @Override\n public void process() throws Exception\n { \n for (PollRequest req : polls)\n {\n req.poll();\n }\n \n // Package up the response\n marshalResponse(polls, response.getOutputStream()); \n }\n }.run();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " public AbstractMobileEditForm(final P parentPage, final O data)\n {\n super(parentPage);\n this.data = data;\n csrfTokenHandler = new CsrfTokenHandler(this);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " protected void onInitialize()\n {\n super.onInitialize();\n final Form hiddenForm = new Form(\"hiddenForm\", new CompoundPropertyModel(new FormBean()));\n hiddenForm.add(AttributeModifier.replace(\"data-mimetype\", mimeType));\n main.add(hiddenForm);\n hiddenForm.add(new TextArea(\"importString\"));\n hiddenForm.add(new TextArea(\"importFileName\"));\n hiddenForm.add(new AjaxSubmitLink(\"submitButton\") {\n private static final long serialVersionUID = 6140567784494429257L;\n\n @Override\n protected void onSubmit(final AjaxRequestTarget target, final Form< ? > form)\n {\n csrfTokenHandler.onSubmit();\n final FormBean modelObject = hiddenForm.getModel().getObject();\n onStringImport(target, modelObject.importFileName, modelObject.importString);\n }\n\n @Override\n protected void onError(final AjaxRequestTarget target, final Form< ? > form)\n {\n // nothing to do here\n }\n\n });\n csrfTokenHandler = new CsrfTokenHandler(hiddenForm);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\n HttpSession session = request.getSession(false);\n String token = request.getHeader(LoginTokenServlet.LOGIN_TOKEN);\n\n if (token == null || session == null) {\n Helpers.doForbidden(response);\n return;\n }\n\n String sessionToken = (String) session.getAttribute(LoginTokenServlet.LOGIN_TOKEN);\n if (!token.equals(sessionToken)) {\n Helpers.doForbidden(response);\n return;\n }\n\n String encoding = request.getHeader(\"Accept-Encoding\");\n boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf(\"gzip\") > -1);\n SessionTerminal st = (SessionTerminal) session.getAttribute(\"terminal\");\n if (st == null || st.isClosed()) {\n st = new SessionTerminal(getCommandProcessor(), getThreadIO());\n session.setAttribute(\"terminal\", st);\n }\n String str = request.getParameter(\"k\");\n String f = request.getParameter(\"f\");\n String dump = st.handle(str, f != null && f.length() > 0);\n if (dump != null) {\n if (supportsGzip) {\n response.setHeader(\"Content-Encoding\", \"gzip\");\n response.setHeader(\"Content-Type\", \"text/html\");\n try {\n GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());\n gzos.write(dump.getBytes());\n gzos.close();\n } catch (IOException ie) {\n LOG.info(\"Exception writing response: \", ie);\n }\n } else {\n response.getOutputStream().write(dump.getBytes());\n }\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " public void simpleGetWithApplicationJsonMimeType() throws ServletException, IOException {\n checkMimeTypes(\"application/json\", \"application/json\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " private void validateCallbackIfGiven(ParsedUri pUri) {\n String callback = pUri.getParameter(ConfigKey.CALLBACK.getKeyValue());\n if (callback != null && !MimeTypeUtil.isValidCallback(callback)) {\n throw new IllegalArgumentException(\"Invalid callback name given, which must be a valid javascript function name\");\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public void debug() throws IOException, ServletException {\n servlet = new AgentServlet();\n initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), \"true\"},null,\"No access restrictor found\",null);\n context.log(find(\"URI:\"));\n context.log(find(\"Path-Info:\"));\n context.log(find(\"Request:\"));\n context.log(find(\"time:\"));\n context.log(find(\"Response:\"));\n context.log(find(\"TestDetector\"),isA(RuntimeException.class));\n expectLastCall().asStub();\n replay(config, context);\n\n servlet.init(config);\n\n StringWriter sw = initRequestResponseMocks();\n expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);\n expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);\n replay(request, response);\n\n servlet.doGet(request, response);\n\n assertTrue(sw.toString().contains(\"used\"));\n servlet.destroy();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " public void corsWildCard() {\n InputStream is = getClass().getResourceAsStream(\"/allow-origin2.xml\");\n PolicyRestrictor restrictor = new PolicyRestrictor(is);\n\n assertTrue(restrictor.isOriginAllowed(\"http://bla.com\", false));\n assertTrue(restrictor.isOriginAllowed(\"http://www.jolokia.org\", false));\n assertTrue(restrictor.isOriginAllowed(\"http://www.consol.de\", false));\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " private static final RestrictorCheck CORS_CHECK = new RestrictorCheck() {\n /** {@inheritDoc} */\n public boolean check(Restrictor restrictor, Object... args) {\n return restrictor.isOriginAllowed((String) args[0], (Boolean) args[1]);\n }\n };", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " public void testGetChunk() throws Exception {\n TestHttpData test = new TestHttpData(\"test\", UTF_8, 0);\n try {\n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n byte[] bytes = new byte[4096];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n test.setContent(tmpFile);\n ByteBuf buf1 = test.getChunk(1024);\n assertEquals(buf1.readerIndex(), 0);\n assertEquals(buf1.writerIndex(), 1024);\n ByteBuf buf2 = test.getChunk(1024);\n assertEquals(buf2.readerIndex(), 0);\n assertEquals(buf2.writerIndex(), 1024);\n assertFalse(\"Arrays should not be equal\",\n Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));\n } finally {\n test.delete();\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-378", "cwe_name": "Creation of Temporary File With Insecure Permissions", "description": "Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.", "url": "https://cwe.mitre.org/data/definitions/378.html", "label_name": "safe"} {"code": " public void setSetContentFromFileExceptionally() throws Exception {\n final long maxSize = 4;\n DiskFileUpload f1 = new DiskFileUpload(\"file5\", \"file5\", \"application/json\", null, null, 0);\n f1.setMaxSize(maxSize);\n try {\n f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));\n File originalFile = f1.getFile();\n assertNotNull(originalFile);\n assertEquals(maxSize, originalFile.length());\n assertEquals(maxSize, f1.length());\n byte[] bytes = new byte[8];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n try {\n f1.setContent(tmpFile);\n fail(\"should not reach here!\");\n } catch (IOException e) {\n assertNotNull(f1.getFile());\n assertEquals(originalFile, f1.getFile());\n assertEquals(maxSize, f1.length());\n }\n } finally {\n f1.delete();\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-378", "cwe_name": "Creation of Temporary File With Insecure Permissions", "description": "Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.", "url": "https://cwe.mitre.org/data/definitions/378.html", "label_name": "safe"} {"code": " public void setSetContentFromFileExceptionally() throws Exception {\n final long maxSize = 4;\n DiskFileUpload f1 = new DiskFileUpload(\"file5\", \"file5\", \"application/json\", null, null, 0);\n f1.setMaxSize(maxSize);\n try {\n f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));\n File originalFile = f1.getFile();\n assertNotNull(originalFile);\n assertEquals(maxSize, originalFile.length());\n assertEquals(maxSize, f1.length());\n byte[] bytes = new byte[8];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), \".tmp\", null);\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n try {\n f1.setContent(tmpFile);\n fail(\"should not reach here!\");\n } catch (IOException e) {\n assertNotNull(f1.getFile());\n assertEquals(originalFile, f1.getFile());\n assertEquals(maxSize, f1.length());\n }\n } finally {\n f1.delete();\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-379", "cwe_name": "Creation of Temporary File in Directory with Insecure Permissions", "description": "The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file.", "url": "https://cwe.mitre.org/data/definitions/379.html", "label_name": "safe"} {"code": " private static File newFile() throws IOException {\n File file = PlatformDependent.createTempFile(\"netty-\", \".tmp\", null);\n file.deleteOnExit();\n\n final FileOutputStream out = new FileOutputStream(file);\n out.write(data);\n out.close();\n return file;\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-378", "cwe_name": "Creation of Temporary File With Insecure Permissions", "description": "Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.", "url": "https://cwe.mitre.org/data/definitions/378.html", "label_name": "safe"} {"code": " void increaseReceivedBytes(boolean server, int streamId, int bytes, boolean isEnd) throws Http2Exception {\n seen += bytes;\n // Check for overflow\n if (seen < 0) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data did overflow and so not match content-length header %d\", expected);\n }\n // Check if we received more data then what was advertised via the content-length header.\n if (seen > expected) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data %d does not match content-length header %d\", seen, expected);\n }\n\n if (isEnd) {\n if (seen == 0 && !server) {\n // This may be a response to a HEAD request, let's just allow it.\n return;\n }\n\n // Check that we really saw what was told via the content-length header.\n if (expected > seen) {\n throw streamError(streamId, PROTOCOL_ERROR,\n \"Received amount of data %d does not match content-length header %d\", seen, expected);\n }\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " public void headersContentLengthPositiveSign() throws Exception {\n headersContentLengthSign(\"+1\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " public void multipleHeadersContentLengthSame() throws Exception {\n multipleHeadersContentLength(true);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " private static int findNonWhitespace(AppendableCharSequence sb, int offset) {\n for (int result = offset; result < sb.length(); ++result) {\n char c = sb.charAtUnsafe(result);\n if (!Character.isWhitespace(c)) {\n return result;\n } else if (!isOWS(c)) {\n // Only OWS is supported for whitespace\n throw new IllegalArgumentException(\"Invalid separator, only a single space or horizontal tab allowed,\" +\n \" but received a '\" + c + \"' (0x\" + Integer.toHexString(c) + \")\");\n }\n }\n return sb.length();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " private static void testInvalidHeaders0(ByteBuf requestBuffer) {\n EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestDecoder());\n assertTrue(channel.writeInbound(requestBuffer));\n HttpRequest request = channel.readInbound();\n assertThat(request.decoderResult().cause(), instanceOf(IllegalArgumentException.class));\n assertTrue(request.decoderResult().isFailure());\n assertFalse(channel.finish());\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": " public static File createTempFile(String prefix, String suffix, File directory) throws IOException {\n if (javaVersion() >= 7) {\n if (directory == null) {\n return Files.createTempFile(prefix, suffix).toFile();\n }\n return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();\n }\n final File file;\n if (directory == null) {\n file = File.createTempFile(prefix, suffix);\n } else {\n file = File.createTempFile(prefix, suffix, directory);\n }\n\n // Try to adjust the perms, if this fails there is not much else we can do...\n if (!file.setReadable(false, false)) {\n throw new IOException(\"Failed to set permissions on temporary file \" + file);\n }\n if (!file.setReadable(true, true)) {\n throw new IOException(\"Failed to set permissions on temporary file \" + file);\n }\n return file;\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-379", "cwe_name": "Creation of Temporary File in Directory with Insecure Permissions", "description": "The software creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file.", "url": "https://cwe.mitre.org/data/definitions/379.html", "label_name": "safe"} {"code": " public void setName(String name)\n {\n this.name = name;\n }", "label": 1, "programming_language": "Java", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "safe"} {"code": " public static void cleanup() {\n if ( path != null ) {\n FileUtils.deleteQuietly( path );\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " public static WebArchive getDeployment() {\n return ShrinkWrap.create(WebArchive.class).addAsWebInfResource(EmptyAsset.INSTANCE, \"beans.xml\")\n .addClasses(SimpleServlet.class, ConversationScopedBean.class);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "safe"} {"code": " protected OHttpSessionManager() {\r\n expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;\r\n\r\n Orient.instance().scheduleTask(new TimerTask() {\r\n @Override\r\n public void run() {\r\n final int expired = checkSessionsValidity();\r\n if (expired > 0)\r\n OLogManager.instance().debug(this, \"Removed %d session because expired\", expired);\r\n }\r\n }, expirationTime, expirationTime);\r\n }\r", "label": 1, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " public int checkSessionsValidity() {\r\n int expired = 0;\r\n\r\n acquireExclusiveLock();\r\n try {\r\n final long now = System.currentTimeMillis();\r\n\r\n Entry s;\r\n for (Iterator> it = sessions.entrySet().iterator(); it.hasNext();) {\r\n s = it.next();\r\n\r\n if (now - s.getValue().getUpdatedOn() > expirationTime) {\r\n // REMOVE THE SESSION\r\n it.remove();\r\n expired++;\r\n }\r\n }\r\n\r\n } finally {\r\n releaseExclusiveLock();\r\n }\r\n\r\n return expired;\r\n }\r", "label": 1, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " public void sendResponse(Throwable error) throws IOException {\n BytesStreamOutput stream = new BytesStreamOutput();\n if (ThrowableObjectOutputStream.canSerialize(error) == false) {\n assert false : \"Can not serialize exception: \" + error; // make sure tests fail\n error = new NotSerializableTransportException(error);\n }\n try {\n writeResponseExceptionHeader(stream);\n RemoteTransportException tx = new RemoteTransportException(targetTransport.nodeName(), targetTransport.boundAddress().boundAddress(), action, error);\n ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);\n too.writeObject(tx);\n too.close();\n } catch (NotSerializableException e) {\n stream.reset();\n writeResponseExceptionHeader(stream);\n RemoteTransportException tx = new RemoteTransportException(targetTransport.nodeName(), targetTransport.boundAddress().boundAddress(), action, new NotSerializableTransportException(error));\n ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);\n too.writeObject(tx);\n too.close();\n }\n final byte[] data = stream.bytes().toBytes();\n targetTransport.workers().execute(new Runnable() {\n @Override\n public void run() {\n targetTransport.messageReceived(data, action, sourceTransport, version, null);\n }\n });\n sourceTransportServiceAdapter.onResponseSent(requestId, action, error);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo)\n throws IOException\n {\n XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());\n this.treeDigest = keyParams.getTreeDigest().getAlgorithm();\n\n XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());\n\n try\n {\n XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters\n .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest)))\n .withIndex(xmssMtPrivateKey.getIndex())\n .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed())\n .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF())\n .withPublicSeed(xmssMtPrivateKey.getPublicSeed())\n .withRoot(xmssMtPrivateKey.getRoot());\n\n if (xmssMtPrivateKey.getBdsState() != null)\n {\n keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState(), BDSStateMap.class));\n }\n\n this.keyParams = keyBuilder.build();\n }\n catch (ClassNotFoundException e)\n {\n throw new IOException(\"ClassNotFoundException processing BDS state: \" + e.getMessage());\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "safe"} {"code": " public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)\n throws IOException\n {\n XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());\n this.treeDigest = keyParams.getTreeDigest().getAlgorithm();\n\n XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());\n\n try\n {\n XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters\n .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))\n .withIndex(xmssPrivateKey.getIndex())\n .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())\n .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())\n .withPublicSeed(xmssPrivateKey.getPublicSeed())\n .withRoot(xmssPrivateKey.getRoot());\n\n if (xmssPrivateKey.getBdsState() != null)\n {\n keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState(), BDS.class));\n }\n\n this.keyParams = keyBuilder.build();\n }\n catch (ClassNotFoundException e)\n {\n throw new IOException(\"ClassNotFoundException processing BDS state: \" + e.getMessage());\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "safe"} {"code": " protected Class resolveClass(ObjectStreamClass desc)\n throws IOException,\n ClassNotFoundException\n {\n if (!found)\n {\n if (!desc.getName().equals(mainClass.getName()))\n {\n throw new InvalidClassException(\n \"unexpected class: \", desc.getName());\n }\n else\n {\n found = true;\n }\n }\n else\n {\n if (!components.contains(desc.getName()))\n {\n throw new InvalidClassException(\n \"unexpected class: \", desc.getName());\n }\n }\n return super.resolveClass(desc);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-470", "cwe_name": "Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')", "description": "The application uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code.", "url": "https://cwe.mitre.org/data/definitions/470.html", "label_name": "safe"} {"code": " protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)\n {\n int iterations = getNumberOfIterations(bitlength, param.getCertainty());\n\n for (int i = 0; i != 5 * bitlength; i++)\n {\n BigInteger p = new BigInteger(bitlength, 1, param.getRandom());\n\n if (p.mod(e).equals(ONE))\n {\n continue;\n }\n\n if (p.multiply(p).compareTo(sqrdBound) < 0)\n {\n continue;\n }\n\n if (!isProbablePrime(p, iterations))\n {\n continue;\n }\n\n if (!e.gcd(p.subtract(ONE)).equals(ONE))\n {\n continue;\n }\n\n return p;\n }\n\n throw new IllegalStateException(\"unable to generate prime number for RSA key\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-327", "cwe_name": "Use of a Broken or Risky Cryptographic Algorithm", "description": "The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.", "url": "https://cwe.mitre.org/data/definitions/327.html", "label_name": "safe"} {"code": " public void engineInit(\n int opmode,\n Key key,\n SecureRandom random)\n throws InvalidKeyException\n {\n try\n {\n engineInit(opmode, key, (AlgorithmParameterSpec)null, random);\n }\n catch (InvalidAlgorithmParameterException e)\n {\n throw new IllegalArgumentException(\"cannot handle supplied parameter spec: \" + e.getMessage());\n }\n\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " BCDHPublicKey(\n DHPublicKeyParameters params)\n {\n this.y = params.getY();\n this.dhSpec = new DHParameterSpec(params.getParameters().getP(), params.getParameters().getG(), params.getParameters().getL());\n this.dhPublicKey = params;\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " public CFB()\n {\n super(new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 128)), 128);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " public PBEWithSHA1AESCBC256()\n {\n super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 256, 16);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " public PBEWithSHA1AESCBC128()\n {\n super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 128, 16);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " private void testDESAndDESede(BigInteger g, BigInteger p)\n throws Exception\n {\n DHParameterSpec dhParams = new DHParameterSpec(p, g, 256);\n\n KeyPairGenerator keyGen = KeyPairGenerator.getInstance(\"DH\", \"BC\");\n\n keyGen.initialize(dhParams);\n\n KeyPair kp = keyGen.generateKeyPair();\n\n KeyAgreement keyAgreement = KeyAgreement.getInstance(\"DH\", \"BC\");\n\n keyAgreement.init(kp.getPrivate());\n keyAgreement.doPhase(kp.getPublic(), true);\n\n SecretKey key = keyAgreement.generateSecret(\"DES\");\n\n if (key.getEncoded().length != 8)\n {\n fail(\"DES length wrong\");\n }\n\n if (!DESKeySpec.isParityAdjusted(key.getEncoded(), 0))\n {\n fail(\"DES parity wrong\");\n }\n\n key = keyAgreement.generateSecret(\"DESEDE\");\n\n if (key.getEncoded().length != 24)\n {\n fail(\"DESEDE length wrong\");\n }\n\n if (!DESedeKeySpec.isParityAdjusted(key.getEncoded(), 0))\n {\n fail(\"DESEDE parity wrong\");\n }\n\n key = keyAgreement.generateSecret(\"Blowfish\");\n\n if (key.getEncoded().length != 16)\n {\n fail(\"Blowfish length wrong\");\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " private void testKeyGenerationAll()\n throws Exception\n {\n testKeyGeneration(1024);\n testKeyGeneration(2048);\n testKeyGeneration(3072);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": " protected void initOther() throws ServletException {\n HashSet suppressProperties = new HashSet();\n suppressProperties.add(\"class\");\n suppressProperties.add(\"multipartRequestHandler\");\n suppressProperties.add(\"resultValueMap\");\n\n PropertyUtils.addBeanIntrospector(\n new SuppressPropertiesBeanIntrospector(suppressProperties));\n PropertyUtils.clearDescriptors();\n\n String value = null;\n value = getServletConfig().getInitParameter(\"config\");\n if (value != null) {\n config = value;\n }\n\n // Backwards compatibility for form beans of Java wrapper classes\n // Set to true for strict Struts 1.0 compatibility\n value = getServletConfig().getInitParameter(\"convertNull\");\n if (\"true\".equalsIgnoreCase(value)\n || \"yes\".equalsIgnoreCase(value)\n || \"on\".equalsIgnoreCase(value)\n || \"y\".equalsIgnoreCase(value)\n || \"1\".equalsIgnoreCase(value)) {\n\n convertNull = true;\n }\n\n if (convertNull) {\n ConvertUtils.deregister();\n ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);\n ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);\n ConvertUtils.register(new BooleanConverter(null), Boolean.class);\n ConvertUtils.register(new ByteConverter(null), Byte.class);\n ConvertUtils.register(new CharacterConverter(null), Character.class);\n ConvertUtils.register(new DoubleConverter(null), Double.class);\n ConvertUtils.register(new FloatConverter(null), Float.class);\n ConvertUtils.register(new IntegerConverter(null), Integer.class);\n ConvertUtils.register(new LongConverter(null), Long.class);\n ConvertUtils.register(new ShortConverter(null), Short.class);\n }\n\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "\tpublic String getOrderBy() {\n\t\treturn SQLUtil.sanitizeSortBy(orderBy);\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "\tstatic Set getFunctionAliases(String query) {\n\n\t\tSet result = new HashSet();\n\t\tMatcher matcher = FUNCTION_PATTERN.matcher(query);\n\n\t\twhile (matcher.find()) {\n\n\t\t\tString alias = matcher.group(FUNCTION_ALIAS_GROUP_NAME);\n\t\t\tif (StringUtils.hasText(alias)) {\n\t\t\t\tresult.add(alias);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " public Process execute()\n throws CommandLineException\n {\n // TODO: Provided only for backward compat. with <= 1.4\n verifyShellState();\n\n Process process;\n\n //addEnvironment( \"MAVEN_TEST_ENVAR\", \"MAVEN_TEST_ENVAR_VALUE\" );\n\n String[] environment = getEnvironmentVariables();\n\n File workingDir = shell.getWorkingDirectory();\n\n try\n {\n if ( workingDir == null )\n {\n process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir );\n }\n else\n {\n if ( !workingDir.exists() )\n {\n throw new CommandLineException( \"Working directory \\\"\" + workingDir.getPath()\n + \"\\\" does not exist!\" );\n }\n else if ( !workingDir.isDirectory() )\n {\n throw new CommandLineException( \"Path \\\"\" + workingDir.getPath()\n + \"\\\" does not specify a directory.\" );\n }\n\n process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir );\n }\n }\n catch ( IOException ex )\n {\n throw new CommandLineException( \"Error while executing process.\", ex );\n }\n\n return process;\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " protected String quoteOneItem( String path, boolean isExecutable )\n {\n if ( path == null )\n {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append( \"'\" );\n sb.append( path.replace( \"'\", \"'\\\"'\\\"'\" ) );\n sb.append( \"'\" );\n\n return sb.toString();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " public List getShellCommandLine( String[] arguments )\n {\n\n List commandLine = new ArrayList();\n\n if ( getShellCommand() != null )\n {\n commandLine.add( getShellCommand() );\n }\n\n if ( getShellArgs() != null )\n {\n commandLine.addAll( getShellArgsList() );\n }\n\n commandLine.addAll( getCommandLine( getOriginalExecutable(), arguments ) );\n\n return commandLine;\n\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " public void testGetShellCommandLineBash_WithSingleQuotedArg()\n throws Exception\n {\n Commandline cmd = new Commandline( new BourneShell() );\n cmd.setExecutable( \"/bin/echo\" );\n cmd.addArguments( new String[] {\n \"\\'hello world\\'\"\n } );\n\n String[] shellCommandline = cmd.getShellCommandline();\n\n assertEquals( \"Command line size\", 3, shellCommandline.length );\n\n assertEquals( \"/bin/sh\", shellCommandline[0] );\n assertEquals( \"-c\", shellCommandline[1] );\n String expectedShellCmd = \"'/bin/echo' ''\\\"'\\\"'hello world'\\\"'\\\"''\";\n if ( Os.isFamily( Os.FAMILY_WINDOWS ) )\n {\n expectedShellCmd = \"\\\\bin\\\\echo \\'hello world\\'\";\n }\n assertEquals( expectedShellCmd, shellCommandline[2] );\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " public void testGetShellCommandLineBash()\n throws Exception\n {\n Commandline cmd = new Commandline( new BourneShell() );\n cmd.setExecutable( \"/bin/echo\" );\n cmd.addArguments( new String[] {\n \"hello world\"\n } );\n\n String[] shellCommandline = cmd.getShellCommandline();\n\n assertEquals( \"Command line size\", 3, shellCommandline.length );\n\n assertEquals( \"/bin/sh\", shellCommandline[0] );\n assertEquals( \"-c\", shellCommandline[1] );\n String expectedShellCmd = \"'/bin/echo' 'hello world'\";\n if ( Os.isFamily( Os.FAMILY_WINDOWS ) )\n {\n expectedShellCmd = \"\\\\bin\\\\echo \\'hello world\\'\";\n }\n assertEquals( expectedShellCmd, shellCommandline[2] );\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep()\n {\n Shell sh = newShell();\n\n sh.setWorkingDirectory( \"\\\\usr\\\\local\\\\'something else'\" );\n sh.setExecutable( \"chmod\" );\n\n String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), \" \" );\n\n assertEquals( \"/bin/sh -c cd '\\\\usr\\\\local\\\\\\'\\\"'\\\"'something else'\\\"'\\\"'' && 'chmod'\", executable );\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " public void testEscapeSingleQuotesOnArgument()\n {\n Shell sh = newShell();\n\n sh.setWorkingDirectory( \"/usr/bin\" );\n sh.setExecutable( \"chmod\" );\n\n String[] args = { \"arg'withquote\" };\n\n List shellCommandLine = sh.getShellCommandLine( args );\n\n String cli = StringUtils.join( shellCommandLine.iterator(), \" \" );\n System.out.println( cli );\n assertEquals(\"cd '/usr/bin' && 'chmod' 'arg'\\\"'\\\"'withquote'\", shellCommandLine.get(shellCommandLine.size() - 1));\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": "\tpublic static boolean isPointOnCurve(final ECPublicKey publicKey, final ECParameterSpec ecParameterSpec) {\n\t\t\n\t\tECPoint point = publicKey.getW();\n\t\treturn isPointOnCurve(point.getAffineX(), point.getAffineY(), ecParameterSpec);\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "safe"} {"code": "\tprivate static ECPublicKey generateECPublicKey(final ECKey.Curve curve)\n\t\tthrows Exception {\n\t\t\n\t\tfinal ECParameterSpec ecParameterSpec = curve.toECParameterSpec();\n\t\t\n\t\tKeyPairGenerator generator = KeyPairGenerator.getInstance(\"EC\");\n\t\tgenerator.initialize(ecParameterSpec);\n\t\tKeyPair keyPair = generator.generateKeyPair();\n\t\t\n\t\treturn (ECPublicKey) keyPair.getPublic();\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "safe"} {"code": "\tpublic void testCurveCheckOk()\n\t\tthrows Exception {\n\t\t\n\t\tECPublicKey ephemeralPublicKey = generateECPublicKey(ECKey.Curve.P_256);\n\t\tECPrivateKey privateKey = generateECPrivateKey(ECKey.Curve.P_256);\n\t\tassertTrue(ECChecks.isPointOnCurve(ephemeralPublicKey, privateKey));\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "safe"} {"code": "\tpublic void testMatchOperations() {\n\n\t\tJWKMatcher matcher = new JWKMatcher.Builder().keyOperations(new LinkedHashSet<>(Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY))).build();\n\n\t\tassertTrue(matcher.matches(new RSAKey.Builder(new Base64URL(\"n\"), new Base64URL(\"e\")).keyID(\"1\")\n\t\t\t.keyOperations(new HashSet<>(Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY))).build()));\n\t\tassertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, EC_P256_X, EC_P256_Y).keyID(\"2\").build()));\n\t\t\n\t\tassertEquals(\"key_ops=[sign, verify]\", matcher.toString());\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "safe"} {"code": "\tpublic void testSelectByUseNotSpecifiedOrSignature() {\n\n\t\tJWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyUses(KeyUse.SIGNATURE, null).build());\n\n\t\tList keyList = new ArrayList<>();\n\t\tkeyList.add(new RSAKey.Builder(new Base64URL(\"n\"), new Base64URL(\"e\")).keyID(\"1\").keyUse(KeyUse.SIGNATURE).build());\n\t\tkeyList.add(new ECKey.Builder(ECKey.Curve.P_256, EC_P256_X, EC_P256_Y).keyID(\"2\").build());\n\t\tkeyList.add(new ECKey.Builder(ECKey.Curve.P_256, EC_P256_X, EC_P256_Y).keyID(\"3\").keyUse(KeyUse.ENCRYPTION).build());\n\n\t\tJWKSet jwkSet = new JWKSet(keyList);\n\n\t\tList matches = selector.select(jwkSet);\n\n\t\tRSAKey key1 = (RSAKey)matches.get(0);\n\t\tassertEquals(KeyType.RSA, key1.getKeyType());\n\t\tassertEquals(KeyUse.SIGNATURE, key1.getKeyUse());\n\t\tassertEquals(\"1\", key1.getKeyID());\n\n\t\tECKey key2 = (ECKey)matches.get(1);\n\t\tassertEquals(KeyType.EC, key2.getKeyType());\n\t\tassertEquals(\"2\", key2.getKeyID());\n\n\t\tassertEquals(2, matches.size());\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "safe"} {"code": "\tpublic static byte[] decryptAuthenticated(final SecretKey secretKey,\n\t\t final byte[] iv,\n\t\t final byte[] cipherText,\n\t\t final byte[] aad,\n\t\t final byte[] authTag,\n\t\t final Provider ceProvider,\n\t\t\t\t\t\t final Provider macProvider)\n\t\tthrows JOSEException {\n\n\n\t\t// Extract MAC + AES/CBC keys from input secret key\n\t\tCompositeKey compositeKey = new CompositeKey(secretKey);\n\n\t\t// AAD length to 8 byte array\n\t\tbyte[] al = AAD.computeLength(aad);\n\n\t\t// Check MAC\n\t\tint hmacInputLength = aad.length + iv.length + cipherText.length + al.length;\n\t\tbyte[] hmacInput = ByteBuffer.allocate(hmacInputLength).\n\t\t\tput(aad).\n\t\t\tput(iv).\n\t\t\tput(cipherText).\n\t\t\tput(al).\n\t\t\tarray();\n\t\tbyte[] hmac = HMAC.compute(compositeKey.getMACKey(), hmacInput, macProvider);\n\n\t\tbyte[] expectedAuthTag = Arrays.copyOf(hmac, compositeKey.getTruncatedMACByteLength());\n\n\t\tif (! ConstantTimeUtils.areEqual(expectedAuthTag, authTag)) {\n\t\t\tthrow new JOSEException(\"MAC check failed\");\n\t\t}\n\n\t\treturn decrypt(compositeKey.getAESKey(), iv, cipherText, ceProvider);\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-354", "cwe_name": "Improper Validation of Integrity Check Value", "description": "The software does not validate or incorrectly validates the integrity check values or \"checksums\" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.", "url": "https://cwe.mitre.org/data/definitions/354.html", "label_name": "safe"} {"code": "\tpublic IntegerOverflowException() {\n\t\tsuper(\"Integer overflow\");\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-345", "cwe_name": "Insufficient Verification of Data Authenticity", "description": "The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.", "url": "https://cwe.mitre.org/data/definitions/345.html", "label_name": "safe"} {"code": "\tpublic void testSafeBitLength_OK()\n\t\tthrows JOSEException {\n\t\t\n\t\tassertEquals(8, ByteUtils.bitLength(1));\n\t\tassertEquals(16, ByteUtils.bitLength(2));\n\t\tassertEquals(32, ByteUtils.bitLength(4));\n\t\tassertEquals(64, ByteUtils.bitLength(8));\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-345", "cwe_name": "Insufficient Verification of Data Authenticity", "description": "The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.", "url": "https://cwe.mitre.org/data/definitions/345.html", "label_name": "safe"} {"code": " protected abstract void saveXML(final String writerString) throws IOException ;\n\n /**\n * When this method is called users name is changed, so also is the username\n * belonging to the group and the view. Also overwrites the \"users.xml\" file\n *\n * @param oldName a {@link java.lang.String} object.\n * @param newName a {@link java.lang.String} object.\n * @throws java.lang.Exception if any.\n */\n public void renameUser(final String oldName, final String newName) throws Exception {\n update();\n\n m_writeLock.lock();\n \n try {\n // Get the old data\n if (m_users.containsKey(oldName)) {\n final User data = m_users.get(oldName);\n if (data == null) {\n m_users.remove(oldName);\n throw new Exception(\"UserFactory:rename the data contained for old user \" + oldName + \" is null\");\n } else {\n if (m_users.containsKey(newName)) {\n throw new Exception(\"UserFactory: cannot rename user \" + oldName + \". An user with the given name \" + newName + \" already exists\");\n }\n\n // Rename the user in the user map.\n m_users.remove(oldName);\n data.setUserId(newName);\n m_users.put(newName, data);\n \n // Refresh the groups config first\n m_groupManager.update();\n \n // Rename the user in the group.\n m_groupManager.renameUser(oldName, newName);\n \n // Rename the user in the view.\n // viewFactory.renameUser(oldName, newName);\n }\n } else {\n throw new Exception(\"UserFactory:rename the old user name \" + oldName + \" is not found\");\n }\n \n _saveCurrent();\n } finally {\n m_writeLock.unlock();\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " public void testValidGroupIds() {\n testInvalidGroupId(\"John-Doe\",false);\n testInvalidGroupId(\"Jane/Doe\",false);\n testInvalidGroupId(\"John.Doe\",false);\n testInvalidGroupId(\"Jane#Doe\", false);\n testInvalidGroupId(\"John@D\u00f6e.com\", false);\n testInvalidGroupId(\"JohnDo\u00e9\", false);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " public void testValidUserIds() {\n testInvalidUserId(\"John-Doe\",false);\n testInvalidUserId(\"Jane/Doe\",false);\n testInvalidUserId(\"John.Doe\",false);\n testInvalidUserId(\"Jane#Doe\", false);\n testInvalidUserId(\"John@D\u00f6e.com\", false);\n testInvalidUserId(\"JohnDo\u00e9\", false);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " public void testInvalidUserIds() {\n testInvalidUserId(\"JohnDoe\",true);\n testInvalidUserId(\"Jane'Doe'\",true);\n testInvalidUserId(\"John&Doe\",true);\n testInvalidUserId(\"Jane\\\"\\\"Doe\",true);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " public void testInvalidUserIds() {\n testInvalidUserId(\"JohnDoe\",true);\n testInvalidUserId(\"Jane'Doe'\",true);\n testInvalidUserId(\"John&Doe\",true);\n testInvalidUserId(\"Jane\\\"\\\"Doe\",true);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public void testValidUserIds() {\n testInvalidUserId(\"John-Doe\",false);\n testInvalidUserId(\"Jane/Doe\",false);\n testInvalidUserId(\"John.Doe\",false);\n testInvalidUserId(\"Jane#Doe\", false);\n testInvalidUserId(\"John@D\u00f6e.com\", false);\n testInvalidUserId(\"JohnDo\u00e9\", false);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public void testValidUserIds() {\n testInvalidUserId(\"John-Doe\",false);\n testInvalidUserId(\"Jane/Doe\",false);\n testInvalidUserId(\"John.Doe\",false);\n testInvalidUserId(\"Jane#Doe\", false);\n testInvalidUserId(\"John@D\u00f6e.com\", false);\n testInvalidUserId(\"JohnDo\u00e9\", false);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public void setEntityResolver(EntityResolver entityResolver) {\n this.entityResolver = entityResolver;\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "safe"} {"code": " public InputSource resolveEntity(String publicId, String systemId) {\n // try create a relative URI reader...\n if ((systemId != null) && (systemId.length() > 0)) {\n if ((uriPrefix != null) && (systemId.indexOf(':') <= 0)) {\n systemId = uriPrefix + systemId;\n }\n }\n\n return new InputSource(systemId);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "safe"} {"code": " protected EntityResolver createDefaultEntityResolver(String systemId) {\n String prefix = null;\n\n if ((systemId != null) && (systemId.length() > 0)) {\n int idx = systemId.lastIndexOf('/');\n\n if (idx > 0) {\n prefix = systemId.substring(0, idx + 1);\n }\n }\n\n return new SAXEntityResolver(prefix);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "safe"} {"code": " public void process(InputStream in, ZipEntry zipEntry) throws IOException {\n String name = mapper.map(zipEntry.getName());\n if (name != null) {\n File file = new File(outputDir, name);\n\n /* If we see the relative traversal string of \"..\" we need to make sure\n * that the outputdir + name doesn't leave the outputdir. See\n * DirectoryTraversalMaliciousTest for details.\n */\n if (name.indexOf(\"..\") != -1 && !file.getCanonicalPath().startsWith(outputDir.getCanonicalPath())) {\n throw new ZipException(\"The file \"+name+\" is trying to leave the target output directory of \"+outputDir+\". Ignoring this file.\");\n }\n\n if (zipEntry.isDirectory()) {\n FileUtils.forceMkdir(file);\n }\n else {\n FileUtils.forceMkdir(file.getParentFile());\n\n if (log.isDebugEnabled() && file.exists()) {\n log.debug(\"Overwriting file '{}'.\", zipEntry.getName());\n }\n\n FileUtils.copy(in, file);\n }\n\n ZTFilePermissions permissions = ZipEntryUtil.getZTFilePermissions(zipEntry);\n if (permissions != null) {\n ZTFilePermissionsUtil.getDefaultStategy().setPermissions(file, permissions);\n }\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": "\tprivate static byte[] safelyAllocate(long len, int maxSize) throws RarException {\r\n\t\tif (maxSize < 0) {\r\n\t\t\tthrow new IllegalArgumentException(\"maxsize must be >= 0\");\r\n\t\t}\r\n\t\tif (len < 0 || len > (long)maxSize) {\r\n\t\t\tthrow new RarException(RarExceptionType.badRarArchive);\r\n\t\t}\r\n\t\treturn new byte[(int)len];\r\n\t}\r", "label": 1, "programming_language": "Java", "cwe_id": "CWE-835", "cwe_name": "Loop with Unreachable Exit Condition ('Infinite Loop')", "description": "The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.", "url": "https://cwe.mitre.org/data/definitions/835.html", "label_name": "safe"} {"code": " private void add0(int h, int i, final CharSequence name, final CharSequence value) {\n if (!(name instanceof AsciiString)) {\n HttpUtils.validateHeader(name);\n }\n if (!(value instanceof AsciiString)) {\n HttpUtils.validateHeader(value);\n }\n // Update the hash table.\n VertxHttpHeaders.MapEntry e = entries[i];\n VertxHttpHeaders.MapEntry newEntry;\n entries[i] = newEntry = new VertxHttpHeaders.MapEntry(h, name, value);\n newEntry.next = e;\n\n // Update the linked list.\n newEntry.addBefore(head);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " static boolean nameContainsForbiddenSequence(String name) {\n boolean result = false;\n if (name != null) {\n name = name.toLowerCase();\n \n result = name.startsWith(\".\") ||\n name.contains(\"../\") ||\n name.contains(\"..\\\\\") ||\n name.startsWith(\"/\") ||\n name.startsWith(\"\\\\\") ||\n name.endsWith(\"/\") ||\n \n name.contains(\"..%2f\") ||\n name.contains(\"..%5c\") ||\n name.startsWith(\"%2f\") ||\n name.startsWith(\"%5c\") ||\n name.endsWith(\"%2f\") ||\n \n name.contains(\"..\\\\u002f\") ||\n name.contains(\"..\\\\u005c\") ||\n name.startsWith(\"\\\\u002f\") ||\n name.startsWith(\"\\\\u005c\") ||\n name.endsWith(\"\\\\u002f\")\n \n ;\n }\n \n return result;\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " public void appendText(String text, final boolean doNotAppend) {\n if (text == null) {\n return;\n }\n final Editable editable = this.binding.textinput.getText();\n String previous = editable == null ? \"\" : editable.toString();\n if (doNotAppend && !TextUtils.isEmpty(previous)) {\n Toast.makeText(getActivity(),R.string.already_drafting_message, Toast.LENGTH_LONG).show();\n return;\n }\n if (UIHelper.isLastLineQuote(previous)) {\n text = '\\n' + text;\n } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {\n text = \" \" + text;\n }\n this.binding.textinput.append(text);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " private void processExtras(Bundle extras) {\n final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);\n final String text = extras.getString(Intent.EXTRA_TEXT);\n final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);\n final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);\n final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);\n final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);\n final List uris = extractUris(extras);\n if (uris != null && uris.size() > 0) {\n final List cleanedUris = cleanUris(new ArrayList<>(uris));\n mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));\n toggleInputMethod();\n return;\n }\n if (nick != null) {\n if (pm) {\n Jid jid = conversation.getJid();\n try {\n Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);\n privateMessageWith(next);\n } catch (final IllegalArgumentException ignored) {\n //do nothing\n }\n } else {\n final MucOptions mucOptions = conversation.getMucOptions();\n if (mucOptions.participating() || conversation.getNextCounterpart() != null) {\n highlightInConference(nick);\n }\n }\n } else {\n if (text != null && asQuote) {\n quoteText(text);\n } else {\n appendText(text, doNotAppend);\n }\n }\n final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);\n if (message != null) {\n startDownloadable(message);\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " public void testLocalhostNotMatching() throws Exception {\n SpringBusFactory bf = new SpringBusFactory();\n URL busFile = HostnameVerificationDeprecatedTest.class.getResource(\"hostname-client-bethal.xml\");\n\n Bus bus = bf.createBus(busFile.toString());\n BusFactory.setDefaultBus(bus);\n BusFactory.setThreadDefaultBus(bus);\n\n URL url = SOAPService.WSDL_LOCATION;\n SOAPService service = new SOAPService(url, SOAPService.SERVICE);\n assertNotNull(\"Service is null\", service);\n final Greeter port = service.getHttpsPort();\n assertNotNull(\"Port is null\", port);\n\n updateAddressPort(port, PORT);\n \n try {\n port.greetMe(\"Kitty\");\n fail(\"Failure expected on the hostname verification\");\n } catch (Exception ex) {\n // expected\n }\n\n ((java.io.Closeable)port).close();\n bus.shutdown(true);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-755", "cwe_name": "Improper Handling of Exceptional Conditions", "description": "The software does not handle or incorrectly handles an exceptional condition.", "url": "https://cwe.mitre.org/data/definitions/755.html", "label_name": "safe"} {"code": " public void create_withThreadPool() throws Exception {\n final QueuedThreadPool threadPool = new QueuedThreadPool(100);\n final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);\n final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);\n final Routes routes = mock(Routes.class);\n\n when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool));\n\n final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool);\n embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);\n\n embeddedServer.ignite(\"localhost\", 6758, null, 0, 0, 0);\n\n verify(jettyServerFactory, times(1)).create(threadPool);\n verifyNoMoreInteractions(jettyServerFactory);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": "\tprotected int getExpectedErrors() {\n\t\treturn 1;\n\t}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "safe"} {"code": " private void ensureHasEnoughBytes(int minimumExpected) {\n int remaining = trans_.getBytesRemainingInBuffer();\n if (remaining < 0) {\n return; // Some transport are not buffered\n }\n if (remaining < minimumExpected) {\n throw new TProtocolException(\n TProtocolException.INVALID_DATA,\n \"Not enough bytes to read the entire message, the data appears to be truncated\");\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "safe"} {"code": " public void testStringCompact() throws Exception {\n TMemoryInputTransport buf = new TMemoryInputTransport(kCompactStringEncoding);\n TProtocol iprot = new TCompactProtocol(buf);\n testTruncated(new MyStringStruct(), iprot);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "safe"} {"code": " public void testStringBinary() throws Exception {\n TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryStringEncoding);\n TProtocol iprot = new TBinaryProtocol(buf);\n testTruncated(new MyStringStruct(), iprot);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "safe"} {"code": "TEST(ProtocolSkipTest, SkipStopInContainer) {\n IOBufQueue queue;\n CompactProtocolWriter writer;\n writer.setOutput(&queue);\n writer.writeListBegin(TType::T_STOP, 1u << 30);\n auto buf = queue.move();\n CompactProtocolReader reader;\n reader.setInput(buf.get());\n bool thrown = false;\n try {\n reader.skip(TType::T_LIST);\n } catch (const TProtocolException& ex) {\n EXPECT_EQ(TProtocolException::INVALID_DATA, ex.getType());\n thrown = true;\n }\n EXPECT_TRUE(thrown);\n}", "label": 1, "programming_language": "Java", "cwe_id": "CWE-755", "cwe_name": "Improper Handling of Exceptional Conditions", "description": "The software does not handle or incorrectly handles an exceptional condition.", "url": "https://cwe.mitre.org/data/definitions/755.html", "label_name": "safe"} {"code": " final void add(CharSequence name, String... values) {\n final AsciiString normalizedName = HttpHeaderNames.of(name);\n requireNonNull(values, \"values\");\n final int h = normalizedName.hashCode();\n final int i = index(h);\n for (String v : values) {\n requireNonNullElement(values, v);\n add0(h, i, normalizedName, v);\n }\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " final void set(CharSequence name, String value) {\n final AsciiString normalizedName = HttpHeaderNames.of(name);\n requireNonNull(value, \"value\");\n final int h = normalizedName.hashCode();\n final int i = index(h);\n remove0(h, i, normalizedName);\n add0(h, i, normalizedName, value);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " void testOfAsciiString() {\n // Should produce a lower-cased AsciiString.\n final AsciiString mixedCased = AsciiString.of(\"Foo\");\n assertThat((Object) HttpHeaderNames.of(mixedCased)).isNotSameAs(mixedCased);\n assertThat(HttpHeaderNames.of(mixedCased).toString()).isEqualTo(\"foo\");\n\n // Should not produce a new instance for an AsciiString that's already lower-cased.\n final AsciiString lowerCased = AsciiString.of(\"foo\");\n assertThat((Object) HttpHeaderNames.of(lowerCased)).isSameAs(lowerCased);\n\n // Should reuse known header name instances.\n assertThat((Object) HttpHeaderNames.of(AsciiString.of(\"date\"))).isSameAs(HttpHeaderNames.DATE);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " void setShouldOverWritePreviousValue() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.set(\"name\", \"value1\");\n headers.set(\"name\", \"value2\");\n assertThat(headers.size()).isEqualTo(1);\n assertThat(headers.getAll(\"name\").size()).isEqualTo(1);\n assertThat(headers.getAll(\"name\").get(0)).isEqualTo(\"value2\");\n assertThat(headers.get(\"name\")).isEqualTo(\"value2\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " void testContains() {\n final HttpHeadersBase headers = newEmptyHeaders();\n\n headers.addLong(\"long\", Long.MAX_VALUE);\n assertThat(headers.containsLong(\"long\", Long.MAX_VALUE)).isTrue();\n assertThat(headers.containsLong(\"long\", Long.MIN_VALUE)).isFalse();\n\n headers.addInt(\"int\", Integer.MIN_VALUE);\n assertThat(headers.containsInt(\"int\", Integer.MIN_VALUE)).isTrue();\n assertThat(headers.containsInt(\"int\", Integer.MAX_VALUE)).isFalse();\n\n headers.addDouble(\"double\", Double.MAX_VALUE);\n assertThat(headers.containsDouble(\"double\", Double.MAX_VALUE)).isTrue();\n assertThat(headers.containsDouble(\"double\", Double.MIN_VALUE)).isFalse();\n\n headers.addFloat(\"float\", Float.MAX_VALUE);\n assertThat(headers.containsFloat(\"float\", Float.MAX_VALUE)).isTrue();\n assertThat(headers.containsFloat(\"float\", Float.MIN_VALUE)).isFalse();\n\n final long millis = System.currentTimeMillis();\n headers.addTimeMillis(\"millis\", millis);\n assertThat(headers.containsTimeMillis(\"millis\", millis)).isTrue();\n // This test doesn't work on midnight, January 1, 1970 UTC\n assertThat(headers.containsTimeMillis(\"millis\", 0)).isFalse();\n\n headers.addObject(\"object\", \"Hello World\");\n assertThat(headers.containsObject(\"object\", \"Hello World\")).isTrue();\n assertThat(headers.containsObject(\"object\", \"\")).isFalse();\n\n headers.add(\"name\", \"value\");\n assertThat(headers.contains(\"name\", \"value\")).isTrue();\n assertThat(headers.contains(\"name\", \"value1\")).isFalse();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " void removingANameForASecondTimeShouldReturnFalse() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\");\n headers.add(\"name2\", \"value2\");\n assertThat(headers.remove(\"name2\")).isTrue();\n assertThat(headers.remove(\"name2\")).isFalse();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " void subsetOfHeadersShouldNotBeEquivalent() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\");\n headers1.add(\"name2\", \"value2\");\n final HttpHeadersBase headers2 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\");\n assertThat(headers1).isNotEqualTo(headers2);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " void iteratorShouldReturnAllNameValuePairs() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\", \"value2\");\n headers1.add(\"name2\", \"value3\");\n headers1.add(\"name3\", \"value4\", \"value5\", \"value6\");\n headers1.add(\"name1\", \"value7\", \"value8\");\n assertThat(headers1.size()).isEqualTo(8);\n\n final HttpHeadersBase headers2 = newEmptyHeaders();\n for (Map.Entry entry : headers1) {\n headers2.add(entry.getKey(), entry.getValue());\n }\n\n assertThat(headers2).isEqualTo(headers1);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " static void closeClientFactory() {\n clientFactory.close();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " boolean isEncoded(int index) {\n return encoded != null && encoded.get(index);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " void doubleDotsInFreeFormQuery() {\n BAD_DOUBLE_DOT_PATTERNS.forEach(pattern -> {\n assertProhibited(\"/?\" + pattern);\n });\n\n GOOD_DOUBLE_DOT_PATTERNS.forEach(pattern -> {\n assertQueryStringAllowed(\"/?\" + pattern, pattern);\n });\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " void colon() {\n assertThat(parse(\"/:\")).isNotNull();\n assertThat(parse(\"/:/\")).isNotNull();\n assertThat(parse(\"/a/:\")).isNotNull();\n assertThat(parse(\"/a/:/\")).isNotNull();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " void ampersand() {\n final PathAndQuery res = parse(\"/&?a=1&a=2&b=3\");\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(\"/&\");\n assertThat(res.query()).isEqualTo(\"a=1&a=2&b=3\");\n\n // '%26' in a query string should never be decoded into '&'.\n final PathAndQuery res2 = parse(\"/%26?a=1%26a=2&b=3\");\n assertThat(res2).isNotNull();\n assertThat(res2.path()).isEqualTo(\"/&\");\n assertThat(res2.query()).isEqualTo(\"a=1%26a=2&b=3\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " void controlChars() {\n assertThat(parse(\"/\\0\")).isNull();\n assertThat(parse(\"/a\\nb\")).isNull();\n assertThat(parse(\"/a\\u007fb\")).isNull();\n\n // Escaped\n assertThat(parse(\"/%00\")).isNull();\n assertThat(parse(\"/a%09b\")).isNull();\n assertThat(parse(\"/a%0ab\")).isNull();\n assertThat(parse(\"/a%0db\")).isNull();\n assertThat(parse(\"/a%7fb\")).isNull();\n\n // With query string\n assertThat(parse(\"/\\0?c\")).isNull();\n assertThat(parse(\"/a\\tb?c\")).isNull();\n assertThat(parse(\"/a\\nb?c\")).isNull();\n assertThat(parse(\"/a\\rb?c\")).isNull();\n assertThat(parse(\"/a\\u007fb?c\")).isNull();\n\n // With query string with control chars\n assertThat(parse(\"/?\\0\")).isNull();\n assertThat(parse(\"/?%00\")).isNull();\n assertThat(parse(\"/?a\\u007fb\")).isNull();\n assertThat(parse(\"/?a%7Fb\")).isNull();\n // However, 0x0A, 0x0D, 0x09 should be accepted in a query string.\n assertThat(parse(\"/?a\\tb\").query()).isEqualTo(\"a%09b\");\n assertThat(parse(\"/?a\\nb\").query()).isEqualTo(\"a%0Ab\");\n assertThat(parse(\"/?a\\rb\").query()).isEqualTo(\"a%0Db\");\n assertThat(parse(\"/?a%09b\").query()).isEqualTo(\"a%09b\");\n assertThat(parse(\"/?a%0Ab\").query()).isEqualTo(\"a%0Ab\");\n assertThat(parse(\"/?a%0Db\").query()).isEqualTo(\"a%0Db\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " void percentEncodedPathParam() {\n final RoutingResultBuilder builder = RoutingResult.builder();\n final RoutingResult routingResult = builder.path(\"/foo\")\n .rawParam(\"bar\", \"%62az%2Fqu%78\")\n .build();\n assertThat(routingResult.pathParams()).containsOnly(Maps.immutableEntry(\"bar\", \"baz/qux\"));\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " private String escapeEl(@Nullable String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n final Matcher m = ESCAPE_PATTERN.matcher(s);\n final StringBuffer sb = new StringBuffer(s.length() + 16);\n while (m.find()) {\n m.appendReplacement(sb, \"\\\\\\\\\\\\${\");\n }\n m.appendTail(sb);\n\n return sb.toString();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " public void subValidateFail(ViolationCollector col) {\n col.addViolation(FAILED + \"subclass\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " public void validateFail(ViolationCollector col) {\n col.addViolation(\"${'value'}\");\n col.addViolation(\"${'property'}\", \"${'value'}\");\n col.addViolation(\"${'property'}\", 1, \"${'value'}\");\n col.addViolation(\"${'property'}\", \"${'key'}\", \"${'value'}\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " public static String escapeMessageParameter(@Nullable String messageParameter) {\n if (messageParameter == null) {\n return null;\n }\n return ESCAPE_MESSAGE_PARAMETER_PATTERN.matcher(messageParameter).replaceAll(Matcher.quoteReplacement(String.valueOf(ESCAPE_CHARACTER)) + \"$1\");\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " public void initialize(SelfValidating constraintAnnotation) {\n escapeExpressions = constraintAnnotation.escapeExpressions();\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": " public ViolationCollector(ConstraintValidatorContext constraintValidatorContext) {\n this(constraintValidatorContext, true);\n }", "label": 1, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "safe"} {"code": "static __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc,\n\t\tunsigned int *rsize)\n{\n\tswitch (hdev->product) {\n\tcase USB_DEVICE_ID_KYE_ERGO_525V:\n\t\t/* the fixups that need to be done:\n\t\t * - change led usage page to button for extra buttons\n\t\t * - report size 8 count 1 must be size 1 count 8 for button\n\t\t * bitfield\n\t\t * - change the button usage range to 4-7 for the extra\n\t\t * buttons\n\t\t */\n\t\tif (*rsize >= 74 &&\n\t\t\trdesc[61] == 0x05 && rdesc[62] == 0x08 &&\n\t\t\trdesc[63] == 0x19 && rdesc[64] == 0x08 &&\n\t\t\trdesc[65] == 0x29 && rdesc[66] == 0x0f &&\n\t\t\trdesc[71] == 0x75 && rdesc[72] == 0x08 &&\n\t\t\trdesc[73] == 0x95 && rdesc[74] == 0x01) {\n\t\t\thid_info(hdev,\n\t\t\t\t \"fixing up Kye/Genius Ergo Mouse \"\n\t\t\t\t \"report descriptor\\n\");\n\t\t\trdesc[62] = 0x09;\n\t\t\trdesc[64] = 0x04;\n\t\t\trdesc[66] = 0x07;\n\t\t\trdesc[72] = 0x01;\n\t\t\trdesc[74] = 0x08;\n\t\t}\n\t\tbreak;\n\tcase USB_DEVICE_ID_KYE_EASYPEN_I405X:\n\t\tif (*rsize == EASYPEN_I405X_RDESC_ORIG_SIZE) {\n\t\t\trdesc = easypen_i405x_rdesc_fixed;\n\t\t\t*rsize = sizeof(easypen_i405x_rdesc_fixed);\n\t\t}\n\t\tbreak;\n\tcase USB_DEVICE_ID_KYE_MOUSEPEN_I608X:\n\t\tif (*rsize == MOUSEPEN_I608X_RDESC_ORIG_SIZE) {\n\t\t\trdesc = mousepen_i608x_rdesc_fixed;\n\t\t\t*rsize = sizeof(mousepen_i608x_rdesc_fixed);\n\t\t}\n\t\tbreak;\n\tcase USB_DEVICE_ID_KYE_EASYPEN_M610X:\n\t\tif (*rsize == EASYPEN_M610X_RDESC_ORIG_SIZE) {\n\t\t\trdesc = easypen_m610x_rdesc_fixed;\n\t\t\t*rsize = sizeof(easypen_m610x_rdesc_fixed);\n\t\t}\n\t\tbreak;\n\tcase USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE:\n\t\trdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104,\n\t\t\t\t\t\"Genius Gila Gaming Mouse\");\n\t\tbreak;\n\tcase USB_DEVICE_ID_GENIUS_GX_IMPERATOR:\n\t\trdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 83,\n\t\t\t\t\t\"Genius Gx Imperator Keyboard\");\n\t\tbreak;\n\tcase USB_DEVICE_ID_GENIUS_MANTICORE:\n\t\trdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104,\n\t\t\t\t\t\"Genius Manticore Keyboard\");\n\t\tbreak;\n\t}\n\treturn rdesc;\n}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": " public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {\n \n Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);\n String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE);\n Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);\n \n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n if (err != null) {\n err.printStackTrace(pw);\n } else {\n pw.println(\"(none)\");\n }\n pw.flush();\n \n // If we are here there was no error servlet, so show the default error page\n String output = Launcher.RESOURCES.getString(\"WinstoneResponse.ErrorPage\",\n new String[] { sc + \"\", (msg == null ? \"\" : msg), sw.toString(),\n Launcher.RESOURCES.getString(\"ServerVersion\"),\n \"\" + new Date() });\n response.setContentLength(output.getBytes(response.getCharacterEncoding()).length);\n Writer out = response.getWriter();\n out.write(output);\n out.flush();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " /*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException {\n String secret = SECRET;\n if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();\n return Util.toAes128Key(secret);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "vulnerable"} {"code": " public SecretRewriter() throws GeneralSecurityException {\n cipher = Secret.getCipher(\"AES\");\n key = Secret.getLegacyKey();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "vulnerable"} {"code": " private String tryRewrite(String s) throws IOException, InvalidKeyException {\n if (s.length()<24)\n return s; // Encrypting \"\" in Secret produces 24-letter characters, so this must be the minimum length\n if (!isBase64(s))\n return s; // decode throws IOException if the input is not base64, and this is also a very quick way to filter\n\n byte[] in;\n try {\n in = Base64.decode(s.toCharArray());\n } catch (IOException e) {\n return s; // not a valid base64\n }\n cipher.init(Cipher.DECRYPT_MODE, key);\n Secret sec = Secret.tryDecrypt(cipher, in);\n if(sec!=null) // matched\n return sec.getEncryptedValue(); // replace by the new encrypted value\n else // not encrypted with the legacy key. leave it unmodified\n return s;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "vulnerable"} {"code": " public Cipher encrypt() {\n try {\n Cipher cipher = Secret.getCipher(ALGORITHM);\n cipher.init(Cipher.ENCRYPT_MODE, getKey());\n return cipher;\n } catch (GeneralSecurityException e) {\n throw new AssertionError(e);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-326", "cwe_name": "Inadequate Encryption Strength", "description": "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", "url": "https://cwe.mitre.org/data/definitions/326.html", "label_name": "vulnerable"} {"code": " protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\n\n resp.setContentType(\"application/json\");\n final PrintWriter out = resp.getWriter();\n\n HttpSession session = req.getSession(false);\n\n if (session != null) {\n Subject subject = (Subject) session.getAttribute(\"subject\");\n if (subject == null) {\n LOG.warn(\"No security subject stored in existing session, invalidating\");\n session.invalidate();\n Helpers.doForbidden(resp);\n }\n returnPrincipals(subject, out);\n return;\n }\n\n AccessControlContext acc = AccessController.getContext();\n Subject subject = Subject.getSubject(acc);\n\n if (subject == null) {\n Helpers.doForbidden(resp);\n return;\n }\n Set principals = subject.getPrincipals();\n\n String username = null;\n\n if (principals != null) {\n for (Principal principal : principals) {\n if (principal.getClass().getSimpleName().equals(\"UserPrincipal\")) {\n username = principal.getName();\n LOG.debug(\"Authorizing user {}\", username);\n }\n }\n }\n\n session = req.getSession(true);\n session.setAttribute(\"subject\", subject);\n session.setAttribute(\"user\", username);\n session.setAttribute(\"org.osgi.service.http.authentication.remote.user\", username);\n session.setAttribute(\"org.osgi.service.http.authentication.type\", HttpServletRequest.BASIC_AUTH);\n session.setAttribute(\"loginTime\", GregorianCalendar.getInstance().getTimeInMillis());\n if (timeout != null) {\n session.setMaxInactiveInterval(timeout);\n }\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Http session timeout for user {} is {} sec.\", username, session.getMaxInactiveInterval());\n }\n\n returnPrincipals(subject, out);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " public void testCallbackPost() throws URISyntaxException, IOException, java.text.ParseException {\n HttpExchange exchange = prepareExchange(\"http://localhost:8080/jolokia?callback=data\",\n \"Content-Type\",\"text/plain; charset=UTF-8\",\n \"Origin\",null\n );\n\n // Simple GET method\n prepareMemoryPostReadRequest(exchange);\n Headers header = new Headers();\n ByteArrayOutputStream out = prepareResponse(handler, exchange, header);\n\n handler.doHandle(exchange);\n\n assertEquals(header.getFirst(\"content-type\"),\"text/javascript; charset=utf-8\");\n String result = out.toString(\"utf-8\");\n assertTrue(result.endsWith(\"});\"));\n assertTrue(result.startsWith(\"data({\"));\n assertTrue(result.contains(\"\\\"used\\\"\"));\n\n assertEquals(header.getFirst(\"Cache-Control\"),\"no-cache\");\n assertEquals(header.getFirst(\"Pragma\"),\"no-cache\");\n SimpleDateFormat rfc1123Format = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss zzz\", Locale.US);\n rfc1123Format.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n String expires = header.getFirst(\"Expires\");\n String date = header.getFirst(\"Date\");\n\n Date parsedExpires = rfc1123Format.parse(expires);\n Date parsedDate = rfc1123Format.parse(date);\n assertTrue(parsedExpires.before(parsedDate) || parsedExpires.equals(parsedDate));\n Date now = new Date();\n assertTrue(parsedExpires.before(now) || parsedExpires.equals(now));\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " public void preflightCheckNegative() {\n String origin = \"http://bla.com\";\n String headers =\"X-Data: Test\";\n expect(backend.isCorsAccessAllowed(origin)).andReturn(false);\n replay(backend);\n\n Map ret = handler.handleCorsPreflightRequest(origin, headers);\n assertNull(ret.get(\"Access-Control-Allow-Origin\"));\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " public void testRenameTo() throws Exception {\n TestHttpData test = new TestHttpData(\"test\", UTF_8, 0);\n try {\n File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n tmpFile.deleteOnExit();\n final int totalByteCount = 4096;\n byte[] bytes = new byte[totalByteCount];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n ByteBuf content = Unpooled.wrappedBuffer(bytes);\n test.setContent(content);\n boolean succ = test.renameTo(tmpFile);\n assertTrue(succ);\n FileInputStream fis = new FileInputStream(tmpFile);\n try {\n byte[] buf = new byte[totalByteCount];\n int count = 0;\n int offset = 0;\n int size = totalByteCount;\n while ((count = fis.read(buf, offset, size)) > 0) {\n offset += count;\n size -= count;\n if (offset >= totalByteCount || size <= 0) {\n break;\n }\n }\n assertArrayEquals(bytes, buf);\n assertEquals(0, fis.available());\n } finally {\n fis.close();\n }\n } finally {\n //release the ByteBuf in AbstractMemoryHttpData\n test.delete();\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-378", "cwe_name": "Creation of Temporary File With Insecure Permissions", "description": "Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.", "url": "https://cwe.mitre.org/data/definitions/378.html", "label_name": "vulnerable"} {"code": " public static void beforeClass() throws IOException {\n final Random r = new Random();\n for (int i = 0; i < BYTES.length; i++) {\n BYTES[i] = (byte) r.nextInt(255);\n }\n\n tmp = File.createTempFile(\"netty-traffic\", \".tmp\");\n tmp.deleteOnExit();\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(tmp);\n out.write(BYTES);\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n // ignore\n }\n }\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-378", "cwe_name": "Creation of Temporary File With Insecure Permissions", "description": "Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.", "url": "https://cwe.mitre.org/data/definitions/378.html", "label_name": "vulnerable"} {"code": " public static File createTempFile(String prefix, String suffix, File directory) throws IOException {\n if (javaVersion() >= 7) {\n if (directory == null) {\n return Files.createTempFile(prefix, suffix).toFile();\n }\n return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();\n }\n if (directory == null) {\n return File.createTempFile(prefix, suffix);\n }\n File file = File.createTempFile(prefix, suffix, directory);\n // Try to adjust the perms, if this fails there is not much else we can do...\n file.setReadable(false, false);\n file.setReadable(true, true);\n return file;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-378", "cwe_name": "Creation of Temporary File With Insecure Permissions", "description": "Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack.", "url": "https://cwe.mitre.org/data/definitions/378.html", "label_name": "vulnerable"} {"code": " private FileItem getFileItem(HttpServletRequest request) throws FileUploadException {\n Iterator iterator = getServletFileUpload().parseRequest(request).iterator();\n while (iterator.hasNext()) {\n FileItem item = (FileItem) iterator.next();\n if (!item.isFormField()) {\n return item;\n }\n }\n return null;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": " public void cleanup() {\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": " public int checkSessionsValidity() {\r\n int expired = 0;\r\n\r\n acquireExclusiveLock();\r\n try {\r\n final long now = System.currentTimeMillis();\r\n\r\n Entry s;\r\n for (Iterator> it = sessions.entrySet().iterator(); it.hasNext();) {\r\n s = it.next();\r\n\r\n if (now - s.getValue().getUpdatedOn() > expirationTime) {\r\n // REMOVE THE SESSION\r\n it.remove();\r\n expired++;\r\n }\r\n }\r\n\r\n } finally {\r\n releaseExclusiveLock();\r\n }\r\n\r\n return expired;\r\n }\r", "label": 0, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " public void testPrivateKeyParsingSHA256()\n throws IOException, ClassNotFoundException\n {\n XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest());\n XMSSMT mt = new XMSSMT(params, new SecureRandom());\n mt.generateKeys();\n byte[] privateKey = mt.exportPrivateKey();\n byte[] publicKey = mt.exportPublicKey();\n\n mt.importState(privateKey, publicKey);\n\n assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey()));\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "vulnerable"} {"code": " protected boolean isProbablePrime(BigInteger x)\n {\n /*\n * Primes class for FIPS 186-4 C.3 primality checking\n */\n return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-327", "cwe_name": "Use of a Broken or Risky Cryptographic Algorithm", "description": "The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.", "url": "https://cwe.mitre.org/data/definitions/327.html", "label_name": "vulnerable"} {"code": " public void init(KeyGenerationParameters param)\n {\n this.param = (RSAKeyGenerationParameters)param;\n this.iterations = getNumberOfIterations(this.param.getStrength(), this.param.getCertainty());\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-327", "cwe_name": "Use of a Broken or Risky Cryptographic Algorithm", "description": "The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.", "url": "https://cwe.mitre.org/data/definitions/327.html", "label_name": "vulnerable"} {"code": " public void engineInit(\n int opmode,\n Key key,\n SecureRandom random)\n throws InvalidKeyException\n {\n try\n {\n engineInit(opmode, key, (AlgorithmParameterSpec)null, random);\n }\n catch (InvalidAlgorithmParameterException e)\n {\n throw new IllegalArgumentException(\"can't handle supplied parameter spec\");\n }\n\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": " public IESCipher(OldIESEngine engine)\n {\n this.engine = engine;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": " public OldECIESwithCipher(BlockCipher baseCipher, int ivLength)\n {\n super(new OldIESEngine(new ECDHBasicAgreement(),\n new KDF2BytesGenerator(new SHA1Digest()),\n new HMac(new SHA1Digest()),\n new PaddedBufferedBlockCipher(baseCipher)), ivLength);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": " private byte[] getOutput()\n throws BadPaddingException\n {\n try\n {\n byte[] bytes = bOut.toByteArray();\n\n return cipher.processBlock(bytes, 0, bytes.length);\n }\n catch (final InvalidCipherTextException e)\n {\n throw new BadPaddingException(\"unable to decrypt block\")\n {\n public synchronized Throwable getCause()\n {\n return e;\n }\n };\n }\n finally\n {\n bOut.reset();\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-361", "cwe_name": "7PK - Time and State", "description": "This category represents one of the phyla in the Seven Pernicious Kingdoms vulnerability classification. It includes weaknesses related to the improper management of time and state in an environment that supports simultaneous or near-simultaneous computation by multiple systems, processes, or threads. According to the authors of the Seven Pernicious Kingdoms, \"Distributed computation is about time and state. That is, in order for more than one component to communicate, state must be shared, and all that takes time. Most programmers anthropomorphize their work. They think about one thread of control carrying out the entire program in the same way they would if they had to do the job themselves. Modern computers, however, switch between tasks very quickly, and in multi-core, multi-CPU, or distributed systems, two events may take place at exactly the same time. Defects rush to fill the gap between the programmer's model of how a program executes and what happens in reality. These defects are related to unexpected interactions between threads, processes, time, and information. These interactions happen through shared state: semaphores, variables, the file system, and, basically, anything that can store information.\"", "url": "https://cwe.mitre.org/data/definitions/361.html", "label_name": "vulnerable"} {"code": " protected BigInteger[] derDecode(\n byte[] encoding)\n throws IOException\n {\n ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);\n ASN1InputStream aIn = new ASN1InputStream(bIn);\n ASN1Sequence s = (ASN1Sequence)aIn.readObject();\n\n BigInteger[] sig = new BigInteger[2];\n\n sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue();\n sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue();\n\n return sig;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "vulnerable"} {"code": " public void performTest()\n throws Exception\n {\n testKeyConversion();\n testAdaptiveKeyConversion();\n decodeTest();\n testECDSA239bitPrime();\n testECDSA239bitBinary();\n testGeneration();\n testKeyPairGenerationWithOIDs();\n testNamedCurveParameterPreservation();\n testNamedCurveSigning();\n testBSI();\n testMQVwithHMACOnePass();\n testAlgorithmParameters();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "vulnerable"} {"code": " private BigInteger validate(BigInteger y, DHParameters dhParams)\n {\n if (y == null)\n {\n throw new NullPointerException(\"y value cannot be null\");\n }\n\n if (dhParams.getQ() != null)\n {\n if (ONE.equals(y.modPow(dhParams.getQ(), dhParams.getP())))\n {\n return y;\n }\n\n throw new IllegalArgumentException(\"Y value does not appear to be in correct group\");\n }\n else\n {\n // TLS check\n if (y.compareTo(TWO) < 0 || y.compareTo(dhParams.getP().subtract(TWO)) > 0)\n {\n throw new IllegalArgumentException(\"invalid DH public key\");\n }\n\n return y; // we can't validate without Q.\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": " public CFB()\n {\n super(new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 128)), 128);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": " public CCM()\n {\n super(new CCMBlockCipher(new AESFastEngine()), false, 16);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": " private void testExplicitWrapping(\n int size,\n int privateValueSize,\n BigInteger g,\n BigInteger p)\n throws Exception\n {\n DHParameterSpec dhParams = new DHParameterSpec(p, g, privateValueSize);\n\n KeyPairGenerator keyGen = KeyPairGenerator.getInstance(\"DH\", \"BC\");\n\n keyGen.initialize(dhParams);\n\n //\n // a side\n //\n KeyPair aKeyPair = keyGen.generateKeyPair();\n\n KeyAgreement aKeyAgree = KeyAgreement.getInstance(\"DH\", \"BC\");\n\n checkKeySize(privateValueSize, aKeyPair);\n\n aKeyAgree.init(aKeyPair.getPrivate());\n\n //\n // b side\n //\n KeyPair bKeyPair = keyGen.generateKeyPair();\n\n KeyAgreement bKeyAgree = KeyAgreement.getInstance(\"DH\", \"BC\");\n\n checkKeySize(privateValueSize, bKeyPair);\n\n bKeyAgree.init(bKeyPair.getPrivate());\n\n //\n // agreement\n //\n aKeyAgree.doPhase(bKeyPair.getPublic(), true);\n bKeyAgree.doPhase(aKeyPair.getPublic(), true);\n\n SecretKey k1 = aKeyAgree.generateSecret(PKCSObjectIdentifiers.id_alg_CMS3DESwrap.getId());\n SecretKey k2 = bKeyAgree.generateSecret(PKCSObjectIdentifiers.id_alg_CMS3DESwrap.getId());\n \n // TODO Compare k1 and k2?\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": " protected void initOther() throws ServletException {\n PropertyUtils.addBeanIntrospector(\n SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS);\n PropertyUtils.clearDescriptors();\n\n String value = null;\n value = getServletConfig().getInitParameter(\"config\");\n if (value != null) {\n config = value;\n }\n\n // Backwards compatibility for form beans of Java wrapper classes\n // Set to true for strict Struts 1.0 compatibility\n value = getServletConfig().getInitParameter(\"convertNull\");\n if (\"true\".equalsIgnoreCase(value)\n || \"yes\".equalsIgnoreCase(value)\n || \"on\".equalsIgnoreCase(value)\n || \"y\".equalsIgnoreCase(value)\n || \"1\".equalsIgnoreCase(value)) {\n\n convertNull = true;\n }\n\n if (convertNull) {\n ConvertUtils.deregister();\n ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);\n ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);\n ConvertUtils.register(new BooleanConverter(null), Boolean.class);\n ConvertUtils.register(new ByteConverter(null), Byte.class);\n ConvertUtils.register(new CharacterConverter(null), Character.class);\n ConvertUtils.register(new DoubleConverter(null), Double.class);\n ConvertUtils.register(new FloatConverter(null), Float.class);\n ConvertUtils.register(new IntegerConverter(null), Integer.class);\n ConvertUtils.register(new LongConverter(null), Long.class);\n ConvertUtils.register(new ShortConverter(null), Short.class);\n }\n\n }", "label": 0, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " public String getStringParameterSQL(String param) {\n return \"'\" + param + \"'\";\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " public void testPreserveSingleQuotesOnArgument()\n {\n Shell sh = newShell();\n\n sh.setWorkingDirectory( \"/usr/bin\" );\n sh.setExecutable( \"chmod\" );\n\n String[] args = { \"\\'some arg with spaces\\'\" };\n\n List shellCommandLine = sh.getShellCommandLine( args );\n\n String cli = StringUtils.join( shellCommandLine.iterator(), \" \" );\n System.out.println( cli );\n assertTrue( cli.endsWith( args[0] ) );\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "vulnerable"} {"code": "\tpublic static void ensurePointOnCurve(final ECPublicKey ephemeralPublicKey, final ECPrivateKey privateKey)\n\t\tthrows JOSEException {\n\t\t\n\t\t// Ensure the following is met:\n\t\t// (y^2) mod p = (x^3 + ax + b) mod p\n\t\tECParameterSpec ecParameterSpec = privateKey.getParams();\n\t\tEllipticCurve curve = ecParameterSpec.getCurve();\n\t\tECPoint point = ephemeralPublicKey.getW();\n\t\tBigInteger x = point.getAffineX();\n\t\tBigInteger y = point.getAffineY();\n\t\tBigInteger a = curve.getA();\n\t\tBigInteger b = curve.getB();\n\t\tBigInteger p = ((ECFieldFp) curve.getField()).getP();\n\t\tBigInteger leftSide = (y.pow(2)).mod(p);\n\t\tBigInteger rightSide = (x.pow(3).add(a.multiply(x)).add(b)).mod(p);\n\t\t\n\t\tif (! leftSide.equals(rightSide)) {\n\t\t\tthrow new JOSEException(\"Invalid ephemeral public key: Point not on expected curve\");\n\t\t}\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "vulnerable"} {"code": "\tpublic void testCurveCheckNegative_P256_attackPt1()\n\t\tthrows Exception {\n\t\t\n\t\t// The malicious JWE contains a public key with order 113\n\t\tString maliciousJWE = \"eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiZ1RsaTY1ZVRRN3otQmgxNDdmZjhLM203azJVaURpRzJMcFlrV0FhRkpDYyIsInkiOiJjTEFuakthNGJ6akQ3REpWUHdhOUVQclJ6TUc3ck9OZ3NpVUQta2YzMEZzIiwiY3J2IjoiUC0yNTYifX0.qGAdxtEnrV_3zbIxU2ZKrMWcejNltjA_dtefBFnRh9A2z9cNIqYRWg.pEA5kX304PMCOmFSKX_cEg.a9fwUrx2JXi1OnWEMOmZhXd94-bEGCH9xxRwqcGuG2AMo-AwHoljdsH5C_kcTqlXS5p51OB1tvgQcMwB5rpTxg.72CHiYFecyDvuUa43KKT6w\";\n\t\tJWEObject jweObject = JWEObject.parse(maliciousJWE);\n\t\t\n\t\tECPublicKey ephemeralPublicKey = jweObject.getHeader().getEphemeralPublicKey().toECPublicKey();\n\t\t\n\t\tECPrivateKey privateKey = generateECPrivateKey(ECKey.Curve.P_256);\n\t\t\n\t\ttry {\n\t\t\tECDH.ensurePointOnCurve(ephemeralPublicKey, privateKey);\n\t\t\tfail();\n\t\t} catch (JOSEException e) {\n\t\t\tassertEquals(\"Invalid ephemeral public key: Point not on expected curve\", e.getMessage());\n\t\t}\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "vulnerable"} {"code": "\tpublic void testSelectByTwoTypes() {\n\n\t\tJWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyTypes(KeyType.RSA, KeyType.EC).build());\n\n\t\tList keyList = new ArrayList<>();\n\t\tkeyList.add(new RSAKey.Builder(new Base64URL(\"n\"), new Base64URL(\"e\")).keyID(\"1\").build());\n\t\tkeyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL(\"x\"), new Base64URL(\"y\")).keyID(\"2\").build());\n\n\t\tJWKSet jwkSet = new JWKSet(keyList);\n\n\t\tList matches = selector.select(jwkSet);\n\n\t\tRSAKey key1 = (RSAKey)matches.get(0);\n\t\tassertEquals(KeyType.RSA, key1.getKeyType());\n\t\tassertEquals(\"1\", key1.getKeyID());\n\n\t\tECKey key2 = (ECKey)matches.get(1);\n\t\tassertEquals(KeyType.EC, key2.getKeyType());\n\t\tassertEquals(\"2\", key2.getKeyID());\n\n\t\tassertEquals(2, matches.size());\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "vulnerable"} {"code": "\tpublic static SecretKey decryptCEK(final SecretKey kek,\n\t\t\t\t\t final byte[] iv,\n\t\t\t\t\t final AuthenticatedCipherText authEncrCEK,\n\t\t\t\t\t final int keyLength,\n\t\t\t\t\t final Provider provider)\n\t\tthrows JOSEException {\n\n\t\tbyte[] keyBytes = AESGCM.decrypt(kek, iv, authEncrCEK.getCipherText(), new byte[0], authEncrCEK.getAuthenticationTag(), provider);\n\n\t\tif (ByteUtils.bitLength(keyBytes) != keyLength) {\n\n\t\t\tthrow new KeyLengthException(\"CEK key length mismatch: \" + ByteUtils.bitLength(keyBytes) + \" != \" + keyLength);\n\t\t}\n\n\t\treturn new SecretKeySpec(keyBytes, \"AES\");\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-345", "cwe_name": "Insufficient Verification of Data Authenticity", "description": "The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.", "url": "https://cwe.mitre.org/data/definitions/345.html", "label_name": "vulnerable"} {"code": "\tpublic SecretKey deriveKey(final SecretKey sharedSecret,\n\t\t\t\t final int keyLengthBits,\n\t\t\t\t final byte[] otherInfo)\n\t\tthrows JOSEException {\n\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n\t\tfinal MessageDigest md = getMessageDigest();\n\n\t\tfor (int i=1; i <= computeDigestCycles(ByteUtils.bitLength(md.getDigestLength()), keyLengthBits); i++) {\n\n\t\t\tbyte[] counterBytes = IntegerUtils.toBytes(i);\n\n\t\t\tmd.update(counterBytes);\n\t\t\tmd.update(sharedSecret.getEncoded());\n\n\t\t\tif (otherInfo != null) {\n\t\t\t\tmd.update(otherInfo);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tbaos.write(md.digest());\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new JOSEException(\"Couldn't write derived key: \" + e.getMessage(), e);\n\t\t\t}\n\t\t}\n\n\t\tbyte[] derivedKeyMaterial = baos.toByteArray();\n\n\t\tfinal int keyLengthBytes = ByteUtils.byteLength(keyLengthBits);\n\n\t\tif (derivedKeyMaterial.length == keyLengthBytes) {\n\t\t\t// Return immediately\n\t\t\treturn new SecretKeySpec(derivedKeyMaterial, \"AES\");\n\t\t}\n\n\t\treturn new SecretKeySpec(ByteUtils.subArray(derivedKeyMaterial, 0, keyLengthBytes), \"AES\");\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-345", "cwe_name": "Insufficient Verification of Data Authenticity", "description": "The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.", "url": "https://cwe.mitre.org/data/definitions/345.html", "label_name": "vulnerable"} {"code": " private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {\n \n String oldName = request.getParameter(\"groupName\");\n String newName = request.getParameter(\"newName\");\n \n if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {\n m_groupRepository.renameGroup(oldName, newName);\n }\n \n return listGroups(request, response);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " public static Document parseText(String text) throws DocumentException {\n SAXReader reader = new SAXReader();\n try {\n reader.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n reader.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n reader.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n } catch (SAXException e) {\n //Parse with external resources downloading allowed.\n }\n\n String encoding = getEncoding(text);\n\n InputSource source = new InputSource(new StringReader(text));\n source.setEncoding(encoding);\n\n Document result = reader.read(source);\n\n // if the XML parser doesn't provide a way to retrieve the encoding,\n // specify it manually\n if (result.getXMLEncoding() == null) {\n result.setXMLEncoding(encoding);\n }\n\n return result;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " protected XMLReader createXMLReader() throws SAXException {\n return SAXHelper.createXMLReader(isValidating());\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " public boolean isStripWhitespaceText() {\n return stripWhitespaceText;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " public void setEncoding(String encoding) {\n this.encoding = encoding;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " public void setErrorHandler(ErrorHandler errorHandler) {\n this.errorHandler = errorHandler;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " public boolean isStringInternEnabled() {\n return stringInternEnabled;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " public void setMergeAdjacentText(boolean mergeAdjacentText) {\n this.mergeAdjacentText = mergeAdjacentText;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " public void setXMLReaderClassName(String xmlReaderClassName)\n throws SAXException {\n setXMLReader(XMLReaderFactory.createXMLReader(xmlReaderClassName));\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " private String getLocalePrefix(FacesContext context) {\n\n String localePrefix = null;\n \n localePrefix = context.getExternalContext().getRequestParameterMap().get(\"loc\");\n \n if(localePrefix != null){\n return localePrefix;\n }\n \n String appBundleName = context.getApplication().getMessageBundle();\n if (null != appBundleName) {\n \t\n Locale locale = null;\n if (context.getViewRoot() != null) {\n locale = context.getViewRoot().getLocale();\n } else {\n locale = context.getApplication().getViewHandler().calculateLocale(context);\n }\n \n try {\n ResourceBundle appBundle =\n ResourceBundle.getBundle(appBundleName,\n locale,\n Util.getCurrentLoader(ResourceManager.class));\n localePrefix =\n appBundle\n .getString(ResourceHandler.LOCALE_PREFIX);\n } catch (MissingResourceException mre) { \n if (LOGGER.isLoggable(Level.FINEST)) {\n LOGGER.log(Level.FINEST, \"Ignoring missing resource\", mre);\n }\n }\n }\n return localePrefix;\n\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " private void renderState(FacesContext context) throws IOException {\n // Get the view state and write it to the response..\n PartialViewContext pvc = context.getPartialViewContext();\n PartialResponseWriter writer = pvc.getPartialResponseWriter();\n String viewStateId = Util.getViewStateId(context);\n\n writer.startUpdate(viewStateId);\n String state = context.getApplication().getStateManager().getViewState(context);\n writer.write(state);\n writer.endUpdate();\n\n ClientWindow window = context.getExternalContext().getClientWindow();\n if (null != window) {\n String clientWindowId = Util.getClientWindowId(context);\n writer.startUpdate(clientWindowId);\n writer.write(window.getId());\n writer.endUpdate();\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": "\tprivate boolean handleJid(Invite invite) {\n\t\tList contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);\n\t\tif (invite.isAction(XmppUri.ACTION_JOIN)) {\n\t\t\tConversation muc = xmppConnectionService.findFirstMuc(invite.getJid());\n\t\t\tif (muc != null) {\n\t\t\t\tswitchToConversation(muc, invite.getBody());\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tshowJoinConferenceDialog(invite.getJid().asBareJid().toString());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (contacts.size() == 0) {\n\t\t\tshowCreateContactDialog(invite.getJid().toString(), invite);\n\t\t\treturn false;\n\t\t} else if (contacts.size() == 1) {\n\t\t\tContact contact = contacts.get(0);\n\t\t\tif (!invite.isSafeSource() && invite.hasFingerprints()) {\n\t\t\t\tdisplayVerificationWarningDialog(contact, invite);\n\t\t\t} else {\n\t\t\t\tif (invite.hasFingerprints()) {\n\t\t\t\t\tif (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {\n\t\t\t\t\t\tToast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (invite.account != null) {\n\t\t\t\t\txmppConnectionService.getShortcutService().report(contact);\n\t\t\t\t}\n\t\t\t\tswitchToConversation(contact, invite.getBody());\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tif (mMenuSearchView != null) {\n\t\t\t\tmMenuSearchView.expandActionView();\n\t\t\t\tmSearchEditText.setText(\"\");\n\t\t\t\tmSearchEditText.append(invite.getJid().toString());\n\t\t\t\tfilter(invite.getJid().toString());\n\t\t\t} else {\n\t\t\t\tmInitialSearchValue.push(invite.getJid().toString());\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " public static void main(String[] args) {\n\n // Will serve all static file are under \"/public\" in classpath if the route isn't consumed by others routes.\n staticFileLocation(\"/public\");\n\n get(\"/hello\", (request, response) -> {\n return \"Hello World!\";\n });\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "\tpublic void checkAccess(ThreadGroup g) {\n\t\tif (RobocodeProperties.isSecurityOff()) {\n\t\t\treturn;\n\t\t}\n\t\tThread c = Thread.currentThread();\n\n\t\tif (isSafeThread(c)) {\n\t\t\treturn;\n\t\t}\n\t\tsuper.checkAccess(g);\n\n\t\tfinal ThreadGroup cg = c.getThreadGroup();\n\n\t\tif (cg == null) {\n\t\t\t// What the heck is going on here? JDK 1.3 is sending me a dead thread.\n\t\t\t// This crashes the entire jvm if I don't return here.\n\t\t\treturn;\n\t\t}\n\n\t\t// Bug fix #382 Unable to run robocode.bat -- Access Control Exception\n\t\tif (\"SeedGenerator Thread\".equals(c.getName()) && \"SeedGenerator ThreadGroup\".equals(cg.getName())) {\n\t\t\treturn; // The SeedGenerator might create a thread, which needs to be silently ignored\n\t\t}\n\t\t\n\t\tIHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);\n\n\t\tif (robotProxy == null) {\n\t\t\tthrow new AccessControlException(\"Preventing \" + c.getName() + \" from access to \" + g.getName());\t\t\t\n\t\t}\n\n\t\tif (cg.activeCount() > 5) {\n\t\t\tString message = \"Robots are only allowed to create up to 5 threads!\";\n\n\t\t\trobotProxy.punishSecurityViolation(message);\n\t\t\tthrow new AccessControlException(message);\n\t\t}\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": "\tprotected int getExpectedErrors() {\n\t\treturn hasJavaNetURLPermission ? 3 : 2; // Security error must be reported as an error\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public TSet readSetBegin() throws TException {\n return new TSet(readByte(), readI32());\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "vulnerable"} {"code": " public void setAllShouldOverwriteSomeAndLeaveOthersUntouched() {\n final HttpHeadersBase h1 = newEmptyHeaders();\n\n h1.add(\"name1\", \"value1\");\n h1.add(\"name2\", \"value2\");\n h1.add(\"name2\", \"value3\");\n h1.add(\"name3\", \"value4\");\n\n final HttpHeadersBase h2 = newEmptyHeaders();\n h2.add(\"name1\", \"value5\");\n h2.add(\"name2\", \"value6\");\n h2.add(\"name1\", \"value7\");\n\n final HttpHeadersBase expected = newEmptyHeaders();\n expected.add(\"name1\", \"value5\");\n expected.add(\"name2\", \"value6\");\n expected.add(\"name1\", \"value7\");\n expected.add(\"name3\", \"value4\");\n\n h1.set(h2);\n\n assertThat(h1).isEqualTo(expected);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": " public void multipleValuesPerNameIteratorWithOtherNames() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\");\n headers.add(\"name1\", \"value2\");\n headers.add(\"name2\", \"value4\");\n headers.add(\"name1\", \"value3\");\n assertThat(headers.size()).isEqualTo(4);\n\n final List values = ImmutableList.copyOf(headers.valueIterator(\"name1\"));\n assertThat(values).containsExactly(\"value1\", \"value2\", \"value3\");\n\n final Iterator itr = headers.valueIterator(\"name2\");\n assertThat(itr).hasNext();\n assertThat(itr.next()).isEqualTo(\"value4\");\n assertThat(itr).isExhausted();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": " public void testHeaderNameNormalization() {\n final HttpHeadersBase headers = newHttp2Headers();\n headers.add(\"Foo\", \"bar\");\n assertThat(headers.getAll(\"foo\")).containsExactly(\"bar\");\n assertThat(headers.getAll(\"fOO\")).containsExactly(\"bar\");\n assertThat(headers.names()).contains(HttpHeaderNames.of(\"foo\"))\n .doesNotContain(AsciiString.of(\"Foo\"));\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": " public void testSetSelfIsNoOp() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name\", \"value\");\n headers.set(headers);\n assertThat(headers.size()).isEqualTo(1);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": " public void testEqualsInsertionOrderSameHeaderName() {\n final HttpHeadersBase h1 = newEmptyHeaders();\n h1.add(\"a\", \"b\");\n h1.add(\"a\", \"c\");\n final HttpHeadersBase h2 = newEmptyHeaders();\n h2.add(\"a\", \"c\");\n h2.add(\"a\", \"b\");\n assertThat(h1).isNotEqualTo(h2);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": " public void testCopy() throws Exception {\n HttpHeadersBase headers = newEmptyHeaders();\n headers.addLong(\"long\", Long.MAX_VALUE);\n headers.addInt(\"int\", Integer.MIN_VALUE);\n headers.addDouble(\"double\", Double.MAX_VALUE);\n headers.addFloat(\"float\", Float.MAX_VALUE);\n final long millis = System.currentTimeMillis();\n headers.addTimeMillis(\"millis\", millis);\n headers.addObject(\"object\", \"Hello World\");\n headers.add(\"name\", \"value\");\n\n final HttpHeadersBase oldHeaders = headers;\n headers = newEmptyHeaders();\n headers.add(oldHeaders);\n\n assertThat(headers.containsLong(\"long\", Long.MAX_VALUE)).isTrue();\n assertThat(headers.containsLong(\"long\", Long.MIN_VALUE)).isFalse();\n\n assertThat(headers.containsInt(\"int\", Integer.MIN_VALUE)).isTrue();\n assertThat(headers.containsInt(\"int\", Integer.MAX_VALUE)).isFalse();\n\n assertThat(headers.containsDouble(\"double\", Double.MAX_VALUE)).isTrue();\n assertThat(headers.containsDouble(\"double\", Double.MIN_VALUE)).isFalse();\n\n assertThat(headers.containsFloat(\"float\", Float.MAX_VALUE)).isTrue();\n assertThat(headers.containsFloat(\"float\", Float.MIN_VALUE)).isFalse();\n\n assertThat(headers.containsTimeMillis(\"millis\", millis)).isTrue();\n // This test doesn't work on midnight, January 1, 1970 UTC\n assertThat(headers.containsTimeMillis(\"millis\", 0)).isFalse();\n\n assertThat(headers.containsObject(\"object\", \"Hello World\")).isTrue();\n assertThat(headers.containsObject(\"object\", \"\")).isFalse();\n\n assertThat(headers.contains(\"name\", \"value\")).isTrue();\n assertThat(headers.contains(\"name\", \"value1\")).isFalse();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": " public void whenNameContainsMultipleValuesGetShouldReturnTheFirst() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\", \"value2\");\n assertThat(headers.get(\"name1\")).isEqualTo(\"value1\");\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": " void encodedUnicode() {\n final String encodedPath = \"/%ec%95%88\";\n final String encodedQuery = \"%eb%85%95\";\n final PathAndQuery res = PathAndQuery.parse(encodedPath + '?' + encodedQuery);\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(Ascii.toUpperCase(encodedPath));\n assertThat(res.query()).isEqualTo(Ascii.toUpperCase(encodedQuery));\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " public void install(\n String displayName, String description, String[] dependencies,\n String account, String password, String config) throws URISyntaxException {\n\n String javaHome = System.getProperty(\"java.home\");\n String javaBinary = javaHome + \"\\\\bin\\\\java.exe\";\n\n File jar = new File(WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI());\n String command = javaBinary\n + \" -Duser.dir=\\\"\" + jar.getParentFile().getAbsolutePath() + \"\\\"\"\n + \" -jar \\\"\" + jar.getAbsolutePath() + \"\\\"\"\n + \" --service \\\"\" + config + \"\\\"\";\n\n StringBuilder dep = new StringBuilder();\n\n if (dependencies != null) {\n for (String s : dependencies) {\n dep.append(s);\n dep.append(\"\\0\");\n }\n }\n dep.append(\"\\0\");\n\n SERVICE_DESCRIPTION desc = new SERVICE_DESCRIPTION();\n desc.lpDescription = description;\n\n SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS);\n\n if (serviceManager != null) {\n SC_HANDLE service = ADVAPI_32.CreateService(serviceManager, serviceName, displayName,\n Winsvc.SERVICE_ALL_ACCESS, WinNT.SERVICE_WIN32_OWN_PROCESS, WinNT.SERVICE_AUTO_START,\n WinNT.SERVICE_ERROR_NORMAL,\n command,\n null, null, dep.toString(), account, password);\n\n if (service != null) {\n ADVAPI_32.ChangeServiceConfig2(service, Winsvc.SERVICE_CONFIG_DESCRIPTION, desc);\n ADVAPI_32.CloseServiceHandle(service);\n }\n ADVAPI_32.CloseServiceHandle(serviceManager);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-428", "cwe_name": "Unquoted Search Path or Element", "description": "The product uses a search path that contains an unquoted element, in which the element contains whitespace or other separators. This can cause the product to access resources in a parent path.", "url": "https://cwe.mitre.org/data/definitions/428.html", "label_name": "vulnerable"} {"code": " public void validateFail2(ViolationCollector col) {\n col.addViolation(FAILED + \"2\");\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-74", "cwe_name": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')", "description": "The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/74.html", "label_name": "vulnerable"} {"code": "\tpublic XssHttpServletRequestWrapper(HttpServletRequest request) {\n\t\tsuper(request);\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " public static SSLSocketFactory getSslSocketFactory(Properties info) throws PSQLException {\n String classname = PGProperty.SSL_FACTORY.get(info);\n if (classname == null\n || \"org.postgresql.ssl.jdbc4.LibPQFactory\".equals(classname)\n || \"org.postgresql.ssl.LibPQFactory\".equals(classname)) {\n return new LibPQFactory(info);\n }\n try {\n return (SSLSocketFactory) ObjectFactory.instantiate(classname, info, true,\n PGProperty.SSL_FACTORY_ARG.get(info));\n } catch (Exception e) {\n throw new PSQLException(\n GT.tr(\"The SSLSocketFactory class provided {0} could not be instantiated.\", classname),\n PSQLState.CONNECTION_FAILURE, e);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-665", "cwe_name": "Improper Initialization", "description": "The software does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used.", "url": "https://cwe.mitre.org/data/definitions/665.html", "label_name": "vulnerable"} {"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tencryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (keySpec == null) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\ttry {\n\t\t\tsetup(ad);\n\t\t\tint result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);\n\t\t\tcipher.doFinal(ciphertext, ciphertextOffset + result);\n\t\t} catch (InvalidKeyException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (InvalidAlgorithmParameterException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (IllegalBlockSizeException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (BadPaddingException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (keySpec == null) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\ttry {\n\t\t\tsetup(ad);\n\t\t\tint result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);\n\t\t\tcipher.doFinal(ciphertext, ciphertextOffset + result);\n\t\t} catch (InvalidKeyException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (InvalidAlgorithmParameterException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (IllegalBlockSizeException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (BadPaddingException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (keySpec == null) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\ttry {\n\t\t\tsetup(ad);\n\t\t\tint result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);\n\t\t\tcipher.doFinal(ciphertext, ciphertextOffset + result);\n\t\t} catch (InvalidKeyException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (InvalidAlgorithmParameterException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (IllegalBlockSizeException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (BadPaddingException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": " public void addUser(JpaUser user) throws UnauthorizedException {\n if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))\n throw new UnauthorizedException(\"The user is not allowed to set the admin role on other users\");\n\n // Create a JPA user with an encoded password.\n String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());\n\n // Only save internal roles\n Set roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf);\n JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(\n (JpaOrganization) user.getOrganization(), emf);\n\n JpaUser newUser = new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(),\n user.getProvider(), user.isManageable(), roles);\n\n // Then save the user\n EntityManager em = null;\n EntityTransaction tx = null;\n try {\n em = emf.createEntityManager();\n tx = em.getTransaction();\n tx.begin();\n em.persist(newUser);\n tx.commit();\n cache.put(user.getUsername() + DELIMITER + user.getOrganization().getId(), newUser);\n } finally {\n if (tx.isActive()) {\n tx.rollback();\n }\n if (em != null)\n em.close();\n }\n\n updateGroupMembership(user);\n\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-327", "cwe_name": "Use of a Broken or Risky Cryptographic Algorithm", "description": "The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.", "url": "https://cwe.mitre.org/data/definitions/327.html", "label_name": "vulnerable"} {"code": " private static IRubyObject getSchema(ThreadContext context, RubyClass klazz, Source source) {\n String moduleName = klazz.getName();\n if (\"Nokogiri::XML::Schema\".equals(moduleName)) {\n return XmlSchema.createSchemaInstance(context, klazz, source);\n } else if (\"Nokogiri::XML::RelaxNG\".equals(moduleName)) {\n return XmlRelaxng.createSchemaInstance(context, klazz, source);\n }\n return context.getRuntime().getNil();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " public Optional getResource(String path) {\n Path filePath = getFilePath(normalize(path));\n if (Files.exists(filePath) && Files.isReadable(filePath) && !Files.isDirectory(filePath)) {\n try {\n URL url = filePath.toUri().toURL();\n return Optional.of(url);\n } catch (MalformedURLException e) {\n }\n }\n return Optional.empty();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " public Stream getResources(String path) {\n Enumeration all;\n try {\n all = classLoader.getResources(prefixPath(path));\n } catch (IOException e) {\n return Stream.empty();\n }\n Stream.Builder builder = Stream.builder();\n while (all.hasMoreElements()) {\n URL url = all.nextElement();\n builder.accept(url);\n }\n return builder.build();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " private Map> initializeTypeParameters(Argument[] genericTypes) {\n Map> typeParameters;\n if (genericTypes != null && genericTypes.length > 0) {\n typeParameters = new LinkedHashMap<>(genericTypes.length);\n for (Argument genericType : genericTypes) {\n typeParameters.put(genericType.getName(), genericType);\n }\n } else {\n typeParameters = Collections.emptyMap();\n }\n return typeParameters;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " public DefaultArgument(Class type, String name, AnnotationMetadata annotationMetadata, Argument... genericTypes) {\n this.type = type;\n this.name = name;\n this.annotationMetadata = annotationMetadata != null ? annotationMetadata : AnnotationMetadata.EMPTY_METADATA;\n this.typeParameters = initializeTypeParameters(genericTypes);\n this.typeParameterArray = genericTypes;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " private void securityCheck(String filename) {\n Assert.doesNotContain(filename, \"..\");\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "\tpublic void configure(ServletContextHandler context) {\n\t\tcontext.setContextPath(\"/\");\n\t\t\n\t\tcontext.getSessionHandler().setMaxInactiveInterval(serverConfig.getSessionTimeout());\n\t\t\n\t\tcontext.setInitParameter(EnvironmentLoader.ENVIRONMENT_CLASS_PARAM, DefaultWebEnvironment.class.getName());\n\t\tcontext.addEventListener(new EnvironmentLoaderListener());\n\t\tcontext.addFilter(new FilterHolder(shiroFilter), \"/*\", EnumSet.allOf(DispatcherType.class));\n\t\t\n context.addFilter(new FilterHolder(gitFilter), \"/*\", EnumSet.allOf(DispatcherType.class));\n\t\t\n\t\tcontext.addServlet(new ServletHolder(preReceiveServlet), GitPreReceiveCallback.PATH + \"/*\");\n \n context.addServlet(new ServletHolder(postReceiveServlet), GitPostReceiveCallback.PATH + \"/*\");\n \n\t\t/*\n\t\t * Add wicket servlet as the default servlet which will serve all requests failed to \n\t\t * match a path pattern\n\t\t */\n\t\tcontext.addServlet(new ServletHolder(wicketServlet), \"/\");\n\t\t\n\t\tcontext.addServlet(new ServletHolder(attachmentUploadServlet), \"/attachment_upload\");\n\t\t\n\t\tcontext.addServlet(new ServletHolder(new ClasspathAssetServlet(ImageScope.class)), \"/img/*\");\n\t\tcontext.addServlet(new ServletHolder(new ClasspathAssetServlet(IconScope.class)), \"/icon/*\");\n\t\t\n\t\tcontext.getSessionHandler().addEventListener(new HttpSessionListener() {\n\n\t\t\t@Override\n\t\t\tpublic void sessionCreated(HttpSessionEvent se) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void sessionDestroyed(HttpSessionEvent se) {\n\t\t\t\twebSocketManager.onDestroySession(se.getSession().getId());\n\t\t\t}\n\t\t\t\n\t\t});\n\t\t\n\t\t/*\n\t\t * Configure a servlet to serve contents under site folder. Site folder can be used \n\t\t * to hold site specific web assets. \n\t\t */\n\t\tServletHolder fileServletHolder = new ServletHolder(new FileAssetServlet(Bootstrap.getSiteDir()));\n\t\tcontext.addServlet(fileServletHolder, \"/site/*\");\n\t\tcontext.addServlet(fileServletHolder, \"/robots.txt\");\n\t\t\n\t\tcontext.addServlet(new ServletHolder(jerseyServlet), \"/rest/*\");\t\t\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "vulnerable"} {"code": "\tpublic boolean loginValidate(String userName, String password) {\n\n\t\tString sql = \"select * from admin_table where admin_name=? and password=?\";\n\t\ttry {\n\t\t\tps=DbUtil.getConnection().prepareStatement(sql);\n\t\t\tps.setString(1, userName);\n\t\t\tps.setString(2,password);\n\t\t\tResultSet rs =ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} catch (SQLException | ClassNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn false;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-759", "cwe_name": "Use of a One-Way Hash without a Salt", "description": "The software uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the software does not also use a salt as part of the input.", "url": "https://cwe.mitre.org/data/definitions/759.html", "label_name": "vulnerable"} {"code": " public static boolean isPermitted(\n final Optional authenticationService,\n final Optional optionalUser,\n final JsonRpcMethod jsonRpcMethod) {\n\n AtomicBoolean foundMatchingPermission = new AtomicBoolean();\n\n if (authenticationService.isPresent()) {\n if (optionalUser.isPresent()) {\n User user = optionalUser.get();\n for (String perm : jsonRpcMethod.getPermissions()) {\n user.isAuthorized(\n perm,\n (authed) -> {\n if (authed.result()) {\n LOG.trace(\n \"user {} authorized : {} via permission {}\",\n user,\n jsonRpcMethod.getName(),\n perm);\n foundMatchingPermission.set(true);\n }\n });\n }\n }\n } else {\n // no auth provider configured thus anything is permitted\n foundMatchingPermission.set(true);\n }\n\n if (!foundMatchingPermission.get()) {\n LOG.trace(\"user NOT authorized : {}\", jsonRpcMethod.getName());\n }\n return foundMatchingPermission.get();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " public void setupRoutes() {\n path(controllerBasePath(), () -> {\n before(\"\", mimeType, this::setContentType);\n\n\n // change the line below to enable appropriate security\n before(\"\", mimeType, this.apiAuthenticationHelper::checkAdminUserAnd403);\n\n get(\"\", mimeType, this::show);\n\n post(\"\", mimeType, this::createOrUpdate);\n put(\"\", mimeType, this::createOrUpdate);\n\n delete(\"\", mimeType, this::deleteBackupConfig);\n });\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " private Document marshallToDocument(JAXBElement object, Class type) throws SAMLException {\n try {\n JAXBContext context = JAXBContext.newInstance(type);\n Marshaller marshaller = context.createMarshaller();\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setNamespaceAware(true);\n DocumentBuilder db = dbf.newDocumentBuilder();\n Document document = db.newDocument();\n marshaller.marshal(object, document);\n return document;\n } catch (JAXBException | ParserConfigurationException e) {\n throw new SAMLException(\"Unable to marshallRequest JAXB SAML object to DOM.\", e);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " private byte[] marshallToBytes(JAXBElement object, Class type) throws SAMLException {\n try {\n JAXBContext context = JAXBContext.newInstance(type);\n Marshaller marshaller = context.createMarshaller();\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n marshaller.marshal(object, baos);\n return baos.toByteArray();\n } catch (JAXBException e) {\n throw new SAMLException(\"Unable to marshallRequest JAXB SAML object to bytes.\", e);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": " public void newDocumentFromURL() throws Exception\n {\n // new document = xwiki:X.Y\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\"), \"Y\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public void newDocumentWebHomeFromURL() throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note1: The bebavior is the same for both a top level space and a child space WebHome.\n // Note2: The title is not \"WebHome\", but \"Y\" (the space's name) to avoid exposing \"WebHome\" in the UI.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null,\n \"xwiki\", context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public void existingDocumentFromUITemplateProviderSpecified() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.Y and using the template extracted from the template provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public void existingDocumentNonTerminalFromUIDeprecatedIgnoringPage() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI space=X&page=Y&tocreate=space\n when(mockRequest.getParameter(\"space\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"page\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"space\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.WebHome instead of X.Y because the tocreate parameter says \"space\" and the page\n // parameter is ignored.\n verify(mockURLFactory).createURL(\"X\", \"WebHome\", \"edit\", \"template=&parent=Main.WebHome&title=X\", null, \"xwiki\",\n context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public void existingDocumentFromUITemplateProviderSpecifiedButOldSpaceTypeButOverridenFromUIToTerminal()\n throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"terminal\");\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, null,\n \"space\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.Y as terminal, since it is overriden from the UI, regardless of any backwards\n // compatibility resolutions. Also using the template extracted from the template provider.\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\",\n null, \"xwiki\", context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public void newDocumentFromURLTemplateProviderSpecifiedNonTerminalButOverriddenFromUITerminal() throws Exception\n {\n // new document = xwiki:X.Y\n DocumentReference documentReference = new DocumentReference(\"xwiki\", \"X\", \"Y\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"terminal\");\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST,\n false);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y as terminal and using a template, as specified in the template\n // provider.\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\",\n null, \"xwiki\", context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public void existingDocumentNonTerminalFromUIDeprecated() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI space=X&tocreate=space\n when(mockRequest.getParameter(\"space\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"space\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.WebHome because the tocreate parameter says \"space\".\n verify(mockURLFactory).createURL(\"X\", \"WebHome\", \"edit\", \"template=&parent=Main.WebHome&title=X\", null, \"xwiki\",\n context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public void existingDocumentFromUITemplateProviderSpecifiedTerminal() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n String spaceReferenceString = \"X\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(spaceReferenceString);\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider that creates terminal documents.\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, true);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y as terminal and using a template, as specified in the template\n // provider.\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\",\n null, \"xwiki\", context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExists() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n String spaceReferenceString = \"X\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(spaceReferenceString);\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider that allows usage in target space.\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Arrays.asList(\"X\"));\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note1: We are allowed to create anything under space X, be it a terminal or a non-terminal document.\n // Note2: We are creating X.Y and using the template extracted from the template provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " void newDocumentInvalidName() throws Exception\n {\n when(mockDocument.isNew()).thenReturn(true);\n DocumentReference documentReference = new DocumentReference(\"XWiki\", \"Foo\", \"Bar\");\n when(mockDocument.getDocumentReference()).thenReturn(documentReference);\n when(this.entityNameValidationConfiguration.useValidation()).thenReturn(true);\n EntityNameValidation entityNameValidation = mock(EntityNameValidation.class);\n when(this.entityNameValidationManager.getEntityReferenceNameStrategy()).thenReturn(entityNameValidation);\n when(entityNameValidation.isValid(documentReference)).thenReturn(false);\n\n assertTrue(saveAction.save(this.context));\n assertEquals(\"entitynamevalidation.create.invalidname\", context.get(\"message\"));\n assertArrayEquals(new Object[] { \"Foo.Bar\" }, (Object[]) context.get(\"messageParameters\"));\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,\n String parent) throws XWikiException\n {\n XWiki xwiki = context.getWiki();\n\n // Set the locale and default locale, considering that we're creating the original version of the document\n // (not a translation).\n newDocument.setLocale(Locale.ROOT);\n if (newDocument.getDefaultLocale() == Locale.ROOT) {\n newDocument.setDefaultLocale(xwiki.getLocalePreference(context));\n }\n\n // Copy the template.\n readFromTemplate(newDocument, template, context);\n\n // Set the parent field.\n if (!StringUtils.isEmpty(parent)) {\n DocumentReference parentReference = this.currentmixedReferenceResolver.resolve(parent);\n newDocument.setParentReference(parentReference);\n }\n\n // Set the document title\n if (title != null) {\n newDocument.setTitle(title);\n }\n\n // Set the author and creator.\n DocumentReference currentUserReference = context.getUserReference();\n newDocument.setAuthorReference(currentUserReference);\n newDocument.setCreatorReference(currentUserReference);\n\n // Make sure the user is allowed to make this modification\n xwiki.checkSavingDocument(currentUserReference, newDocument, context);\n\n xwiki.saveDocument(newDocument, context);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "vulnerable"} {"code": " private void checkUserReference(UserReference userReference) throws ResetPasswordException\n {\n if (!this.userManager.exists(userReference)) {\n String exceptionMessage =\n this.localizationManager.getTranslationPlain(\"xe.admin.passwordReset.error.noUser\",\n userReference.toString());\n throw new ResetPasswordException(exceptionMessage);\n }\n\n // FIXME: This check shouldn't be needed if we'd have the proper API to determine which kind of\n // authentication is used.\n if (!(userReference instanceof DocumentUserReference)) {\n throw new ResetPasswordException(\"Only user having a page on the wiki can reset their password.\");\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-640", "cwe_name": "Weak Password Recovery Mechanism for Forgotten Password", "description": "The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.", "url": "https://cwe.mitre.org/data/definitions/640.html", "label_name": "vulnerable"} {"code": " DefaultResetPasswordRequestResponse(UserReference reference, InternetAddress userEmail, String verificationCode)\n {\n this.userReference = reference;\n this.userEmail = userEmail;\n this.verificationCode = verificationCode;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-640", "cwe_name": "Weak Password Recovery Mechanism for Forgotten Password", "description": "The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.", "url": "https://cwe.mitre.org/data/definitions/640.html", "label_name": "vulnerable"} {"code": " void resetPasswordUnexistingUser() throws Exception\n {\n when(this.userReference.toString()).thenReturn(\"user:Foobar\");\n when(this.userManager.exists(this.userReference)).thenReturn(false);\n String exceptionMessage = \"User [user:Foobar] doesn't exist\";\n when(this.localizationManager.getTranslationPlain(\"xe.admin.passwordReset.error.noUser\",\n \"user:Foobar\")).thenReturn(exceptionMessage);\n ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class,\n () -> this.resetPasswordManager.resetPassword(this.userReference, \"some password\"));\n assertEquals(exceptionMessage, resetPasswordException.getMessage());\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-640", "cwe_name": "Weak Password Recovery Mechanism for Forgotten Password", "description": "The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.", "url": "https://cwe.mitre.org/data/definitions/640.html", "label_name": "vulnerable"} {"code": " public Claims validateToken(String token) throws AuthenticationException {\n try {\n RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();\n PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey);\n\n return Jwts.parser().setSigningKey(publicKey).parseJws(token.replace(\"Bearer \", \"\")).getBody();\n } catch (Exception e){\n throw new AuthenticationException(String.format(\"Failed to check user authorization for token: %s\", token), e);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-290", "cwe_name": "Authentication Bypass by Spoofing", "description": "This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks.", "url": "https://cwe.mitre.org/data/definitions/290.html", "label_name": "vulnerable"} {"code": " protected int addFileNames(List list) { // This appears to only be used by unit tests and the copy\n // constructor\n for (String file : list) {\n workUnitList.add(new WorkUnit(file));\n }\n return size();\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "vulnerable"} {"code": " public static void setRequestMethod(HttpURLConnection conn, RequestMethod method) {\n try {\n conn.setRequestMethod(getRequestMethodAsString(method));\n } catch (ProtocolException e) {\n throw ErrorUtil.createCommandException(e.getMessage());\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-306", "cwe_name": "Missing Authentication for Critical Function", "description": "The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.", "url": "https://cwe.mitre.org/data/definitions/306.html", "label_name": "vulnerable"} {"code": " public static HttpURLConnection createHttpUrlConnection(URL url, String proxyHost, int proxyPort,\n String proxyUsername, String proxyPassword) {\n try {\n Proxy proxy = getProxy(proxyHost, proxyPort, proxyUsername, proxyPassword);\n // set proxy if exists.\n if (proxy == null) {\n return (HttpURLConnection) url.openConnection();\n } else {\n return (HttpURLConnection) url.openConnection(proxy);\n }\n } catch (IOException e) {\n throw ErrorUtil.createCommandException(e.getMessage());\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-306", "cwe_name": "Missing Authentication for Critical Function", "description": "The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.", "url": "https://cwe.mitre.org/data/definitions/306.html", "label_name": "vulnerable"} {"code": " public void testPullCount() throws IOException {\n initializeSsl();\n String url = RepoUtils.getRemoteRepoURL() + \"/modules/info/\" + orgName + \"/\" + moduleName + \"/*/\";\n HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), \"\", 0, \"\", \"\");\n conn.setInstanceFollowRedirects(false);\n setRequestMethod(conn, Utils.RequestMethod.GET);\n\n int statusCode = conn.getResponseCode();\n if (statusCode == 200) {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),\n Charset.defaultCharset()))) {\n StringBuilder result = new StringBuilder();\n String line;\n while ((line = reader.readLine()) != null) {\n result.append(line);\n }\n Object payload = JSONParser.parse(result.toString());\n if (payload instanceof MapValue) {\n long pullCount = ((MapValue) payload).getIntValue(\"totalPullCount\");\n Assert.assertEquals(pullCount, totalPullCount);\n } else {\n Assert.fail(\"error: invalid response received\");\n }\n }\n } else {\n Assert.fail(\"error: could not connect to remote repository to find the latest version of module\");\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-306", "cwe_name": "Missing Authentication for Critical Function", "description": "The software does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.", "url": "https://cwe.mitre.org/data/definitions/306.html", "label_name": "vulnerable"} {"code": " public void translate(ServerSettingsRequestPacket packet, GeyserSession session) {\n CustomForm window = SettingsUtils.buildForm(session);\n int windowId = session.getFormCache().addForm(window);\n\n // Fixes https://bugs.mojang.com/browse/MCPE-94012 because of the delay\n session.getConnector().getGeneralThreadPool().schedule(() -> {\n ServerSettingsResponsePacket serverSettingsResponsePacket = new ServerSettingsResponsePacket();\n serverSettingsResponsePacket.setFormData(window.getJsonData());\n serverSettingsResponsePacket.setFormId(windowId);\n session.sendUpstreamPacket(serverSettingsResponsePacket);\n }, 1, TimeUnit.SECONDS);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(EmotePacket packet, GeyserSession session) {\n if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) {\n // Activate the workaround - we should trigger the offhand now\n ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO,\n BlockFace.DOWN);\n session.sendDownstreamPacket(swapHandsPacket);\n\n if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {\n return;\n }\n }\n\n long javaId = session.getPlayerEntity().getEntityId();\n for (GeyserSession otherSession : session.getConnector().getPlayers()) {\n if (otherSession != session) {\n if (otherSession.isClosed()) continue;\n if (otherSession.getEventLoop().inEventLoop()) {\n playEmote(otherSession, javaId, packet.getEmoteId());\n } else {\n session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId()));\n }\n }\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(LoginSuccessPacket packet, GeyserSession session) {\n PlayerEntity playerEntity = session.getPlayerEntity();\n AuthType remoteAuthType = session.getRemoteAuthType();\n\n // Required, or else Floodgate players break with Spigot chunk caching\n GameProfile profile = packet.getProfile();\n playerEntity.setUsername(profile.getName());\n playerEntity.setUuid(profile.getId());\n\n // Check if they are not using a linked account\n if (remoteAuthType == AuthType.OFFLINE || playerEntity.getUuid().getMostSignificantBits() == 0) {\n SkinManager.handleBedrockSkin(playerEntity, session.getClientData());\n }\n\n if (remoteAuthType == AuthType.FLOODGATE) {\n // We'll send the skin upload a bit after the handshake packet (aka this packet),\n // because otherwise the global server returns the data too fast.\n session.getAuthData().upload(session.getConnector());\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(ServerEntityAttachPacket packet, GeyserSession session) {\n\n Entity holderId;\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n holderId = session.getPlayerEntity();\n } else {\n holderId = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (holderId == null) {\n return;\n }\n }\n\n Entity attachedToId;\n if (packet.getAttachedToId() == session.getPlayerEntity().getEntityId()) {\n attachedToId = session.getPlayerEntity();\n } else {\n attachedToId = session.getEntityCache().getEntityByJavaId(packet.getAttachedToId());\n if ((attachedToId == null || packet.getAttachedToId() == 0)) {\n // Is not being leashed\n holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, false);\n holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, -1L);\n holderId.updateBedrockMetadata(session);\n EntityEventPacket eventPacket = new EntityEventPacket();\n eventPacket.setRuntimeEntityId(holderId.getGeyserId());\n eventPacket.setType(EntityEventType.REMOVE_LEASH);\n eventPacket.setData(0);\n session.sendUpstreamPacket(eventPacket);\n return;\n }\n }\n\n holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, true);\n holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, attachedToId.getGeyserId());\n holderId.updateBedrockMetadata(session);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(ServerEntityVelocityPacket packet, GeyserSession session) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();\n }\n if (entity == null) return;\n\n entity.setMotion(Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ()));\n\n if (entity == session.getRidingVehicleEntity() && entity instanceof AbstractHorseEntity) {\n // Horses for some reason teleport back when a SetEntityMotionPacket is sent while\n // a player is riding on them. Java clients seem to ignore it anyways.\n return;\n }\n\n if (entity instanceof ItemEntity) {\n // Don't bother sending entity motion packets for items\n // since the client doesn't seem to care\n return;\n }\n\n SetEntityMotionPacket entityMotionPacket = new SetEntityMotionPacket();\n entityMotionPacket.setRuntimeEntityId(entity.getGeyserId());\n entityMotionPacket.setMotion(entity.getMotion());\n\n session.sendUpstreamPacket(entityMotionPacket);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(ServerSpawnExpOrbPacket packet, GeyserSession session) {\n Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n\n Entity entity = new ExpOrbEntity(\n packet.getExp(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),\n EntityType.EXPERIENCE_ORB, position, Vector3f.ZERO, Vector3f.ZERO\n );\n\n session.getEntityCache().spawnEntity(entity);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(ServerUpdateScorePacket packet, GeyserSession session) {\n WorldCache worldCache = session.getWorldCache();\n Scoreboard scoreboard = worldCache.getScoreboard();\n int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();\n\n Objective objective = scoreboard.getObjective(packet.getObjective());\n if (objective == null && packet.getAction() != ScoreboardAction.REMOVE) {\n logger.info(LanguageUtils.getLocaleStringLog(\"geyser.network.translator.score.failed_objective\", packet.getObjective()));\n return;\n }\n\n switch (packet.getAction()) {\n case ADD_OR_UPDATE:\n objective.setScore(packet.getEntry(), packet.getValue());\n break;\n case REMOVE:\n if (objective != null) {\n objective.removeScore(packet.getEntry());\n } else {\n for (Objective objective1 : scoreboard.getObjectives().values()) {\n objective1.removeScore(packet.getEntry());\n }\n }\n break;\n }\n\n // ScoreboardUpdater will handle it for us if the packets per second\n // (for score and team packets) is higher then the first threshold\n if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {\n scoreboard.onUpdate();\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(ServerSetTitleTextPacket packet, GeyserSession session) {\n String text;\n if (packet.getText() == null) { //TODO 1.17 can this happen?\n text = \" \";\n } else {\n text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());\n }\n\n SetTitlePacket titlePacket = new SetTitlePacket();\n titlePacket.setType(SetTitlePacket.Type.TITLE);\n titlePacket.setText(text);\n titlePacket.setXuid(\"\");\n titlePacket.setPlatformOnlineId(\"\");\n session.sendUpstreamPacket(titlePacket);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(ServerSpawnParticlePacket packet, GeyserSession session) {\n Function particleCreateFunction = createParticle(session, packet.getParticle());\n if (particleCreateFunction != null) {\n if (packet.getAmount() == 0) {\n // 0 means don't apply the offset\n Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n session.sendUpstreamPacket(particleCreateFunction.apply(position));\n } else {\n Random random = ThreadLocalRandom.current();\n for (int i = 0; i < packet.getAmount(); i++) {\n double offsetX = random.nextGaussian() * (double) packet.getOffsetX();\n double offsetY = random.nextGaussian() * (double) packet.getOffsetY();\n double offsetZ = random.nextGaussian() * (double) packet.getOffsetZ();\n Vector3f position = Vector3f.from(packet.getX() + offsetX, packet.getY() + offsetY, packet.getZ() + offsetZ);\n\n session.sendUpstreamPacket(particleCreateFunction.apply(position));\n }\n }\n } else {\n // Null is only returned when no particle of this type is found\n session.getConnector().getLogger().debug(\"Unhandled particle packet: \" + packet);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " public void translate(ServerUpdateViewPositionPacket packet, GeyserSession session) {\n if (!session.isSpawned() && session.getLastChunkPosition() == null) {\n ChunkUtils.updateChunkPosition(session, Vector3i.from(packet.getChunkX() << 4, 64, packet.getChunkZ() << 4));\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": "\tpublic boolean updateConfiguration(String mapperId, Serializable mapper, int expirationTime) {\n\t\tString configuration = XStreamHelper.createXStreamInstance().toXML(mapper);\n\t\tDate currentDate = new Date();\n\t\tDate expirationDate = null;\n\t\tif(expirationTime > 0) {\n\t\t\tCalendar cal = Calendar.getInstance();\n\t\t\tcal.setTime(currentDate);\n\t\t\tcal.add(Calendar.SECOND, expirationTime);\n\t\t\texpirationDate = cal.getTime();\n\t\t}\n\t\tint row = dbInstance.getCurrentEntityManager().createNamedQuery(\"updateMapperByMapperId\")\n\t\t\t.setParameter(\"now\", currentDate)\n\t\t\t.setParameter(\"expirationDate\", expirationDate)\n\t\t\t.setParameter(\"config\", configuration)\n\t\t\t.setParameter(\"mapperId\", mapperId)\n\t\t\t.executeUpdate();\n\n\t\tdbInstance.commit();\n\t\treturn row > 0;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-91", "cwe_name": "XML Injection (aka Blind XPath Injection)", "description": "The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system.", "url": "https://cwe.mitre.org/data/definitions/91.html", "label_name": "vulnerable"} {"code": "\tpublic VideoMetadata readVideoMetadataFile(OLATResource videoResource){\n\t\tVFSContainer baseContainer= FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n\t\ttry {\n\t\t\treturn (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"Error while parsing XStream file for videoResource::{}\", videoResource, e);\n\t\t\t// return an empty, so at least it displays something and not an error\n\t\t\tVideoMetadata meta = new VideoMetadataImpl();\n\t\t\tmeta.setWidth(800);\n\t\t\tmeta.setHeight(600);\n\t\t\treturn meta;\n\t\t}\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-91", "cwe_name": "XML Injection (aka Blind XPath Injection)", "description": "The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system.", "url": "https://cwe.mitre.org/data/definitions/91.html", "label_name": "vulnerable"} {"code": "\tpublic void testUpdateMapper_serializade() {\n\t\t//create a mapper\n\t\tString mapperId = UUID.randomUUID().toString();\n\t\tString sessionId = UUID.randomUUID().toString().substring(0, 32);\n\t\tPersistentMapper sMapper = new PersistentMapper(\"mapper-to-persist-bis\");\n\t\tPersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, -1);\n\t\tAssert.assertNotNull(pMapper);\n\t\tdbInstance.commitAndCloseSession();\n\t\t\n\t\t//load the mapper\n\t\tPersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId);\n\t\tAssert.assertNotNull(loadedMapper);\n\t\tObject objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration());\n\t\tAssert.assertTrue(objReloaded instanceof PersistentMapper);\n\t\tPersistentMapper sMapperReloaded = (PersistentMapper)objReloaded;\n\t\tAssert.assertEquals(\"mapper-to-persist-bis\", sMapperReloaded.getKey());\n\t\t\n\t\t//update\n\t\tPersistentMapper sMapper2 = new PersistentMapper(\"mapper-to-update\");\n\t\tboolean updated = mapperDao.updateConfiguration(mapperId, sMapper2, -1);\n\t\tAssert.assertTrue(updated);\n\t\tdbInstance.commitAndCloseSession();\n\t\t\n\t\t//load the updated mapper\n\t\tPersistedMapper loadedMapper2 = mapperDao.loadByMapperId(mapperId);\n\t\tAssert.assertNotNull(loadedMapper2);\n\t\tObject objReloaded2 = XStreamHelper.createXStreamInstance().fromXML(loadedMapper2.getXmlConfiguration());\n\t\tAssert.assertTrue(objReloaded2 instanceof PersistentMapper);\n\t\tPersistentMapper sMapperReloaded2 = (PersistentMapper)objReloaded2;\n\t\tAssert.assertEquals(\"mapper-to-update\", sMapperReloaded2.getKey());\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-91", "cwe_name": "XML Injection (aka Blind XPath Injection)", "description": "The software does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system.", "url": "https://cwe.mitre.org/data/definitions/91.html", "label_name": "vulnerable"} {"code": "\tprivate void processReturnFiles(VFSLeaf target, List rows) {\n\t\tMap assessedIdToRow = new HashMap<>();\n\t\tfor(BulkAssessmentRow row:rows) {\n\t\t\tassessedIdToRow.put(row.getAssessedId(), row);\n\t\t}\n\n\t\tif(target.exists()) {\n\t\t\tFile parentTarget = ((LocalImpl)target).getBasefile().getParentFile();\n\n\t\t\tZipEntry entry;\n\t\t\ttry(InputStream is = target.getInputStream();\n\t\t\t\t\tZipInputStream zis = new ZipInputStream(is)) {\n\t\t\t\tbyte[] b = new byte[FileUtils.BSIZE];\n\t\t\t\twhile ((entry = zis.getNextEntry()) != null) {\n\t\t\t\t\tif(!entry.isDirectory()) {\n\t\t\t\t\t\twhile (zis.read(b) > 0) {\n\t\t\t\t\t\t\t//continue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tPath op = new File(parentTarget, entry.getName()).toPath();\n\t\t\t\t\t\tif(!Files.isHidden(op) && !op.toFile().isDirectory()) {\n\t\t\t\t\t\t\tPath parentDir = op.getParent();\n\t\t\t\t\t\t\tString assessedId = parentDir.getFileName().toString();\n\t\t\t\t\t\t\tString filename = op.getFileName().toString();\n\n\t\t\t\t\t\t\tBulkAssessmentRow row;\n\t\t\t\t\t\t\tif(assessedIdToRow.containsKey(assessedId)) {\n\t\t\t\t\t\t\t\trow = assessedIdToRow.get(assessedId);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\trow = new BulkAssessmentRow();\n\t\t\t\t\t\t\t\trow.setAssessedId(assessedId);\n\t\t\t\t\t\t\t\tassessedIdToRow.put(assessedId, row);\n\t\t\t\t\t\t\t\trows.add(row);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(row.getReturnFiles() == null) {\n\t\t\t\t\t\t\t\trow.setReturnFiles(new ArrayList(2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trow.getReturnFiles().add(filename);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch(Exception e) {\n\t\t\t\tlogError(\"\", e);\n\t\t\t}\n\t\t}\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "\tprivate void parse(UserRequest ureq) {\n\t\tString[] sFiles = ureq.getHttpReq().getParameterValues(FORM_ID);\n\t\tif (sFiles == null || sFiles.length == 0) return;\n\t\tfiles = Arrays.asList(sFiles);\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " private void updateStatus() {\n if (config.getHIDMode() == 0) {\n config.setNetworkStatus(false);\n EditorActivity.stopNetworkSocketService(this);\n ipButton.setVisibility(View.GONE);\n ipStatusDivider.setVisibility(View.GONE);\n if (config.getUSBStatus()) {\n statusText.setText(R.string.config_status_usb_on);\n statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_usb));\n } else {\n statusText.setText(R.string.config_status_usb_off);\n statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_usb_off));\n }\n } else if (config.getHIDMode() == 1) {\n EditorActivity.startNetworkSocketService(this);\n ipButton.setVisibility(View.VISIBLE);\n ipStatusDivider.setVisibility(View.VISIBLE);\n if (config.getNetworkStatus()) {\n statusText.setText(R.string.config_status_net_on);\n statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_net));\n } else {\n statusText.setText(R.string.config_status_net_off);\n statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_net_off));\n }\n EditorActivity.updateNotification(this);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-327", "cwe_name": "Use of a Broken or Risky Cryptographic Algorithm", "description": "The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.", "url": "https://cwe.mitre.org/data/definitions/327.html", "label_name": "vulnerable"} {"code": " private JsonNode yamlPathToJson(Path path) throws IOException {\n Yaml reader = new Yaml();\n ObjectMapper mapper = new ObjectMapper();\n Path p;\n \n try (InputStream in = Files.newInputStream(path)) {\n \treturn mapper.valueToTree(reader.load(in));\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "vulnerable"} {"code": " public Group createDefaultReadGroup(Context context, Collection collection, String typeOfGroupString,\n int defaultRead)\n throws SQLException, AuthorizeException {\n Group role = groupService.create(context);\n groupService.setName(role, \"COLLECTION_\" + collection.getID().toString() + \"_\" + typeOfGroupString +\n \"_DEFAULT_READ\");\n\n // Remove existing privileges from the anonymous group.\n authorizeService.removePoliciesActionFilter(context, collection, defaultRead);\n\n // Grant our new role the default privileges.\n authorizeService.addPolicy(context, collection, defaultRead, role);\n groupService.update(context, role);\n return role;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-863", "cwe_name": "Incorrect Authorization", "description": "The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.", "url": "https://cwe.mitre.org/data/definitions/863.html", "label_name": "vulnerable"} {"code": " protected synchronized void releaseNativeResources() throws Exception {\n synchronized (globalRef) {\n if (globalRef != null) {\n try {\n globalRef.close();\n } finally {\n globalRef = null;\n }\n }\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " public static DocumentBuilderFactory getNsAwareDocumentBuilderFactory() throws ParserConfigurationException {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setNamespaceAware(true);\n setFeature(dbf, \"http://apache.org/xml/features/disallow-doctype-decl\");\n return dbf;\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-611", "cwe_name": "Improper Restriction of XML External Entity Reference", "description": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.", "url": "https://cwe.mitre.org/data/definitions/611.html", "label_name": "vulnerable"} {"code": "\tstatic public UStroke getStrokeInternal(IGroup group, ISkinParam skinParam, Style style) {\n\t\tfinal Colors colors = group.getColors();\n\t\tif (colors.getSpecificLineStroke() != null)\n\t\t\treturn colors.getSpecificLineStroke();\n\n\t\tif (style != null)\n\t\t\treturn style.getStroke();\n\n\t\tif (group.getUSymbol() != null && group.getUSymbol() != USymbols.PACKAGE)\n\t\t\treturn group.getUSymbol().getSkinParameter().getStroke(skinParam, group.getStereotype());\n\n\t\treturn GeneralImageBuilder.getForcedStroke(group.getStereotype(), skinParam);\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "\tpublic final HColor getBackColor(ISkinParam skinParam, Style style) {\n\t\tif (colors == null || colors.getColor(ColorType.BACK) == null) {\n\t\t\tif (UseStyle.useBetaStyle() == false)\n\t\t\t\treturn HColorUtils.COL_D7E0F2;\n\n\t\t\treturn style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());\n\t\t}\n\t\treturn colors.getColor(ColorType.BACK);\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "\tprotected SymbolContext getContextLegacy() {\n\n\t\tif (UseStyle.useBetaStyle() == false)\n\t\t\treturn new SymbolContext(HColorUtils.COL_D7E0F2, HColorUtils.COL_038048).withStroke(new UStroke(2));\n\n\t\tfinal HColor lineColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(),\n\t\t\t\tskinParam.getIHtmlColorSet());\n\t\tfinal HColor backgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(),\n\t\t\t\tskinParam.getIHtmlColorSet());\n\n\t\treturn new SymbolContext(backgroundColor, lineColor).withStroke(getStroke());\n\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "\tpublic PlayerClock(String title, ISkinParam skinParam, TimingRuler ruler, int period, int pulse, int offset,\n\t\t\tboolean compact) {\n\t\tsuper(title, skinParam, ruler, compact);\n\t\tthis.displayTitle = title.length() > 0;\n\t\tthis.period = period;\n\t\tthis.pulse = pulse;\n\t\tthis.offset = offset;\n\t\tthis.suggestedHeight = 30;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "\tpublic CommandExecutionResult createRobustConcise(String code, String full, TimingStyle type, boolean compact) {\n\t\tfinal Player player = new PlayerRobustConcise(type, full, getSkinParam(), ruler, compactByDefault || compact);\n\t\tplayers.put(code, player);\n\t\tlastPlayer = player;\n\t\treturn CommandExecutionResult.ok();\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "\tpublic static HColor noGradient(HColor color) {\n\t\tif (color instanceof HColorGradient) {\n\t\t\treturn ((HColorGradient) color).getColor1();\n\t\t}\n\t\treturn color;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": "\tpublic static int beta() {\n\t\tfinal int beta = 1;\n\t\treturn beta;\n\t}", "label": 0, "programming_language": "Java", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": " public void update(DatabaseTypeUpdateRequest request) {\n databaseTypeDao.selectOptionalById(request.getId()).ifPresent(data -> {\n if (DatabaseTypes.has(data.getDatabaseType())) {\n throw DomainErrors.MUST_NOT_MODIFY_SYSTEM_DEFAULT_DATABASE_TYPE.exception();\n }\n\n DatabaseTypePojo pojo = databaseTypePojoConverter.of(request);\n try {\n databaseTypeDao.updateById(pojo);\n } catch (DuplicateKeyException e) {\n throw DomainErrors.DATABASE_TYPE_NAME_DUPLICATE.exception();\n }\n\n // \u540d\u79f0\u4fee\u6539\uff0c\u4e0b\u8f7d\u5730\u5740\u4fee\u6539\u9700\u8981\u5220\u9664\u539f\u6709\u7684 driver\n if (!Objects.equals(request.getDatabaseType(), data.getDatabaseType())\n || !Objects.equals(request.getJdbcDriverFileUrl(), data.getJdbcDriverFileUrl())) {\n driverResources.delete(data.getDatabaseType());\n }\n });\n\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " private void ondata(byte[] data) {\n try {\n this.decoder.add(data);\n } catch (DecodingException e) {\n this.onerror(e);\n }\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": " public void encodeByteArray() {\n Packet packet = new Packet<>(Parser.BINARY_EVENT);\n packet.data = \"abc\".getBytes(Charset.forName(\"UTF-8\"));\n packet.id = 23;\n packet.nsp = \"/cool\";\n Helpers.testBin(packet);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": " protected TestPolicy(Policy.ParseContext parseContext) throws PolicyException {\n super(parseContext);\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " public static final String getRevision() {\n return \"a\";\n }", "label": 0, "programming_language": "Java", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt,\n\t\t\t\t void (*get)(struct x86_emulate_ctxt *ctxt,\n\t\t\t\t\t struct desc_ptr *ptr))\n{\n\tstruct desc_ptr desc_ptr;\n\n\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n\t\tctxt->op_bytes = 8;\n\tget(ctxt, &desc_ptr);\n\tif (ctxt->op_bytes == 2) {\n\t\tctxt->op_bytes = 4;\n\t\tdesc_ptr.address &= 0x00ffffff;\n\t}\n\t/* Disable writeback. */\n\tctxt->dst.type = OP_NONE;\n\treturn segmented_write_std(ctxt, ctxt->dst.addr.mem,\n\t\t\t\t &desc_ptr, 2 + ctxt->op_bytes);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "static inline int assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)\n{\n\treturn assign_eip_far(ctxt, dst, ctxt->mode == X86EMUL_MODE_PROT64);\n}", "label": 1, "programming_language": "C++", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "static int em_loop(struct x86_emulate_ctxt *ctxt)\n{\n\tint rc = X86EMUL_CONTINUE;\n\n\tregister_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -1);\n\tif ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) &&\n\t (ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))\n\t\trc = jmp_rel(ctxt, ctxt->src.val);\n\n\treturn rc;\n}", "label": 1, "programming_language": "C++", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "static int em_jcxz(struct x86_emulate_ctxt *ctxt)\n{\n\tint rc = X86EMUL_CONTINUE;\n\n\tif (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)\n\t\trc = jmp_rel(ctxt, ctxt->src.val);\n\n\treturn rc;\n}", "label": 1, "programming_language": "C++", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "compat_mpt_command(struct file *filp, unsigned int cmd,\n\t\t\tunsigned long arg)\n{\n\tstruct mpt_ioctl_command32 karg32;\n\tstruct mpt_ioctl_command32 __user *uarg = (struct mpt_ioctl_command32 __user *) arg;\n\tstruct mpt_ioctl_command karg;\n\tMPT_ADAPTER *iocp = NULL;\n\tint iocnum, iocnumX;\n\tint nonblock = (filp->f_flags & O_NONBLOCK);\n\tint ret;\n\n\tif (copy_from_user(&karg32, (char __user *)arg, sizeof(karg32)))\n\t\treturn -EFAULT;\n\n\t/* Verify intended MPT adapter */\n\tiocnumX = karg32.hdr.iocnum & 0xFF;\n\tif (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||\n\t (iocp == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"::compat_mpt_command @%d - ioc%d not found!\\n\",\n\t\t\t__LINE__, iocnumX);\n\t\treturn -ENODEV;\n\t}\n\n\tif ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n\t\treturn ret;\n\n\tdctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT \"compat_mpt_command() called\\n\",\n\t iocp->name));\n\t/* Copy data to karg */\n\tkarg.hdr.iocnum = karg32.hdr.iocnum;\n\tkarg.hdr.port = karg32.hdr.port;\n\tkarg.timeout = karg32.timeout;\n\tkarg.maxReplyBytes = karg32.maxReplyBytes;\n\n\tkarg.dataInSize = karg32.dataInSize;\n\tkarg.dataOutSize = karg32.dataOutSize;\n\tkarg.maxSenseBytes = karg32.maxSenseBytes;\n\tkarg.dataSgeOffset = karg32.dataSgeOffset;\n\n\tkarg.replyFrameBufPtr = (char __user *)(unsigned long)karg32.replyFrameBufPtr;\n\tkarg.dataInBufPtr = (char __user *)(unsigned long)karg32.dataInBufPtr;\n\tkarg.dataOutBufPtr = (char __user *)(unsigned long)karg32.dataOutBufPtr;\n\tkarg.senseDataPtr = (char __user *)(unsigned long)karg32.senseDataPtr;\n\n\t/* Pass new structure to do_mpt_command\n\t */\n\tret = mptctl_do_mpt_command (iocp, karg, &uarg->MF);\n\n\tmutex_unlock(&iocp->ioctl_cmds.mutex);\n\n\treturn ret;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "safe"} {"code": "mptctl_eventquery (MPT_ADAPTER *ioc, unsigned long arg)\n{\n\tstruct mpt_ioctl_eventquery __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_eventquery\t karg;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_eventquery - \"\n\t\t\t\"Unable to read in mpt_ioctl_eventquery struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_eventquery called.\\n\",\n\t ioc->name));\n\tkarg.eventEntries = MPTCTL_EVENT_LOG_SIZE;\n\tkarg.eventTypes = ioc->eventTypes;\n\n\t/* Copy the data from kernel memory to user memory\n\t */\n\tif (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_eventquery - \"\n\t\t\t\"Unable to write out mpt_ioctl_eventquery struct @ %p\\n\",\n\t\t\tioc->name, __FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\treturn 0;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "safe"} {"code": "const char *string_of_NPNVariable(int variable)\n{\n const char *str;\n\n switch (variable) {\n#define _(VAL) case VAL: str = #VAL; break;\n\t_(NPNVxDisplay);\n\t_(NPNVxtAppContext);\n\t_(NPNVnetscapeWindow);\n\t_(NPNVjavascriptEnabledBool);\n\t_(NPNVasdEnabledBool);\n\t_(NPNVisOfflineBool);\n\t_(NPNVserviceManager);\n\t_(NPNVDOMElement);\n\t_(NPNVDOMWindow);\n\t_(NPNVToolkit);\n\t_(NPNVSupportsXEmbedBool);\n\t_(NPNVWindowNPObject);\n\t_(NPNVPluginElementNPObject);\n\t_(NPNVSupportsWindowless);\n\t_(NPNVprivateModeBool);\n\t_(NPNVsupportsAdvancedKeyHandling);\n#undef _\n default:\n\tswitch (variable & 0xff) {\n#define _(VAL, VAR) case VAL: str = #VAR; break\n\t _(10, NPNVserviceManager);\n\t _(11, NPNVDOMElement);\n\t _(12, NPNVDOMWindow);\n\t _(13, NPNVToolkit);\n#undef _\n\tdefault:\n\t str = \"\";\n\t break;\n\t}\n\tbreak;\n }\n\n return str;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " void operator = (const IniSection &s)\n\t{\n\t if (&s == this)\n\t {\n\t\treturn;\n\t } \n\t IniBase::operator = (s);\n\t ip = s.ip;\n\t end_comment = s.end_comment;\n is_private = s.is_private;\n rewrite_by = s.rewrite_by;\n\t container = s.container;\n\n\t reindex ();\n\t}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": "void CIRCNetwork::SetEncoding(const CString& s) {\n m_sEncoding = CZNC::Get().FixupEncoding(s);\n if (GetIRCSock()) {\n GetIRCSock()->SetEncoding(m_sEncoding);\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "void CZNC::ForceEncoding() {\n m_uiForceEncoding++;\n#ifdef HAVE_ICU\n for (Csock* pSock : GetManager()) {\n pSock->SetEncoding(FixupEncoding(pSock->GetEncoding()));\n }\n#endif\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "bool CClient::OnTextMessage(CTextMessage& Message) {\n CString sTargets = Message.GetTarget();\n\n VCString vTargets;\n sTargets.Split(\",\", vTargets, false);\n\n for (CString& sTarget : vTargets) {\n Message.SetTarget(sTarget);\n if (m_pNetwork) {\n // May be nullptr.\n Message.SetChan(m_pNetwork->FindChan(sTarget));\n }\n\n if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {\n EchoMessage(Message);\n\n if (sTarget.Equals(\"status\")) {\n CString sMsg = Message.GetText();\n UserCommand(sMsg);\n } else {\n CALLMOD(sTarget, this, m_pUser, m_pNetwork,\n OnModCommand(Message.GetText()));\n }\n continue;\n }\n\n bool bContinue = false;\n NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,\n &bContinue);\n if (bContinue) continue;\n\n if (!GetIRCSock()) {\n // Some lagmeters do a PRIVMSG to their own nick, ignore those.\n if (!sTarget.Equals(m_sNick))\n PutStatus(\n t_f(\"Your message to {1} got lost, you are not connected \"\n \"to IRC!\")(Message.GetTarget()));\n continue;\n }\n\n if (m_pNetwork) {\n AddBuffer(Message);\n EchoMessage(Message);\n PutIRC(Message.ToString(CMessage::ExcludePrefix |\n CMessage::ExcludeTags));\n }\n }\n\n return true;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "void CClient::EchoMessage(const CMessage& Message) {\n CMessage EchoedMessage = Message;\n for (CClient* pClient : GetClients()) {\n if (pClient->HasEchoMessage() ||\n (pClient != this && ((m_pNetwork && m_pNetwork->IsChan(Message.GetParam(0))) ||\n pClient->HasSelfMessage()))) {\n EchoedMessage.SetNick(GetNickMask());\n pClient->PutClient(EchoedMessage);\n }\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "void FrameFactory::rebuildAggregateFrames(ID3v2::Tag *tag) const\n{\n if(tag->header()->majorVersion() < 4 &&\n tag->frameList(\"TDRC\").size() == 1 &&\n tag->frameList(\"TDAT\").size() == 1)\n {\n TextIdentificationFrame *tdrc =\n dynamic_cast(tag->frameList(\"TDRC\").front());\n UnknownFrame *tdat = static_cast(tag->frameList(\"TDAT\").front());\n\n if(tdrc &&\n tdrc->fieldList().size() == 1 &&\n tdrc->fieldList().front().size() == 4 &&\n tdat->data().size() >= 5)\n {\n String date(tdat->data().mid(1), String::Type(tdat->data()[0]));\n if(date.length() == 4) {\n tdrc->setText(tdrc->toString() + '-' + date.substr(2, 2) + '-' + date.substr(0, 2));\n if(tag->frameList(\"TIME\").size() == 1) {\n UnknownFrame *timeframe = static_cast(tag->frameList(\"TIME\").front());\n if(timeframe->data().size() >= 5) {\n String time(timeframe->data().mid(1), String::Type(timeframe->data()[0]));\n if(time.length() == 4) {\n tdrc->setText(tdrc->toString() + 'T' + time.substr(0, 2) + ':' + time.substr(2, 2));\n }\n }\n }\n }\n }\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-434", "cwe_name": "Unrestricted Upload of File with Dangerous Type", "description": "The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.", "url": "https://cwe.mitre.org/data/definitions/434.html", "label_name": "safe"} {"code": "\tCommandAuthenticate(Module* Creator, SimpleExtItem& ext, GenericCap& Cap)\n\t\t: Command(Creator, \"AUTHENTICATE\", 1), authExt(ext), cap(Cap)\n\t{\n\t\tworks_before_reg = true;\n\t\tallow_empty_last_param = false;\n\t}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "\tCmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE\n\t{\n\t\tif (parameters.empty())\n\t\t\treturn ShowSilenceList(user);\n\n\t\t// If neither add nor remove are specified we default to add.\n\t\tbool is_remove = parameters[0][0] == '-';\n\n\t\t// If a prefix mask has been given then strip it and clean it up.\n\t\tstd::string mask = parameters[0];\n\t\tif (mask[0] == '-' || mask[0] == '+')\n\t\t{\n\t\t\tmask.erase(0);\n\t\t\tif (mask.empty())\n\t\t\t\tmask.assign(\"*\");\n\t\t\tModeParser::CleanMask(mask);\n\t\t}\n\n\t\t// If the user specified a flags then use that. Otherwise, default to blocking\n\t\t// all CTCPs, invites, notices, privmsgs, and invites.\n\t\tuint32_t flags = SilenceEntry::SF_DEFAULT;\n\t\tif (parameters.size() > 1)\n\t\t{\n\t\t\tif (!SilenceEntry::FlagsToBits(parameters[1], flags))\n\t\t\t{\n\t\t\t\tuser->WriteNumeric(ERR_SILENCE, mask, parameters[1], \"You specified one or more invalid SILENCE flags\");\n\t\t\t\treturn CMD_FAILURE;\n\t\t\t}\n\t\t\telse if (flags == SilenceEntry::SF_EXEMPT)\n\t\t\t{\n\t\t\t\t// The user specified \"x\" with no other flags which does not make sense; add the \"d\" flag.\n\t\t\t\tflags |= SilenceEntry::SF_DEFAULT;\n\t\t\t}\n\t\t}\n\n\t\treturn is_remove ? RemoveSilence(user, mask, flags) : AddSilence(user, mask, flags);\n\t}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "\tvoid ReadConfig(ConfigStatus& status) CXX11_OVERRIDE\n\t{\n\t\tConfigTag* tag = ServerInstance->Config->ConfValue(\"silence\");\n\t\texemptuline = tag->getBool(\"exemptuline\", true);\n\t\tcmd.maxsilence = tag->getUInt(\"maxentries\", 32, 1);\n\t}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "\tstatic std::string BitsToFlags(uint32_t flags)\n\t{\n\t\tstd::string out;\n\t\tif (flags & SF_CTCP_USER)\n\t\t\tout.push_back('C');\n\t\tif (flags & SF_CTCP_CHANNEL)\n\t\t\tout.push_back('c');\n\t\tif (flags & SF_INVITE)\n\t\t\tout.push_back('i');\n\t\tif (flags & SF_NOTICE_USER)\n\t\t\tout.push_back('N');\n\t\tif (flags & SF_NOTICE_CHANNEL)\n\t\t\tout.push_back('n');\n\t\tif (flags & SF_PRIVMSG_USER)\n\t\t\tout.push_back('P');\n\t\tif (flags & SF_PRIVMSG_CHANNEL)\n\t\t\tout.push_back('p');\n\t\tif (flags & SF_TAGMSG_CHANNEL)\n\t\t\tout.push_back('T');\n\t\tif (flags & SF_TAGMSG_USER)\n\t\t\tout.push_back('t');\n\t\tif (flags & SF_EXEMPT)\n\t\t\tout.push_back('x');\n\t\treturn out;\n\t}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "\tCmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE\n\t{\n\t\tsize_t origin = parameters.size() > 1 ? 1 : 0;\n\t\tif (parameters[origin].empty())\n\t\t{\n\t\t\tuser->WriteNumeric(ERR_NOORIGIN, \"No origin specified\");\n\t\t\treturn CMD_FAILURE;\n\t\t}\n\n\t\tClientProtocol::Messages::Pong pong(parameters[0], origin ? parameters[1] : ServerInstance->Config->GetServerName());\n\t\tuser->Send(ServerInstance->GetRFCEvents().pong, pong);\n\t\treturn CMD_SUCCESS;\n\t}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-732", "cwe_name": "Incorrect Permission Assignment for Critical Resource", "description": "The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.", "url": "https://cwe.mitre.org/data/definitions/732.html", "label_name": "safe"} {"code": "\tvoid initialize(const string &path, bool owner) {\n\t\tTRACE_POINT();\n\t\tstruct stat buf;\n\t\tint ret;\n\n\t\tthis->path = path;\n\t\tthis->owner = owner;\n\t\t\n\t\t/* Create the server instance directory. We only need to write to this\n\t\t * directory for these reasons:\n\t\t * 1. Initial population of structure files (structure_version.txt, instance.pid).\n\t\t * 2. Creating/removing a generation directory.\n\t\t * 3. Removing the entire server instance directory (after all\n\t\t * generations are removed).\n\t\t *\n\t\t * 1 and 2 are done by the helper server during initialization and before lowering\n\t\t * privilege. 3 is done during helper server shutdown by a cleanup process that's\n\t\t * running as the same user the helper server was running as before privilege\n\t\t * lowering.\n\t\t * Therefore, we make the directory only writable by the user the helper server\n\t\t * was running as before privilege is lowered. Everybody else has read and execute\n\t\t * rights though, because we want admin tools to be able to list the available\n\t\t * generations no matter what user they're running as.\n\t\t */\n\n\t\tdo {\n\t\t\tret = lstat(path.c_str(), &buf);\n\t\t} while (ret == -1 && errno == EAGAIN);\n\t\tif (owner) {\n\t\t\tif (ret == 0) {\n\t\t\t\tif (S_ISDIR(buf.st_mode)) {\n\t\t\t\t\tverifyDirectoryPermissions(path, buf);\n\t\t\t\t} else {\n\t\t\t\t\tthrow RuntimeException(\"'\" + path + \"' already exists, and is not a directory\");\n\t\t\t\t}\n\t\t\t} else if (errno == ENOENT) {\n\t\t\t\tcreateDirectory(path);\n\t\t\t} else {\n\t\t\t\tint e = errno;\n\t\t\t\tthrow FileSystemException(\"Cannot lstat '\" + path + \"'\",\n\t\t\t\t\te, path);\n\t\t\t}\n\t\t} else if (!S_ISDIR(buf.st_mode)) {\n\t\t\tthrow RuntimeException(\"Server instance directory '\" + path +\n\t\t\t\t\"' does not exist\");\n\t\t}\n\t}", "label": 1, "programming_language": "C++", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "safe"} {"code": "void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)\n{\n Q_UNUSED(bufferInfo);\n if (!msg.contains(' '))\n return;\n\n QString target = msg.section(' ', 0, 0);\n QString msgSection = msg.section(' ', 1);\n\n std::function encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {\n return userEncode(target, message);\n };\n\n#ifdef HAVE_QCA2\n putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));\n#else\n putPrivmsg(target, msgSection, encodeFunc);\n#endif\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "safe"} {"code": "FBUnserializer::unserializeVector(size_t depth) {\n p_ += CODE_SIZE;\n\n typename V::VectorType ret = V::createVector();\n\n size_t code = nextCode();\n while (code != FB_SERIALIZE_STOP) {\n V::vectorAppend(ret, unserializeThing(depth + 1));\n code = nextCode();\n }\n p_ += CODE_SIZE;\n return ret;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-674", "cwe_name": "Uncontrolled Recursion", "description": "The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.", "url": "https://cwe.mitre.org/data/definitions/674.html", "label_name": "safe"} {"code": "inline typename V::MapType FBUnserializer::unserializeMap(size_t depth) {\n p_ += CODE_SIZE;\n\n typename V::MapType ret = V::createMap();\n\n size_t code = nextCode();\n while (code != FB_SERIALIZE_STOP) {\n switch (code) {\n case FB_SERIALIZE_VARCHAR:\n case FB_SERIALIZE_STRING:\n {\n auto key = unserializeString();\n auto value = unserializeThing(depth + 1);\n V::mapSet(ret, std::move(key), std::move(value));\n }\n break;\n default:\n {\n auto key = unserializeInt64();\n auto value = unserializeThing(depth + 1);\n V::mapSet(ret, std::move(key), std::move(value));\n }\n }\n\n code = nextCode();\n }\n p_ += CODE_SIZE;\n\n return ret;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-674", "cwe_name": "Uncontrolled Recursion", "description": "The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.", "url": "https://cwe.mitre.org/data/definitions/674.html", "label_name": "safe"} {"code": "void VariableUnserializer::unserializeProp(ObjectData* obj,\n const String& key,\n Class* ctx,\n const String& realKey,\n int nProp) {\n\n auto const cls = obj->getVMClass();\n auto const lookup = cls->getDeclPropSlot(ctx, key.get());\n auto const slot = lookup.slot;\n tv_lval t;\n\n if (slot == kInvalidSlot || !lookup.accessible) {\n // Unserialize as a dynamic property. If this is the first, we need to\n // pre-allocate space in the array to ensure the elements don't move during\n // unserialization.\n obj->reserveDynProps(nProp);\n t = obj->makeDynProp(realKey.get());\n } else {\n // We'll check if this doesn't violate the type-hint once we're done\n // unserializing all the props.\n t = obj->getPropLval(ctx, key.get());\n }\n\n unserializePropertyValue(t, nProp);\n if (!RuntimeOption::RepoAuthoritative) return;\n if (!Repo::get().global().HardPrivatePropInference) return;\n\n /*\n * We assume for performance reasons in repo authoriative mode that\n * we can see all the sets to private properties in a class.\n *\n * It's a hole in this if we don't check unserialization doesn't\n * violate what we've seen, which we handle by throwing if the repo\n * was built with this option.\n */\n if (UNLIKELY(slot == kInvalidSlot)) return;\n auto const repoTy = cls->declPropRepoAuthType(slot);\n if (LIKELY(tvMatchesRepoAuthType(*t, repoTy))) return;\n if (t.type() == KindOfUninit &&\n (cls->declProperties()[slot].attrs & AttrLateInit)) {\n return;\n }\n throwUnexpectedType(key, obj, *t);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "void pcre_dump_cache(folly::File& file) {\n s_pcreCache.dump(file);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "String HHVM_FUNCTION(ldap_escape,\n const String& value,\n const String& ignores /* = \"\" */,\n int flags /* = 0 */) {\n char esc[256] = {};\n\n if (flags & k_LDAP_ESCAPE_FILTER) { // llvm.org/bugs/show_bug.cgi?id=18389\n esc['*'*1u] = esc['('*1u] = esc[')'*1u] = esc['\\0'*1u] = esc['\\\\'*1u] = 1;\n }\n\n if (flags & k_LDAP_ESCAPE_DN) {\n esc[','*1u] = esc['='*1u] = esc['+'*1u] = esc['<'*1u] = esc['\\\\'*1u] = 1;\n esc['>'*1u] = esc[';'*1u] = esc['\"'*1u] = esc['#'*1u] = 1;\n }\n\n if (!flags) {\n memset(esc, 1, sizeof(esc));\n }\n\n for (int i = 0; i < ignores.size(); i++) {\n esc[(unsigned char)ignores[i]] = 0;\n }\n\n char hex[] = \"0123456789abcdef\";\n\n String result(3UL * value.size(), ReserveString);\n char *rdata = result.get()->mutableData(), *r = rdata;\n\n for (int i = 0; i < value.size(); i++) {\n auto c = (unsigned char)value[i];\n if (esc[c]) {\n *r++ = '\\\\';\n *r++ = hex[c >> 4];\n *r++ = hex[c & 0xf];\n } else {\n *r++ = c;\n }\n }\n\n result.setSize(r - rdata);\n return result;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": "Variant HHVM_METHOD(XMLReader, expand,\n const Variant& basenode /* = null */) {\n auto* data = Native::data(this_);\n req::ptr doc;\n xmlDocPtr docp = nullptr;\n SYNC_VM_REGS_SCOPED();\n\n if (!basenode.isNull()) {\n auto dombasenode = Native::data(basenode.toObject());\n doc = dombasenode->doc();\n if (doc == nullptr || doc->docp() == nullptr) {\n raise_warning(\"Invalid State Error\");\n return false;\n }\n docp = doc->docp();\n }\n\n if (data->m_ptr) {\n xmlNodePtr node = xmlTextReaderExpand(data->m_ptr);\n if (node == nullptr) {\n raise_warning(\"An Error Occurred while expanding\");\n return false;\n } else {\n xmlNodePtr nodec = xmlDocCopyNode(node, docp, 1);\n if (nodec == nullptr) {\n raise_notice(\"Cannot expand this node type\");\n return false;\n } else {\n return php_dom_create_object(nodec, doc);\n }\n }\n }\n\n raise_warning(\"Load Data before trying to read\");\n return false;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": "Variant HHVM_FUNCTION(mcrypt_create_iv, int size, int source /* = 0 */) {\n if (size <= 0 || size >= INT_MAX) {\n raise_warning(\"Can not create an IV with a size of less than 1 or \"\n \"greater than %d\", INT_MAX);\n return false;\n }\n\n int n = 0;\n char *iv = (char*)calloc(size + 1, 1);\n if (source == RANDOM || source == URANDOM) {\n int fd = open(source == RANDOM ? \"/dev/random\" : \"/dev/urandom\", O_RDONLY);\n if (fd < 0) {\n free(iv);\n raise_warning(\"Cannot open source device\");\n return false;\n }\n int read_bytes;\n for (read_bytes = 0; read_bytes < size && n >= 0; read_bytes += n) {\n n = read(fd, iv + read_bytes, size - read_bytes);\n }\n n = read_bytes;\n close(fd);\n if (n < size) {\n free(iv);\n raise_warning(\"Could not gather sufficient random data\");\n return false;\n }\n } else {\n n = size;\n while (size) {\n // Use userspace rand() function because it handles auto-seeding\n iv[--size] = (char)f_rand(0, 255);\n }\n }\n return String(iv, n, AttachString);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "safe"} {"code": "String preg_quote(const String& str,\n const String& delimiter /* = null_string */) {\n const char* in_str = str.data();\n const char* in_str_end = in_str + str.size();\n\n /* Nothing to do if we got an empty string */\n if (in_str == in_str_end) {\n return str;\n }\n\n char delim_char = 0; /* Delimiter character to be quoted */\n bool quote_delim = false; /* Whether to quote additional delim char */\n if (!delimiter.empty()) {\n delim_char = delimiter.charAt(0);\n quote_delim = true;\n }\n\n /* Allocate enough memory so that even if each character\n is quoted, we won't run out of room */\n static_assert(\n (StringData::MaxSize * 4 + 1) < std::numeric_limits::max()\n );\n String ret(4 * str.size() + 1, ReserveString);\n char* out_str = ret.mutableData();\n\n /* Go through the string and quote necessary characters */\n const char* p;\n char* q;\n for (p = in_str, q = out_str; p != in_str_end; p++) {\n char c = *p;\n switch (c) {\n case '.': case '\\\\': case '+': case '*': case '?':\n case '[': case '^': case ']': case '$': case '(':\n case ')': case '{': case '}': case '=': case '!':\n case '>': case '<': case '|': case ':': case '-':\n case '#':\n *q++ = '\\\\';\n *q++ = c;\n break;\n\n case '\\0':\n *q++ = '\\\\';\n *q++ = '0';\n *q++ = '0';\n *q++ = '0';\n break;\n\n default:\n if (quote_delim && c == delim_char)\n *q++ = '\\\\';\n *q++ = c;\n break;\n }\n }\n *q = '\\0';\n\n return ret.setSize(q - out_str);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": " const String& setSize(int64_t len) {\n assertx(m_str);\n m_str->setSize(len);\n return *this;\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": " const String& setSize(int64_t len) {\n assertx(m_str);\n m_str->setSize(len);\n return *this;\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": " const String& setSize(int64_t len) {\n assertx(m_str);\n m_str->setSize(len);\n return *this;\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": " void writeStats(Array& /*ret*/) override {\n fprintf(stderr, \"writeStats start\\n\");\n // RetSame: the return value is the same instance every time\n // HasThis: call has a this argument\n // AllSame: all returns were the same data even though args are different\n // MemberCount: number of different arg sets (including this)\n fprintf(stderr, \"Count Function MinSerLen MaxSerLen RetSame HasThis \"\n \"AllSame MemberCount\\n\");\n for (auto& me : m_memos) {\n if (me.second.m_ignore) continue;\n if (me.second.m_count == 1) continue;\n int min_ser_len = 999999999;\n int max_ser_len = 0;\n int count = 0;\n int member_count = 0;\n bool all_same = true;\n if (me.second.m_has_this) {\n bool any_multiple = false;\n auto& fr = me.second.m_member_memos.begin()->second.m_return_value;\n member_count = me.second.m_member_memos.size();\n for (auto& mme : me.second.m_member_memos) {\n if (mme.second.m_return_value != fr) all_same = false;\n count += mme.second.m_count;\n auto ser_len = mme.second.m_return_value.length();\n min_ser_len = std::min(min_ser_len, ser_len);\n max_ser_len = std::max(max_ser_len, ser_len);\n if (mme.second.m_count > 1) any_multiple = true;\n }\n if (!any_multiple && !all_same) continue;\n } else {\n min_ser_len = max_ser_len = me.second.m_return_value.length();\n count = me.second.m_count;\n all_same = me.second.m_ret_tv_same;\n }\n fprintf(stderr, \"%d %s %d %d %s %s %s %d\\n\",\n count, me.first.data(),\n min_ser_len, max_ser_len,\n me.second.m_ret_tv_same ? \" true\" : \"false\",\n me.second.m_has_this ? \" true\" : \"false\",\n all_same ? \" true\" : \"false\",\n member_count\n );\n }\n fprintf(stderr, \"writeStats end\\n\");\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " void writeStats(Array& /*ret*/) override {\n fprintf(stderr, \"writeStats start\\n\");\n // RetSame: the return value is the same instance every time\n // HasThis: call has a this argument\n // AllSame: all returns were the same data even though args are different\n // MemberCount: number of different arg sets (including this)\n fprintf(stderr, \"Count Function MinSerLen MaxSerLen RetSame HasThis \"\n \"AllSame MemberCount\\n\");\n for (auto& me : m_memos) {\n if (me.second.m_ignore) continue;\n if (me.second.m_count == 1) continue;\n int min_ser_len = 999999999;\n int max_ser_len = 0;\n int count = 0;\n int member_count = 0;\n bool all_same = true;\n if (me.second.m_has_this) {\n bool any_multiple = false;\n auto& fr = me.second.m_member_memos.begin()->second.m_return_value;\n member_count = me.second.m_member_memos.size();\n for (auto& mme : me.second.m_member_memos) {\n if (mme.second.m_return_value != fr) all_same = false;\n count += mme.second.m_count;\n auto ser_len = mme.second.m_return_value.length();\n min_ser_len = std::min(min_ser_len, ser_len);\n max_ser_len = std::max(max_ser_len, ser_len);\n if (mme.second.m_count > 1) any_multiple = true;\n }\n if (!any_multiple && !all_same) continue;\n } else {\n min_ser_len = max_ser_len = me.second.m_return_value.length();\n count = me.second.m_count;\n all_same = me.second.m_ret_tv_same;\n }\n fprintf(stderr, \"%d %s %d %d %s %s %s %d\\n\",\n count, me.first.data(),\n min_ser_len, max_ser_len,\n me.second.m_ret_tv_same ? \" true\" : \"false\",\n me.second.m_has_this ? \" true\" : \"false\",\n all_same ? \" true\" : \"false\",\n member_count\n );\n }\n fprintf(stderr, \"writeStats end\\n\");\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,\n const String& key,\n const String& iv) {\n auto pm = get_valid_mcrypt_resource(td);\n if (!pm) {\n return false;\n }\n\n int max_key_size = mcrypt_enc_get_key_size(pm->m_td);\n int iv_size = mcrypt_enc_get_iv_size(pm->m_td);\n\n if (key.empty()) {\n raise_warning(\"Key size is 0\");\n }\n\n unsigned char *key_s = (unsigned char *)malloc(key.size());\n memset(key_s, 0, key.size());\n\n unsigned char *iv_s = (unsigned char *)malloc(iv_size + 1);\n memset(iv_s, 0, iv_size + 1);\n\n int key_size;\n if (key.size() > max_key_size) {\n raise_warning(\"Key size too large; supplied length: %ld, max: %d\",\n key.size(), max_key_size);\n key_size = max_key_size;\n } else {\n key_size = key.size();\n }\n memcpy(key_s, key.data(), key.size());\n\n if (iv.size() != iv_size) {\n raise_warning(\"Iv size incorrect; supplied length: %ld, needed: %d\",\n iv.size(), iv_size);\n }\n memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));\n\n mcrypt_generic_deinit(pm->m_td);\n int result = mcrypt_generic_init(pm->m_td, key_s, key_size, iv_s);\n\n /* If this function fails, close the mcrypt module to prevent crashes\n * when further functions want to access this resource */\n if (result < 0) {\n pm->close();\n switch (result) {\n case -3:\n raise_warning(\"Key length incorrect\");\n break;\n case -4:\n raise_warning(\"Memory allocation error\");\n break;\n case -1:\n default:\n raise_warning(\"Unknown error\");\n break;\n }\n } else {\n pm->m_init = true;\n }\n\n free(iv_s);\n free(key_s);\n return result;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "ALWAYS_INLINE String serialize_impl(const Variant& value,\n const SerializeOptions& opts) {\n switch (value.getType()) {\n case KindOfClass:\n case KindOfLazyClass:\n case KindOfPersistentString:\n case KindOfString: {\n auto const str =\n isStringType(value.getType()) ? value.getStringData() :\n isClassType(value.getType()) ? classToStringHelper(value.toClassVal()) :\n lazyClassToStringHelper(value.toLazyClassVal());\n auto const size = str->size();\n if (size >= RuntimeOption::MaxSerializedStringSize) {\n throw Exception(\"Size of serialized string (%ld) exceeds max\", size);\n }\n StringBuffer sb;\n sb.append(\"s:\");\n sb.append(size);\n sb.append(\":\\\"\");\n sb.append(str->data(), size);\n sb.append(\"\\\";\");\n return sb.detach();\n }\n case KindOfResource:\n return s_Res;\n\n case KindOfUninit:\n case KindOfNull:\n case KindOfBoolean:\n case KindOfInt64:\n case KindOfFunc:\n case KindOfPersistentVec:\n case KindOfVec:\n case KindOfPersistentDict:\n case KindOfDict:\n case KindOfPersistentKeyset:\n case KindOfKeyset:\n case KindOfPersistentDArray:\n case KindOfDArray:\n case KindOfPersistentVArray:\n case KindOfVArray:\n case KindOfDouble:\n case KindOfObject:\n case KindOfClsMeth:\n case KindOfRClsMeth:\n case KindOfRFunc:\n case KindOfRecord:\n break;\n }\n VariableSerializer vs(VariableSerializer::Type::Serialize);\n if (opts.keepDVArrays) vs.keepDVArrays();\n if (opts.forcePHPArrays) vs.setForcePHPArrays();\n if (opts.warnOnHackArrays) vs.setHackWarn();\n if (opts.warnOnPHPArrays) vs.setPHPWarn();\n if (opts.ignoreLateInit) vs.setIgnoreLateInit();\n if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy();\n // Keep the count so recursive calls to serialize() embed references properly.\n return vs.serialize(value, true, true);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "static std::string make_relative_path(const std::string& path) {\n if (path.empty()) {\n return path;\n }\n\n // First get the path to a state where we don't have .. in the middle of it\n // etc. canonicalize handles Windows paths too.\n std::string canonical(FileUtil::canonicalize(path));\n\n // If we have a slash at the beginning, then just remove it and we are\n // relative. This check will hold because we have canonicalized the\n // path above to remove .. from the path, so we know we can be sure\n // we are at a good place for this check.\n if (FileUtil::isDirSeparator(canonical[0])) {\n return canonical.substr(1);\n }\n\n // If we get here, canonical looks something like:\n // a/b/c\n\n // Search through the path and if we find a place where we have a slash\n // and a \".\" just before that slash, then cut the path off right there\n // and just take everything after the slash.\n std::string relative(canonical);\n int idx = canonical.length() - 1;\n while (1) {\n while (idx > 0 && !(FileUtil::isDirSeparator(canonical[idx]))) {\n idx--;\n }\n // If we ever get to idx == 0, then there were no other slashes to deal with\n if (idx == 0) {\n return canonical;\n }\n if (idx >= 1 && (canonical[idx - 1] == '.' || canonical[idx - 1] == ':')) {\n relative = canonical.substr(idx + 1);\n break;\n }\n idx--;\n }\n return relative;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": "static String HHVM_FUNCTION(bcmul, const String& left, const String& right,\n int64_t scale /* = -1 */) {\n scale = adjust_scale(scale);\n bc_num first, second, result;\n bc_init_num(&first);\n bc_init_num(&second);\n bc_init_num(&result);\n php_str2num(&first, (char*)left.data());\n php_str2num(&second, (char*)right.data());\n bc_multiply(first, second, &result, scale);\n if (result->n_scale > scale) {\n result->n_scale = scale;\n }\n String ret(bc_num2str(result), AttachString);\n bc_free_num(&first);\n bc_free_num(&second);\n bc_free_num(&result);\n return ret;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "http_error_t::make_body (int n, const str &si, const str &aux)\n{\n strbuf b;\n str ldesc;\n const str sdesc = xss_escape (http_status.get_desc (n, &ldesc));\n b << \"\\n\"\n << \" \\n\"\n << \" \" << n << \" \" << sdesc << \"\\n\"\n << \" \\n\"\n << \" \\n\"\n << \"

      Error \" << n << \" \" << sdesc << \"



      \\n\"\n ;\n if (n == HTTP_NOT_FOUND && aux) {\n b << \"The file \" << xss_escape (aux)\n << \" was not found on this server.

      \\n\\n\";\n }\n b << \"
      \\n\"\n << \" \" << xss_escape (si) << \"\\n\"\n << \"
      \\n\"\n << \" \\n\"\n << \"\\n\"\n ;\n return b;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " public static boolean excludes( final Collection patterns,\n final URI uri ) {\n checkNotNull( \"patterns\", patterns );\n checkNotNull( \"uri\", uri );\n return matches( patterns, uri );\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": "\tboost::int64_t lazy_entry::int_value() const\n\t{\n\t\tTORRENT_ASSERT(m_type == int_t);\n\t\tboost::int64_t val = 0;\n\t\tbool negative = false;\n\t\tif (*m_data.start == '-') negative = true;\n\t\tbdecode_errors::error_code_enum ec = bdecode_errors::no_error;\n\t\tparse_int(m_data.start + negative\n\t\t\t, m_data.start + m_size, 'e', val, ec);\n\t\tif (ec) return 0;\n\t\tif (negative) val = -val;\n\t\treturn val;\n\t}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "static char *pool_strdup(const char *s)\n{\n\tsize_t len = strlen(s) + 1;\n\tchar *r = pool_alloc(len);\n\tmemcpy(r, s, len);\n\treturn r;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "\tclass BadDistanceErr : public Err {public: BadDistanceErr() : Err(INVALID_DATA_FORMAT, \"Inflator: error in bit distance\") {}};\r", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TEST_F(QuotedString_ExtractFrom_Tests, UnterminatedEscapeSequence) {\n whenInputIs(\"\\\"\\\\\\0\\\"\", 4);\n resultMustBe(0);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "static bool is_legal_file(const std::string &filename)\n{\n\tDBG_FS << \"Looking for '\" << filename << \"'.\\n\";\n\n\tif (filename.empty()) {\n\t\tLOG_FS << \" invalid filename\\n\";\n\t\treturn false;\n\t}\n\n\tif (filename.find(\"..\") != std::string::npos) {\n\t\tERR_FS << \"Illegal path '\" << filename << \"' (\\\"..\\\" not allowed).\\n\";\n\t\treturn false;\n\t}\n\n\tif (looks_like_pbl(filename)) {\n\t\tERR_FS << \"Illegal path '\" << filename << \"' (.pbl files are not allowed).\" << std::endl;\n\t\treturn false;\n\t}\n\n\treturn true;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": "void *jas_malloc(size_t size)\n{\n\tvoid *result;\n\tJAS_DBGLOG(101, (\"jas_malloc(%zu)\\n\", size));\n\tresult = malloc(size);\n\tJAS_DBGLOG(100, (\"jas_malloc(%zu) -> %p\\n\", size, result));\n\treturn result;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,\n int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,\n int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,\n uint_fast32_t inmem)\n{\n\tjas_image_cmpt_t *cmpt;\n\tsize_t size;\n\n\tJAS_DBGLOG(100, (\n\t \"jas_image_cmpt_create(%ld, %ld, %ld, %ld, %ld, %ld, %d, %d, %d)\\n\",\n\t JAS_CAST(long, tlx),\n\t JAS_CAST(long, tly),\n\t JAS_CAST(long, hstep),\n\t JAS_CAST(long, vstep),\n\t JAS_CAST(long, width),\n\t JAS_CAST(long, height),\n\t JAS_CAST(int, depth),\n\t sgnd,\n\t inmem\n\t ));\n\n\tcmpt = 0;\n\tif (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {\n\t\tgoto error;\n\t}\n\tif (!jas_safe_intfast32_add(tlx, width, 0) ||\n\t !jas_safe_intfast32_add(tly, height, 0)) {\n\t\tgoto error;\n\t}\n\tif (!jas_safe_intfast32_mul3(width, height, depth, 0)) {\n\t\tgoto error;\n\t}\n\n\tif (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {\n\t\tgoto error;\n\t}\n\n\tcmpt->type_ = JAS_IMAGE_CT_UNKNOWN;\n\tcmpt->tlx_ = tlx;\n\tcmpt->tly_ = tly;\n\tcmpt->hstep_ = hstep;\n\tcmpt->vstep_ = vstep;\n\tcmpt->width_ = width;\n\tcmpt->height_ = height;\n\tcmpt->prec_ = depth;\n\tcmpt->sgnd_ = sgnd;\n\tcmpt->stream_ = 0;\n\tcmpt->cps_ = (depth + 7) / 8;\n\n\t// Compute the number of samples in the image component, while protecting\n\t// against overflow.\n\t// size = cmpt->width_ * cmpt->height_ * cmpt->cps_;\n\tif (!jas_safe_size_mul3(cmpt->width_, cmpt->height_, cmpt->cps_, &size)) {\n\t\tgoto error;\n\t}\n\tcmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) :\n\t jas_stream_tmpfile();\n\tif (!cmpt->stream_) {\n\t\tgoto error;\n\t}\n\n\t/* Zero the component data. This isn't necessary, but it is\n\tconvenient for debugging purposes. */\n\t/* Note: conversion of size - 1 to long can overflow */\n\tif (size > 0) {\n\t\tif (size - 1 > LONG_MAX) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||\n\t\t jas_stream_putc(cmpt->stream_, 0) == EOF ||\n\t\t jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\treturn cmpt;\n\nerror:\n\tif (cmpt) {\n\t\tjas_image_cmpt_destroy(cmpt);\n\t}\n\treturn 0;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "static int putint(jas_stream_t *out, int sgnd, int prec, long val)\n{\n\tint n;\n\tint c;\n\tbool s;\n\tjas_ulong tmp;\n\tassert((!sgnd && prec >= 1) || (sgnd && prec >= 2));\n\tif (sgnd) {\n\t\tval = encode_twos_comp(val, prec);\n\t}\n\tassert(val >= 0);\n\tval &= (1 << prec) - 1;\n\tn = (prec + 7) / 8;\n\twhile (--n >= 0) {\n\t\tc = (val >> (n * 8)) & 0xff;\n\t\tif (jas_stream_putc(out, c) != c)\n\t\t\treturn -1;\n\t}\n\treturn 0;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "jas_matrix_t *jas_matrix_create(jas_matind_t numrows, jas_matind_t numcols)\n{\n\tjas_matrix_t *matrix;\n\tjas_matind_t i;\n\tsize_t size;\n\n\tmatrix = 0;\n\n\tif (numrows < 0 || numcols < 0) {\n\t\tgoto error;\n\t}\n\n\tif (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {\n\t\tgoto error;\n\t}\n\tmatrix->flags_ = 0;\n\tmatrix->numrows_ = numrows;\n\tmatrix->numcols_ = numcols;\n\tmatrix->rows_ = 0;\n\tmatrix->maxrows_ = numrows;\n\tmatrix->data_ = 0;\n\tmatrix->datasize_ = 0;\n\n\t// matrix->datasize_ = numrows * numcols;\n\tif (!jas_safe_size_mul(numrows, numcols, &size)) {\n\t\tgoto error;\n\t}\n\tmatrix->datasize_ = size;\n\n\tif (matrix->maxrows_ > 0) {\n\t\tif (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,\n\t\t sizeof(jas_seqent_t *)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tif (matrix->datasize_ > 0) {\n\t\tif (!(matrix->data_ = jas_alloc2(matrix->datasize_,\n\t\t sizeof(jas_seqent_t)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tfor (i = 0; i < numrows; ++i) {\n\t\tmatrix->rows_[i] = &matrix->data_[i * matrix->numcols_];\n\t}\n\n\tfor (i = 0; i < matrix->datasize_; ++i) {\n\t\tmatrix->data_[i] = 0;\n\t}\n\n\tmatrix->xstart_ = 0;\n\tmatrix->ystart_ = 0;\n\tmatrix->xend_ = matrix->numcols_;\n\tmatrix->yend_ = matrix->numrows_;\n\n\treturn matrix;\n\nerror:\n\tif (matrix) {\n\t\tjas_matrix_destroy(matrix);\n\t}\n\treturn 0;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "jas_matrix_t *jas_matrix_create(jas_matind_t numrows, jas_matind_t numcols)\n{\n\tjas_matrix_t *matrix;\n\tjas_matind_t i;\n\tsize_t size;\n\n\tmatrix = 0;\n\n\tif (numrows < 0 || numcols < 0) {\n\t\tgoto error;\n\t}\n\n\tif (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {\n\t\tgoto error;\n\t}\n\tmatrix->flags_ = 0;\n\tmatrix->numrows_ = numrows;\n\tmatrix->numcols_ = numcols;\n\tmatrix->rows_ = 0;\n\tmatrix->maxrows_ = numrows;\n\tmatrix->data_ = 0;\n\tmatrix->datasize_ = 0;\n\n\t// matrix->datasize_ = numrows * numcols;\n\tif (!jas_safe_size_mul(numrows, numcols, &size)) {\n\t\tgoto error;\n\t}\n\tmatrix->datasize_ = size;\n\n\tif (matrix->maxrows_ > 0) {\n\t\tif (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,\n\t\t sizeof(jas_seqent_t *)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tif (matrix->datasize_ > 0) {\n\t\tif (!(matrix->data_ = jas_alloc2(matrix->datasize_,\n\t\t sizeof(jas_seqent_t)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tfor (i = 0; i < numrows; ++i) {\n\t\tmatrix->rows_[i] = &matrix->data_[i * matrix->numcols_];\n\t}\n\n\tfor (i = 0; i < matrix->datasize_; ++i) {\n\t\tmatrix->data_[i] = 0;\n\t}\n\n\tmatrix->xstart_ = 0;\n\tmatrix->ystart_ = 0;\n\tmatrix->xend_ = matrix->numcols_;\n\tmatrix->yend_ = matrix->numrows_;\n\n\treturn matrix;\n\nerror:\n\tif (matrix) {\n\t\tjas_matrix_destroy(matrix);\n\t}\n\treturn 0;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)\n{\n\tjas_matind_t i;\n\tjas_matind_t j;\n\tjas_seqent_t *rowstart;\n\tjas_matind_t rowstep;\n\tjas_seqent_t *data;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t*data = val;\n\t\t\t}\n\t\t}\n\t}\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "jas_matrix_t *jas_seq2d_input(FILE *in)\n{\n\tjas_matrix_t *matrix;\n\tjas_matind_t i;\n\tjas_matind_t j;\n\tlong x;\n\tjas_matind_t numrows;\n\tjas_matind_t numcols;\n\tjas_matind_t xoff;\n\tjas_matind_t yoff;\n\tlong tmp_xoff;\n\tlong tmp_yoff;\n\tlong tmp_numrows;\n\tlong tmp_numcols;\n\n\tif (fscanf(in, \"%ld %ld\", &tmp_xoff, &tmp_yoff) != 2) {\n\t\treturn 0;\n\t}\n\txoff = tmp_xoff;\n\tyoff = tmp_yoff;\n\tif (fscanf(in, \"%ld %ld\", &tmp_numcols, &tmp_numrows) != 2) {\n\t\treturn 0;\n\t}\n\tnumrows = tmp_numrows;\n\tnumcols = tmp_numcols;\n\tif (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols,\n\t yoff + numrows))) {\n\t\treturn 0;\n\t}\n\n\tif (jas_matrix_numrows(matrix) != numrows ||\n\t jas_matrix_numcols(matrix) != numcols) {\n\t\tabort();\n\t}\n\n\t/* Get matrix data. */\n\tfor (i = 0; i < jas_matrix_numrows(matrix); i++) {\n\t\tfor (j = 0; j < jas_matrix_numcols(matrix); j++) {\n\t\t\tif (fscanf(in, \"%ld\", &x) != 1) {\n\t\t\t\tjas_matrix_destroy(matrix);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tjas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x));\n\t\t}\n\t}\n\n\treturn matrix;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)\n{\n\tjas_matrix_t *y;\n\tjas_matind_t i;\n\tjas_matind_t j;\n\ty = jas_matrix_create(x->numrows_, x->numcols_);\n\tfor (i = 0; i < x->numrows_; ++i) {\n\t\tfor (j = 0; j < x->numcols_; ++j) {\n\t\t\t*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);\n\t\t}\n\t}\n\treturn y;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1,\n jas_matind_t r0, jas_matind_t c0, jas_matind_t r1, jas_matind_t c1)\n{\n\tjas_matind_t i;\n\n\tif (mat0->data_) {\n\t\tif (!(mat0->flags_ & JAS_MATRIX_REF)) {\n\t\t\tjas_free(mat0->data_);\n\t\t}\n\t\tmat0->data_ = 0;\n\t\tmat0->datasize_ = 0;\n\t}\n\tif (mat0->rows_) {\n\t\tjas_free(mat0->rows_);\n\t\tmat0->rows_ = 0;\n\t}\n\tmat0->flags_ |= JAS_MATRIX_REF;\n\tmat0->numrows_ = r1 - r0 + 1;\n\tmat0->numcols_ = c1 - c0 + 1;\n\tmat0->maxrows_ = mat0->numrows_;\n\tif (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {\n\t\t/*\n\t\t\tThere is no way to indicate failure to the caller.\n\t\t\tSo, we have no choice but to abort.\n\t\t\tIdeally, this function should have a non-void return type.\n\t\t\tIn practice, a non-void return type probably would not help\n\t\t\tmuch anyways as the caller would just have to terminate anyways.\n\t\t*/\n\t\tabort();\n\t}\n\n\tfor (i = 0; i < mat0->numrows_; ++i) {\n\t\tmat0->rows_[i] = mat1->rows_[r0 + i] + c0;\n\t}\n\n\tmat0->xstart_ = mat1->xstart_ + c0;\n\tmat0->ystart_ = mat1->ystart_ + r0;\n\tmat0->xend_ = mat0->xstart_ + mat0->numcols_;\n\tmat0->yend_ = mat0->ystart_ + mat0->numrows_;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "inline static bool jas_safe_intfast32_mul3(int_fast32_t a, int_fast32_t b,\n int_fast32_t c, int_fast32_t *result)\n{\n\tint_fast32_t tmp;\n\tif (!jas_safe_intfast32_mul(a, b, &tmp) ||\n\t !jas_safe_intfast32_mul(tmp, c, &tmp)) {\n\t\treturn false;\n\t}\n\tif (result) {\n\t\t*result = tmp;\n\t}\n\treturn true;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "inline static bool jas_safe_intfast32_mul(int_fast32_t x, int_fast32_t y,\n int_fast32_t *result)\n{\n\tif (x > 0) {\n\t\t/* x is positive */\n\t\tif (y > 0) {\n\t\t\t/* x and y are positive */\n\t\t\tif (x > INT_FAST32_MAX / y) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\t/* x positive, y nonpositive */\n\t\t\tif (y < INT_FAST32_MIN / x) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t/* x is nonpositive */\n\t\tif (y > 0) {\n\t\t\t/* x is nonpositive, y is positive */\n\t\t\tif (x < INT_FAST32_MIN / y) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else { /* x and y are nonpositive */\n\t\t\tif (x != 0 && y < INT_FAST32_MAX / x) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (result) {\n\t\t*result = x * y;\n\t}\n\treturn true;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "int pnm_validate(jas_stream_t *in)\n{\n\tjas_uchar buf[2];\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= 2);\n\n\t/* Read the first two characters that constitute the signature. */\n\tif ((n = jas_stream_read(in, buf, 2)) < 0) {\n\t\treturn -1;\n\t}\n\t/* Put these characters back to the stream. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\t/* Did we read enough data? */\n\tif (n < 2) {\n\t\treturn -1;\n\t}\n\t/* Is this the correct signature for a PNM file? */\n\tif (buf[0] == 'P' && isdigit(buf[1])) {\n\t\treturn 0;\n\t}\n\treturn -1;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "static unsigned int UTFCharLength(uint8 lead)\n{\n if (lead < 0x80)\n return 1;\n else if ((lead >> 5) == 0x6)\n return 2;\n else if ((lead >> 4) == 0xe)\n return 3;\n else if ((lead >> 3) == 0x1e)\n return 4;\n else\n // Invalid size?\n return 0;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": "compute_U_value_R3(std::string const& user_password,\n\t\t QPDF::EncryptionData const& data)\n{\n // Algorithm 3.5 from the PDF 1.7 Reference Manual\n\n std::string k1 = QPDF::compute_encryption_key(user_password, data);\n MD5 md5;\n md5.encodeDataIncrementally(\n\tpad_or_truncate_password_V4(\"\").c_str(), key_bytes);\n md5.encodeDataIncrementally(data.getId1().c_str(),\n data.getId1().length());\n MD5::Digest digest;\n md5.digest(digest);\n pad_short_parameter(k1, data.getLengthBytes());\n iterate_rc4(digest, sizeof(MD5::Digest),\n\t\tQUtil::unsigned_char_pointer(k1),\n data.getLengthBytes(), 20, false);\n char result[key_bytes];\n memcpy(result, digest, sizeof(MD5::Digest));\n // pad with arbitrary data -- make it consistent for the sake of\n // testing\n for (unsigned int i = sizeof(MD5::Digest); i < key_bytes; ++i)\n {\n\tresult[i] = static_cast((i * i) % 0xff);\n }\n return std::string(result, key_bytes);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "string PacketReader::getLabel(unsigned int recurs)\n{\n string ret;\n size_t wirelength = 0;\n ret.reserve(40);\n getLabelFromContent(d_content, d_pos, ret, recurs++, wirelength);\n return ret;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "safe"} {"code": "bool chopOffDotted(string &domain)\n{\n if(domain.empty() || (domain.size()==1 && domain[0]=='.'))\n return false;\n\n bool escaped = false;\n const string::size_type domainLen = domain.length();\n for (size_t fdot = 0; fdot < domainLen; fdot++)\n {\n if (domain[fdot] == '.' && !escaped) {\n if (fdot==domain.size()-1) {\n domain=\".\";\n }\n else {\n string::size_type remain = domainLen - (fdot + 1);\n char tmp[remain];\n memcpy(tmp, domain.c_str()+fdot+1, remain);\n domain.assign(tmp, remain); // don't dare to do this w/o tmp holder :-)\n }\n return true;\n }\n else if (domain[fdot] == '\\\\' && !escaped) {\n escaped = true;\n }\n else {\n escaped = false;\n }\n }\n\n return false;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-399", "cwe_name": "Resource Management Errors", "description": "Weaknesses in this category are related to improper management of system resources.", "url": "https://cwe.mitre.org/data/definitions/399.html", "label_name": "safe"} {"code": "int my_redel(const char *org_name, const char *tmp_name,\n time_t backup_time_stamp, myf MyFlags)\n{\n int error=1;\n DBUG_ENTER(\"my_redel\");\n DBUG_PRINT(\"my\",(\"org_name: '%s' tmp_name: '%s' MyFlags: %d\",\n\t\t org_name,tmp_name,MyFlags));\n\n if (!my_disable_copystat_in_redel &&\n my_copystat(org_name,tmp_name,MyFlags) < 0)\n goto end;\n if (MyFlags & MY_REDEL_MAKE_BACKUP)\n {\n char name_buff[FN_REFLEN + MY_BACKUP_NAME_EXTRA_LENGTH]; \n my_create_backup_name(name_buff, org_name, backup_time_stamp);\n if (my_rename(org_name, name_buff, MyFlags))\n goto end;\n }\n else if (my_delete(org_name, MyFlags))\n goto end;\n if (my_rename(tmp_name,org_name,MyFlags))\n goto end;\n\n error=0;\nend:\n DBUG_RETURN(error);\n} /* my_redel */", "label": 1, "programming_language": "C++", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "safe"} {"code": "std::wstring GetUniqueTempDirectoryPrefix()\n{\n wchar_t tmpdir[MAX_PATH + 1];\n if (GetTempPath(MAX_PATH + 1, tmpdir) == 0)\n throw Win32Exception(\"Cannot create temporary directory\");\n\n std::wstring dir(tmpdir);\n dir += L\"Update-\";\n return dir;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-426", "cwe_name": "Untrusted Search Path", "description": "The application searches for critical resources using an externally-supplied search path that can point to resources that are not under the application's direct control.", "url": "https://cwe.mitre.org/data/definitions/426.html", "label_name": "safe"} {"code": "DSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,\n const std::string& params,\n const std::string& provider) const\n {\n if(provider == \"base\" || provider.empty())\n return std::unique_ptr(new DSA_Signature_Operation(*this, params, rng));\n throw Provider_Not_Found(algo_name(), provider);\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": "AP4_StszAtom::AP4_StszAtom(AP4_UI32 size, \n AP4_UI08 version,\n AP4_UI32 flags,\n AP4_ByteStream& stream) :\n AP4_Atom(AP4_ATOM_TYPE_STSZ, size, version, flags)\n{\n stream.ReadUI32(m_SampleSize);\n stream.ReadUI32(m_SampleCount);\n if (m_SampleSize == 0) { // means that the samples have different sizes\n // check for overflow\n if (m_SampleCount > (size-8)/4) {\n m_SampleCount = 0;\n return;\n }\n \n // read the entries\n AP4_Cardinal sample_count = m_SampleCount;\n m_Entries.SetItemCount(sample_count);\n unsigned char* buffer = new unsigned char[sample_count*4];\n AP4_Result result = stream.Read(buffer, sample_count*4);\n if (AP4_FAILED(result)) {\n delete[] buffer;\n return;\n }\n for (unsigned int i=0; ifile);\n\n /* We need to do this in order to prevent malicious desktop files\n * with the executable bit already set.\n * See https://bugzilla.gnome.org/show_bug.cgi?id=777991\n */\n nautilus_file_set_metadata (parameters->file, NAUTILUS_METADATA_KEY_DESKTOP_FILE_TRUSTED,\n NULL,\n \"yes\");\n\n nautilus_file_mark_desktop_file_executable (file,\n parameters->parent_window,\n TRUE,\n NULL, NULL);\n\n /* Need to force a reload of the attributes so is_trusted is marked\n * correctly. Not sure why the general monitor doesn't fire in this\n * case when setting the metadata\n */\n nautilus_file_invalidate_all_attributes (parameters->file);\n\n screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));\n uri = nautilus_file_get_uri (parameters->file);\n DEBUG (\"Launching untrusted launcher %s\", uri);\n nautilus_launch_desktop_file (screen, uri, NULL,\n parameters->parent_window);\n g_free (uri);\n g_object_unref (file);\n }\n break;\n\n default:\n {\n /* Just destroy dialog */\n }\n break;\n }\n\n gtk_widget_destroy (GTK_WIDGET (dialog));\n activate_parameters_desktop_free (parameters);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)\n{\n /* we only care about evil server here, so skip TS packets */\n if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {\n return true;\n }\n\n TcpStream *receiver_stream = &ssn->client;\n uint32_t ts_echo = TCP_GET_TSECR(p);\n if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {\n if (receiver_stream->last_ts != 0 && ts_echo != 0 &&\n ts_echo != receiver_stream->last_ts)\n {\n SCLogDebug(\"ssn %p: BAD TSECR echo %u recv %u\", ssn,\n ts_echo, receiver_stream->last_ts);\n return false;\n }\n } else {\n if (receiver_stream->last_ts == 0 && ts_echo != 0) {\n SCLogDebug(\"ssn %p: BAD TSECR echo %u recv %u\", ssn,\n ts_echo, receiver_stream->last_ts);\n return false;\n }\n }\n return true;\n}", "label": 1, "programming_language": "C++", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "void Archive::Seek(int64 Offset,int Method)\n{\n#ifdef USE_QOPEN\n if (QOpen.Seek(Offset,Method))\n return;\n#endif\n#ifdef USE_ARCMEM\n if (ArcMem.Seek(Offset,Method))\n return;\n#endif\n File::Seek(Offset,Method);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "void CommandData::ParseArg(wchar *Arg)\n{\n if (IsSwitch(*Arg) && !NoMoreSwitches)\n if (Arg[1]=='-' && Arg[2]==0)\n NoMoreSwitches=true;\n else\n ProcessSwitch(Arg+1);\n else\n if (*Command==0)\n {\n wcsncpyz(Command,Arg,ASIZE(Command));\n\n\n *Command=toupperw(*Command);\n // 'I' and 'S' commands can contain case sensitive strings after\n // the first character, so we must not modify their case.\n // 'S' can contain SFX name, which case is important in Unix.\n if (*Command!='I' && *Command!='S')\n wcsupper(Command);\n }\n else\n if (*ArcName==0)\n wcsncpyz(ArcName,Arg,ASIZE(ArcName));\n else\n {\n // Check if last character is the path separator.\n size_t Length=wcslen(Arg);\n wchar EndChar=Length==0 ? 0:Arg[Length-1];\n bool EndSeparator=IsDriveDiv(EndChar) || IsPathDiv(EndChar);\n\n wchar CmdChar=toupperw(*Command);\n bool Add=wcschr(L\"AFUM\",CmdChar)!=NULL;\n bool Extract=CmdChar=='X' || CmdChar=='E';\n if (EndSeparator && !Add)\n wcsncpyz(ExtrPath,Arg,ASIZE(ExtrPath));\n else\n if ((Add || CmdChar=='T') && (*Arg!='@' || ListMode==RCLM_REJECT_LISTS))\n FileArgs.AddString(Arg);\n else\n {\n FindData FileData;\n bool Found=FindFile::FastFind(Arg,&FileData);\n if ((!Found || ListMode==RCLM_ACCEPT_LISTS) && \n ListMode!=RCLM_REJECT_LISTS && *Arg=='@' && !IsWildcard(Arg))\n {\n FileLists=true;\n\n ReadTextFile(Arg+1,&FileArgs,false,true,FilelistCharset,true,true,true);\n\n }\n else\n if (Found && FileData.IsDir && Extract && *ExtrPath==0)\n {\n wcsncpyz(ExtrPath,Arg,ASIZE(ExtrPath));\n AddEndSlash(ExtrPath,ASIZE(ExtrPath));\n }\n else\n FileArgs.AddString(Arg);\n }\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": " virtual bool IsOpened() {return hFile!=FILE_BAD_HANDLE;};", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "bool Unpack::ProcessDecoded(UnpackThreadData &D)\n{\n UnpackDecodedItem *Item=D.Decoded,*Border=D.Decoded+D.DecodedSize;\n while (ItemDestUnpSize)\n return false;\n }\n\n if (Item->Type==UNPDT_LITERAL)\n {\n#if defined(LITTLE_ENDIAN) && defined(ALLOW_MISALIGNED)\n if (Item->Length==3 && UnpPtrLiteral;\n UnpPtr+=4;\n }\n else\n#endif\n for (uint I=0;I<=Item->Length;I++)\n Window[UnpPtr++ & MaxWinMask]=Item->Literal[I];\n }\n else\n if (Item->Type==UNPDT_MATCH)\n {\n InsertOldDist(Item->Distance);\n LastLength=Item->Length;\n CopyString(Item->Length,Item->Distance);\n }\n else\n if (Item->Type==UNPDT_REP)\n {\n uint Distance=OldDist[Item->Distance];\n for (uint I=Item->Distance;I>0;I--)\n OldDist[I]=OldDist[I-1];\n OldDist[0]=Distance;\n LastLength=Item->Length;\n CopyString(Item->Length,Distance);\n }\n else\n if (Item->Type==UNPDT_FULLREP)\n {\n if (LastLength!=0)\n CopyString(LastLength,OldDist[0]);\n }\n else\n if (Item->Type==UNPDT_FILTER)\n {\n UnpackFilter Filter;\n \n Filter.Type=(byte)Item->Length;\n Filter.BlockStart=Item->Distance;\n\n Item++;\n\n Filter.Channels=(byte)Item->Length;\n Filter.BlockLength=Item->Distance;\n\n AddFilter(Filter);\n }\n Item++;\n }\n return true;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tif (!sz || sz == UT64_MAX) {\n\t\treturn NULL;\n\t}\n#if 0\n\t/// XXX this breaks tests\n\tif (sz < 8) {\n\t\treturn NULL;\n\t}\n#endif\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR;\n\t\tattr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tattr->size = offset;\n\t\t// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);\n\t}\n\treturn attr;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {\n\tRBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);\n\tif (se) {\n\t\tse->tag = type;\n\t\tif (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {\n\t\t\tse->info.obj_val_cp_idx = (ut16) value;\n\t\t} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {\n\t\t\tse->info.uninit_offset = (ut16) value;\n\t\t}\n\t}\n\treturn se;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-788", "cwe_name": "Access of Memory Location After End of Buffer", "description": "The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer.", "url": "https://cwe.mitre.org/data/definitions/788.html", "label_name": "safe"} {"code": "R_API RBinJavaAttrInfo *r_bin_java_rtv_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 offset = 0;\n\tif (sz < 8) {\n\t\treturn NULL;\n\t}\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR;\n\t\tattr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tattr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);\n\t\tfor (i = 0; i < attr->info.annotation_array.num_annotations; i++) {\n\t\t\tif (offset >= sz) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tRBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\t\tif (annotation) {\n\t\t\t\toffset += annotation->size;\n\t\t\t\tr_list_append (attr->info.annotation_array.annotations, (void *) annotation);\n\t\t\t}\n\t\t}\n\t\tattr->size = offset;\n\t}\n\treturn attr;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-805", "cwe_name": "Buffer Access with Incorrect Length Value", "description": "The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer.", "url": "https://cwe.mitre.org/data/definitions/805.html", "label_name": "safe"} {"code": "R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tRBinJavaElementValuePair *evps = NULL;\n\tut64 offset = 0;\n\tif (sz < 8) {\n\t\treturn NULL;\n\t}\n\tRBinJavaAnnotation *annotation = R_NEW0 (RBinJavaAnnotation);\n\tif (!annotation) {\n\t\treturn NULL;\n\t}\n\t// (ut16) read and set annotation_value.type_idx;\n\tannotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\t// (ut16) read and set annotation_value.num_element_value_pairs;\n\tannotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tannotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);\n\t// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs\n\tfor (i = 0; i < annotation->num_element_value_pairs; i++) {\n\t\tif (offset > sz) {\n\t\t\tbreak;\n\t\t}\n\t\tevps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\tif (evps) {\n\t\t\toffset += evps->size;\n\t\t\tr_list_append (annotation->element_value_pairs, (void *) evps);\n\t\t}\n\t}\n\tannotation->size = offset;\n\treturn annotation;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": "int MSADPCM::decodeBlock(const uint8_t *encoded, int16_t *decoded)\n{\n\tms_adpcm_state decoderState[2];\n\tms_adpcm_state *state[2];\n\n\tint channelCount = m_track->f.channelCount;\n\n\t// Calculate the number of bytes needed for decoded data.\n\tint outputLength = m_framesPerPacket * sizeof (int16_t) * channelCount;\n\n\tstate[0] = &decoderState[0];\n\tif (channelCount == 2)\n\t\tstate[1] = &decoderState[1];\n\telse\n\t\tstate[1] = &decoderState[0];\n\n\t// Initialize block predictor.\n\tfor (int i=0; ipredictorIndex = *encoded++;\n\t\tassert(state[i]->predictorIndex < m_numCoefficients);\n\t}\n\n\t// Initialize delta.\n\tfor (int i=0; idelta = (encoded[1]<<8) | encoded[0];\n\t\tencoded += sizeof (uint16_t);\n\t}\n\n\t// Initialize first two samples.\n\tfor (int i=0; isample1 = (encoded[1]<<8) | encoded[0];\n\t\tencoded += sizeof (uint16_t);\n\t}\n\n\tfor (int i=0; isample2 = (encoded[1]<<8) | encoded[0];\n\t\tencoded += sizeof (uint16_t);\n\t}\n\n\tconst int16_t *coefficient[2] =\n\t{\n\t\tm_coefficients[state[0]->predictorIndex],\n\t\tm_coefficients[state[1]->predictorIndex]\n\t};\n\n\tfor (int i=0; isample2;\n\n\tfor (int i=0; isample1;\n\n\t/*\n\t\tThe first two samples have already been 'decoded' in\n\t\tthe block header.\n\t*/\n\tint samplesRemaining = (m_framesPerPacket - 2) * m_track->f.channelCount;\n\n\twhile (samplesRemaining > 0)\n\t{\n\t\tuint8_t code;\n\t\tint16_t newSample;\n\t\tbool ok;\n\n\t\tcode = *encoded >> 4;\n\t\tnewSample = decodeSample(*state[0], code, coefficient[0], &ok);\n\t\tif (!ok) return 0;\n\t\t*decoded++ = newSample;\n\n\t\tcode = *encoded & 0x0f;\n\t\tnewSample = decodeSample(*state[1], code, coefficient[1], &ok);\n\t\tif (!ok) return 0;\n\t\t*decoded++ = newSample;\n\n\t\tencoded++;\n\t\tsamplesRemaining -= 2;\n\t}\n\n\treturn outputLength;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "namespace{void nop(){}}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-1187", "cwe_name": "DEPRECATED: Use of Uninitialized Resource", "description": "This entry has been deprecated because it was a duplicate of CWE-908. All content has been transferred to CWE-908.", "url": "https://cwe.mitre.org/data/definitions/1187.html", "label_name": "safe"} {"code": "static int lookup1_values(int entries, int dim)\n{\n int r = (int) floor(exp((float) log((float) entries) / dim));\n if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;\n ++r; // floor() to avoid _ftol() when non-CRT\n if (pow((float) r+1, dim) <= entries)\n return -1;\n if ((int) floor(pow((float) r, dim)) > entries)\n return -1;\n return r;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "static int lookup1_values(int entries, int dim)\n{\n int r = (int) floor(exp((float) log((float) entries) / dim));\n if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;\n ++r; // floor() to avoid _ftol() when non-CRT\n if (pow((float) r+1, dim) <= entries)\n return -1;\n if ((int) floor(pow((float) r, dim)) > entries)\n return -1;\n return r;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "static int lookup1_values(int entries, int dim)\n{\n int r = (int) floor(exp((float) log((float) entries) / dim));\n if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;\n ++r; // floor() to avoid _ftol() when non-CRT\n if (pow((float) r+1, dim) <= entries)\n return -1;\n if ((int) floor(pow((float) r, dim)) > entries)\n return -1;\n return r;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)\n{\n int prev,i,j;\n // we use right&left (the start of the right- and left-window sin()-regions)\n // to determine how much to return, rather than inferring from the rules\n // (same result, clearer code); 'left' indicates where our sin() window\n // starts, therefore where the previous window's right edge starts, and\n // therefore where to start mixing from the previous buffer. 'right'\n // indicates where our sin() ending-window starts, therefore that's where\n // we start saving, and where our returned-data ends.\n\n // mixin from previous window\n if (f->previous_length) {\n int i,j, n = f->previous_length;\n float *w = get_window(f, n);\n if (w == NULL) return 0;\n for (i=0; i < f->channels; ++i) {\n for (j=0; j < n; ++j)\n f->channel_buffers[i][left+j] =\n f->channel_buffers[i][left+j]*w[ j] +\n f->previous_window[i][ j]*w[n-1-j];\n }\n }\n\n prev = f->previous_length;\n\n // last half of this data becomes previous window\n f->previous_length = len - right;\n\n // @OPTIMIZE: could avoid this copy by double-buffering the\n // output (flipping previous_window with channel_buffers), but\n // then previous_window would have to be 2x as large, and\n // channel_buffers couldn't be temp mem (although they're NOT\n // currently temp mem, they could be (unless we want to level\n // performance by spreading out the computation))\n for (i=0; i < f->channels; ++i)\n for (j=0; right+j < len; ++j)\n f->previous_window[i][j] = f->channel_buffers[i][right+j];\n\n if (!prev)\n // there was no previous packet, so this data isn't valid...\n // this isn't entirely true, only the would-have-overlapped data\n // isn't valid, but this seems to be what the spec requires\n return 0;\n\n // truncate a short frame\n if (len < right) right = len;\n\n f->samples_output += right-left;\n\n return right - left;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)\n{\n int dy = y1 - y0;\n int adx = x1 - x0;\n int ady = abs(dy);\n int base;\n int x=x0,y=y0;\n int err = 0;\n int sy;\n\n#ifdef STB_VORBIS_DIVIDE_TABLE\n if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {\n if (dy < 0) {\n base = -integer_divide_table[ady][adx];\n sy = base-1;\n } else {\n base = integer_divide_table[ady][adx];\n sy = base+1;\n }\n } else {\n base = dy / adx;\n if (dy < 0)\n sy = base - 1;\n else\n sy = base+1;\n }\n#else\n base = dy / adx;\n if (dy < 0)\n sy = base - 1;\n else\n sy = base+1;\n#endif\n ady -= abs(base) * adx;\n if (x1 > n) x1 = n;\n if (x < x1) {\n LINE_OP(output[x], inverse_db_table[y&255]);\n for (++x; x < x1; ++x) {\n err += ady;\n if (err >= adx) {\n err -= adx;\n y += sy;\n } else\n y += base;\n LINE_OP(output[x], inverse_db_table[y&255]);\n }\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-617", "cwe_name": "Reachable Assertion", "description": "The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.", "url": "https://cwe.mitre.org/data/definitions/617.html", "label_name": "safe"} {"code": "bool __fastcall TSiteRawDialog::Execute(TSessionData * Data)\r\n{\r\n std::unique_ptr FactoryDefaults(new TSessionData(L\"\"));\r\n std::unique_ptr RawData(new TSessionData(L\"\"));\r\n RawData->Assign(Data);\r\n // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that\r\n if (RawData->FSProtocol != fsSFTPonly)\r\n {\r\n RawData->FSProtocol = FactoryDefaults->FSProtocol;\r\n }\r\n RawData->HostName = FactoryDefaults->HostName;\r\n RawData->PortNumber = FactoryDefaults->PortNumber;\r\n RawData->UserName = FactoryDefaults->UserName;\r\n RawData->Password = FactoryDefaults->Password;\r\n RawData->Ftps = FactoryDefaults->Ftps;\r\n\r\n std::unique_ptr Options(RawData->SaveToOptions(FactoryDefaults.get(), false, false));\r\n\r\n SettingsMemo->Lines = Options.get();\r\n\r\n bool Result = TCustomDialog::Execute();\r\n if (Result)\r\n {\r\n std::unique_ptr BackupData(new TSessionData(L\"\"));\r\n BackupData->Assign(Data);\r\n Data->DefaultSettings();\r\n\r\n Data->FSProtocol = BackupData->FSProtocol;\r\n Data->HostName = BackupData->HostName;\r\n Data->PortNumber = BackupData->PortNumber;\r\n Data->UserName = BackupData->UserName;\r\n Data->Password = BackupData->Password;\r\n Data->Ftps = BackupData->Ftps;\r\n\r\n Data->ApplyRawSettings(SettingsMemo->Lines, false);\r\n }\r\n return Result;\r\n}\r", "label": 1, "programming_language": "C++", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "safe"} {"code": "void ecall_non_oblivious_sort_merge_join(uint8_t *join_expr, size_t join_expr_length,\n uint8_t *input_rows, size_t input_rows_length,\n uint8_t *join_row, size_t join_row_length,\n uint8_t **output_rows, size_t *output_rows_length) {\n // Guard against operating on arbitrary enclave memory\n assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1);\n assert(sgx_is_outside_enclave(join_row, join_row_length) == 1);\n sgx_lfence();\n\n try {\n non_oblivious_sort_merge_join(join_expr, join_expr_length,\n input_rows, input_rows_length,\n join_row, join_row_length,\n output_rows, output_rows_length);\n } catch (const std::runtime_error &e) {\n ocall_throw(e.what());\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "void UncompressElementOp::Compute(OpKernelContext* ctx) {\n Tensor tensor = ctx->input(0);\n const Variant& variant = tensor.scalar()();\n const CompressedElement* compressed = variant.get();\n OP_REQUIRES(\n ctx, compressed != nullptr,\n errors::InvalidArgument(\n \"Input does not contain a compressed element. Instead got tensor \",\n tensor.DebugString()));\n\n std::vector components;\n OP_REQUIRES_OK(ctx, UncompressElement(*compressed, &components));\n OP_REQUIRES(ctx, components.size() == output_types_.size(),\n errors::FailedPrecondition(\"Expected \", output_types_.size(),\n \" outputs from uncompress, but got \",\n components.size()));\n for (int i = 0; i < components.size(); ++i) {\n OP_REQUIRES(\n ctx, components[i].dtype() == output_types_[i],\n errors::FailedPrecondition(\"Expected a tensor of type \",\n DataTypeString(output_types_[i]),\n \" but got a tensor of type \",\n DataTypeString(components[i].dtype())));\n ctx->set_output(i, components[i]);\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "bool L2NormalizeReduceAxis(Value sq_op, DenseElementsAttr axis) {\n if (axis.getNumElements() == 0) {\n return false;\n }\n if (sq_op.getType().cast().getRank() - 1 ==\n *axis.getValues().begin() ||\n *axis.getValues().begin() == -1) {\n return true;\n }\n if (sq_op.getType().cast().getRank() != axis.getNumElements()) {\n return false;\n }\n auto shape = sq_op.getType().cast();\n SmallVector elems{axis.getValues().begin(),\n axis.getValues().end()};\n for (int i = 0; i < shape.getRank(); ++i) {\n if (i != elems[i]) return false;\n }\n return true;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": " Status check_index_ordering(const Tensor& indices) {\n if (indices.NumElements() == 0) {\n return errors::InvalidArgument(\"Indices are empty\");\n }\n\n auto findices = indices.flat();\n\n for (std::size_t i = 0; i < findices.dimension(0) - 1; ++i) {\n if (findices(i) < findices(i + 1)) {\n continue;\n }\n\n return errors::InvalidArgument(\"Indices are not strictly ordered\");\n }\n\n return Status::OK();\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-824", "cwe_name": "Access of Uninitialized Pointer", "description": "The program accesses or uses a pointer that has not been initialized.", "url": "https://cwe.mitre.org/data/definitions/824.html", "label_name": "safe"} {"code": "Status TensorSliceReader::GetTensor(\n const string& name, std::unique_ptr* out_tensor) const {\n DataType type;\n TensorShape shape;\n TensorSlice slice;\n {\n mutex_lock l(mu_);\n const TensorSliceSet* tss = gtl::FindPtrOrNull(tensors_, name);\n if (tss == nullptr) {\n return errors::NotFound(name, \" not found in checkpoint file\");\n }\n\n if (tss->Slices().size() > 1) {\n // TODO(sherrym): Support multi-slice checkpoints.\n return errors::Unimplemented(\"Sliced checkpoints are not supported\");\n }\n\n type = tss->type();\n shape = tss->shape();\n slice = tss->Slices().begin()->second.slice;\n }\n\n std::unique_ptr t(new tensorflow::Tensor);\n Status s = tensorflow::Tensor::BuildTensor(type, shape, t.get());\n if (!s.ok()) return s;\n bool success = false;\n\n#define READER_COPY(dt) \\\n case dt: \\\n success = CopySliceData(name, slice, \\\n t->flat::Type>().data()); \\\n break;\n\n switch (type) {\n READER_COPY(DT_FLOAT);\n READER_COPY(DT_DOUBLE);\n READER_COPY(DT_INT32);\n READER_COPY(DT_UINT8);\n READER_COPY(DT_INT16);\n READER_COPY(DT_INT8);\n READER_COPY(DT_INT64);\n READER_COPY(DT_STRING);\n default:\n return errors::Unimplemented(\"Data type not supported\");\n }\n#undef READER_COPY\n\n if (!success) {\n return errors::NotFound(name, \" not found in checkpoint file\");\n }\n std::swap(*out_tensor, t);\n\n return Status::OK();\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-345", "cwe_name": "Insufficient Verification of Data Authenticity", "description": "The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.", "url": "https://cwe.mitre.org/data/definitions/345.html", "label_name": "safe"} {"code": "TEST(CudnnRNNOpsTest, ForwardV3Gru) {\n int max_seq_length = 2;\n int batch_size = 3;\n int num_units = 4;\n int num_layers = 5;\n int dir_count = 1;\n std::vector input_shape = {max_seq_length, batch_size, num_units};\n std::vector input_h_shape = {num_layers * dir_count, batch_size,\n num_units};\n std::vector input_c_shape = {num_layers * dir_count, batch_size,\n num_units};\n std::vector output_shape = {max_seq_length, batch_size,\n num_units * dir_count};\n std::vector seq_lengths_shape = {batch_size};\n auto shape_to_str = [](const std::vector& v) {\n return strings::StrCat(\"[\", absl::StrJoin(v, \",\"), \"]\");\n };\n string input_shapes_desc = strings::StrCat(\n shape_to_str(input_shape), \";\", shape_to_str(input_h_shape), \";\",\n shape_to_str(input_c_shape), \";\", \"[?]\", \";\",\n shape_to_str(seq_lengths_shape));\n string output_shapes_desc = \"[d0_0,d0_1,d1_2];in1;[];?;?\";\n\n ShapeInferenceTestOp op(\"CudnnRNNV3\");\n TF_ASSERT_OK(NodeDefBuilder(\"test\", \"CudnnRNNV3\")\n .Input({\"input\", 0, DT_FLOAT})\n .Input({\"input_h\", 0, DT_FLOAT})\n .Input({\"input_c\", 0, DT_FLOAT})\n .Input({\"params\", 0, DT_FLOAT})\n .Input({\"sequence_lengths\", 0, DT_INT32})\n .Attr(\"rnn_mode\", \"gru\")\n .Attr(\"input_mode\", \"auto_select\")\n .Attr(\"direction\", \"unidirectional\")\n .Finalize(&op.node_def));\n INFER_OK(op, input_shapes_desc, output_shapes_desc);\n INFER_ERROR(\"Shape must be rank 3 \", op, \"[];[?,?,?];[];[?];[?]\");\n INFER_ERROR(\"Shape must be rank 3 \", op, \"[?,?,?];[];[];[?];[?]\");\n INFER_ERROR(\"Shape must be rank 1 \", op, \"[?,?,?];[?,?,?];[];[];[?]\");\n INFER_ERROR(\"Shape must be rank 1 \", op, \"[?,?,?];[?,?,?];[];[?];[]\");\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "void ImmutableConstantOp::Compute(OpKernelContext* ctx) {\n std::unique_ptr allocator(\n new MemmappedTensorAllocator());\n\n OP_REQUIRES_OK(ctx,\n allocator->InitializeFromRegion(region_name_, ctx->env()));\n OP_REQUIRES(ctx, dtype_ != DT_STRING,\n errors::Unimplemented(\"Sorry, DT_STRING is not currently \"\n \"supported for ImmutableConstOp.\"));\n ctx->set_output(0, Tensor(allocator.get(), dtype_, shape_));\n OP_REQUIRES_OK(ctx, allocator->allocation_status());\n // Allocator is owned by the tensor from this point.\n allocator.release()->set_delete_on_deallocate();\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "StatusOr SpecializeType(const AttrSlice& attrs,\n const OpDef& op_def) {\n FullTypeDef ft;\n ft.set_type_id(TFT_PRODUCT);\n\n for (int i = 0; i < op_def.output_arg_size(); i++) {\n auto* t = ft.add_args();\n\n *t = op_def.output_arg(i).experimental_full_type();\n\n // Resolve dependent types. The convention for op registrations is to use\n // attributes as type variables.\n // See https://www.tensorflow.org/guide/create_op#type_polymorphism.\n // Once the op signature can be defined entirely in FullType, this\n // convention can be deprecated.\n //\n // Note: While this code performs some basic verifications, it generally\n // assumes consistent op defs and attributes. If more complete\n // verifications are needed, they should be done by separately, and in a\n // way that can be reused for type inference.\n for (int j = 0; j < t->args_size(); j++) {\n auto* arg = t->mutable_args(i);\n if (arg->type_id() == TFT_VAR) {\n const auto* attr = attrs.Find(arg->s());\n if (attr == nullptr) {\n return Status(\n error::INVALID_ARGUMENT,\n absl::StrCat(\"Could not find an attribute for key \", arg->s()));\n }\n if (attr->value_case() == AttrValue::kList) {\n const auto& attr_list = attr->list();\n arg->set_type_id(TFT_PRODUCT);\n for (int i = 0; i < attr_list.type_size(); i++) {\n map_dtype_to_tensor(attr_list.type(i), arg->add_args());\n }\n\n } else if (attr->value_case() == AttrValue::kType) {\n map_dtype_to_tensor(attr->type(), arg);\n\n } else {\n return Status(error::UNIMPLEMENTED,\n absl::StrCat(\"unknown attribute type\",\n attrs.DebugString(), \" key=\", arg->s()));\n }\n\n arg->clear_s();\n }\n }\n }\n\n return ft;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "TEST_F(OpLevelCostEstimatorTest, OpDimensionsFromInputsError) {\n std::vector paddings = {\"VALID\", \"SAME\"};\n std::vector formats = {\"NHWC\", \"NCHW\"};\n for (const auto& p : paddings) {\n for (const auto& f : formats) {\n // n, h, w, c, kx, ky, sx, sy, data_format, padding.\n ASSERT_THAT(\n CallOpDimensionsFromInputs(10, 14, 14, 3840, 3, 3, 0, 2, f, p),\n testing::StatusIs(\n error::INVALID_ARGUMENT,\n \"Stride must be > 0 for Height and Width, but got (2, 0)\"));\n ASSERT_THAT(\n CallOpDimensionsFromInputs(10, 14, 14, 3840, 3, 3, 2, 0, f, p),\n testing::StatusIs(\n error::INVALID_ARGUMENT,\n \"Stride must be > 0 for Height and Width, but got (0, 2)\"));\n }\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-369", "cwe_name": "Divide By Zero", "description": "The product divides a value by zero.", "url": "https://cwe.mitre.org/data/definitions/369.html", "label_name": "safe"} {"code": "TEST_F(QuantizedConv2DTest, OddPadding) {\n const int stride = 2;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 4;\n const int image_batch_count = 1;\n AddInputFromArray(\n TensorShape({image_batch_count, image_height, image_width, depth}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});\n const int filter_size = 3;\n const int filter_count = 1;\n AddInputFromArray(\n TensorShape({filter_size, filter_size, depth, filter_count}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9});\n AddInputFromArray(TensorShape({}), {0});\n AddInputFromArray(TensorShape({}), {255.0f});\n AddInputFromArray(TensorShape({}), {0});\n AddInputFromArray(TensorShape({}), {255.0f});\n\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width / stride;\n const int expected_height = (image_height * filter_count) / stride;\n Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,\n expected_width, filter_count}));\n test::FillValues(&expected, {348, 252, 274, 175});\n test::ExpectTensorEqual(expected, *GetOutput(0));\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "TEST_F(QuantizedConv2DTest, Small32Bit) {\n const int stride = 1;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 3;\n const int image_batch_count = 1;\n AddInputFromArray(\n TensorShape({image_batch_count, image_height, image_width, depth}),\n {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120});\n const int filter_size = 3;\n const int filter_count = 1;\n AddInputFromArray(\n TensorShape({filter_size, filter_size, depth, filter_count}),\n {10, 40, 70, 20, 50, 80, 30, 60, 90});\n AddInputFromArray(TensorShape({}), {0});\n AddInputFromArray(TensorShape({}), {255.0f});\n AddInputFromArray(TensorShape({}), {0});\n AddInputFromArray(TensorShape({}), {255.0f});\n\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width;\n const int expected_height = image_height * filter_count;\n Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,\n expected_width, filter_count}));\n test::FillValues(\n &expected, {10500, 15000, 18300, 9500, 23500, 31200, 35700, 17800, 18700,\n 23400, 26100, 12100});\n test::ExpectTensorEqual(expected, *GetOutput(0));\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "Status GetDeviceForInput(const EagerOperation& op, const EagerContext& ctx,\n TensorHandle* tensor_handle, Device** result) {\n Device* cpu_device = ctx.HostCPU();\n string device_name;\n if (tensor_handle->Type() != TensorHandle::LOCAL) {\n Device* device = tensor_handle->device();\n device_name = device != nullptr ? device->name() : cpu_device->name();\n *result = (device == nullptr ? cpu_device : device);\n } else if (tensor_handle->dtype == DT_RESOURCE) {\n // Use the resource's actual device because it is the device that will\n // influence partitioning the multi-device function.\n const Tensor* tensor;\n // TODO(fishx): Avoid blocking here.\n TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor));\n if (tensor->NumElements() == 0) {\n return errors::InvalidArgument(\"Empty resource handle\");\n }\n const ResourceHandle& handle = tensor->flat()(0);\n device_name = handle.device();\n\n Device* input_device;\n TF_RETURN_IF_ERROR(\n ctx.FindDeviceFromName(device_name.c_str(), &input_device));\n *result = input_device;\n } else {\n Device* device = tensor_handle->device();\n const bool is_tpu = device != nullptr && device->device_type() == \"TPU\";\n // int32 return values can be placed on TPUs.\n const bool use_host_memory =\n is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype)\n : MTypeFromDType(tensor_handle->dtype);\n if (use_host_memory) {\n *result = cpu_device;\n } else {\n // Eager ops executing as functions should have their preferred inputs set\n // to the op's device. This allows us to avoid expensive D2H copies if a\n // mirror of the tensor already exists on the op's device.\n if (!op.is_function() && device != nullptr && device != cpu_device) {\n device = absl::get(op.Device());\n }\n *result = (device == nullptr ? cpu_device : device);\n }\n }\n return Status::OK();\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-475", "cwe_name": "Undefined Behavior for Input to API", "description": "The behavior of this function is undefined unless its control parameter is set to a specific value.", "url": "https://cwe.mitre.org/data/definitions/475.html", "label_name": "safe"} {"code": "TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotConsecutive) {\n SegmentSumOpModel model({TensorType_INT32, {3, 2}},\n {TensorType_INT32, {3}});\n model.PopulateTensor(model.data(), {1, 2, 3, 4, 5, 6});\n model.PopulateTensor(model.segment_ids(), {0, 3, 5});\n ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": " static TfLiteRegistration DelegateRegistration() {\n TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};\n\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n // If tensors are resized, the runtime should propagate shapes\n // automatically if correct flag is set. Ensure values are correct.\n // Output 0 should be dynamic.\n TfLiteTensor* output0;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output0));\n TF_LITE_ENSURE(context, IsDynamicTensor(output0));\n // Output 1 has the same shape as input.\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n TfLiteTensor* output1;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 1, &output1));\n TF_LITE_ENSURE(context, input->dims->size == output1->dims->size);\n TF_LITE_ENSURE(context, input->dims->data[0] == output1->dims->data[0]);\n return kTfLiteOk;\n };\n\n return reg;\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " static TfLiteRegistration DynamicCopyOpRegistration() {\n TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};\n\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n // Output 0 is dynamic\n TfLiteTensor* output0;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output0));\n SetTensorToDynamic(output0);\n // Output 1 has the same shape as input.\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n TfLiteTensor* output1;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 1, &output1));\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(\n context, output1, TfLiteIntArrayCopy(input->dims)));\n return kTfLiteOk;\n };\n\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n // Not implemented since this isn't required in testing.\n return kTfLiteOk;\n };\n return reg;\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "bool IsFullyConnectedOpSupported(const TfLiteRegistration* registration,\n const TfLiteNode* node,\n TfLiteContext* context) {\n if (node->builtin_data == nullptr) return false;\n const auto* fc_params =\n reinterpret_cast(node->builtin_data);\n const int kInput = 0;\n const int kWeights = 1;\n const int kBias = 2;\n\n if (fc_params->weights_format != kTfLiteFullyConnectedWeightsFormatDefault) {\n return false;\n }\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInput, &input));\n const TfLiteTensor* weights;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kWeights, &weights));\n\n if (!IsFloatType(input->type)) {\n return false;\n }\n if (!IsFloatType(weights->type) || !IsConstantTensor(weights)) {\n return false;\n }\n // Core ML 2 only supports single-batch fully connected layer, thus dimensions\n // except the last one should be 1.\n if (input->dims->data[input->dims->size - 1] != NumElements(input)) {\n return false;\n }\n\n if (node->inputs->size > 2) {\n const TfLiteTensor* bias;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBias, &bias));\n if (!IsFloatType(bias->type) || !IsConstantTensor(bias)) {\n return false;\n }\n }\n\n TfLiteFusedActivation activation = fc_params->activation;\n if (activation == kTfLiteActSignBit) {\n return false;\n }\n return true;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": " TfLiteRegistration CancelOpRegistration() {\n TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};\n\n // Set output size to the input size in CancelOp::Prepare(). Code exists to\n // have a framework in Prepare. The input and output tensors are not used.\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* in_tensor;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &in_tensor));\n TfLiteTensor* out_tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &out_tensor));\n TfLiteIntArray* new_size = TfLiteIntArrayCopy(in_tensor->dims);\n return context->ResizeTensor(context, out_tensor, new_size);\n };\n\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n cancellation_data_.is_cancelled = true;\n return kTfLiteOk;\n };\n return reg;\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus PrepareHashtable(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 0);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n TF_LITE_ENSURE(context, node->user_data != nullptr);\n const auto* params =\n reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE(context, !params->table_name.empty());\n TF_LITE_ENSURE(context, (params->key_dtype == kTfLiteInt64 &&\n params->value_dtype == kTfLiteString) ||\n (params->key_dtype == kTfLiteString &&\n params->value_dtype == kTfLiteInt64));\n\n TfLiteTensor* resource_handle_tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kResourceHandleTensor,\n &resource_handle_tensor));\n TF_LITE_ENSURE_EQ(context, resource_handle_tensor->type, kTfLiteInt32);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);\n outputSize->data[0] = 1;\n return context->ResizeTensor(context, resource_handle_tensor, outputSize);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus PrepareHashtableFind(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input_resource_id_tensor;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputResourceIdTensor,\n &input_resource_id_tensor));\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1);\n\n const TfLiteTensor* default_value_tensor;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDefaultValueTensor,\n &default_value_tensor));\n\n const TfLiteTensor* key_tensor;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kKeyTensor, &key_tensor));\n TfLiteTensor* output_tensor;\n TF_LITE_ENSURE_OK(\n context, GetOutputSafe(context, node, kOutputTensor, &output_tensor));\n TF_LITE_ENSURE_EQ(context, default_value_tensor->type, output_tensor->type);\n TF_LITE_ENSURE(context, (key_tensor->type == kTfLiteInt64 &&\n output_tensor->type == kTfLiteString) ||\n (key_tensor->type == kTfLiteString &&\n output_tensor->type == kTfLiteInt64));\n return context->ResizeTensor(context, output_tensor,\n TfLiteIntArrayCopy(key_tensor->dims));\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus GetInputSafe(const TfLiteContext* context, const TfLiteNode* node,\n int index, const TfLiteTensor** tensor) {\n return GetMutableInputSafe(context, node, index, tensor);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "inline TfLiteStatus GetMutableInputSafe(const TfLiteContext* context,\n const TfLiteNode* node, int index,\n const TfLiteTensor** tensor) {\n int tensor_index;\n TF_LITE_ENSURE_OK(\n context, ValidateTensorIndexingSafe(context, index, node->inputs->size,\n node->inputs->data, &tensor_index));\n *tensor = GetTensorAtIndex(context, tensor_index);\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "inline TfLiteTensor* GetMutableInput(const TfLiteContext* context,\n const TfLiteNode* node, int index) {\n const int tensor_index = ValidateTensorIndexing(\n context, index, node->inputs->size, node->inputs->data);\n if (tensor_index < 0) {\n return nullptr;\n }\n return GetTensorAtIndex(context, tensor_index);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus SimpleOpEval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input1;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, /*index=*/0, &input1));\n const TfLiteTensor* input2;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, /*index=*/1, &input2));\n\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, /*index=*/0, &output));\n\n int32_t* output_data = output->data.i32;\n *output_data = *(input1->data.i32) + *(input2->data.i32);\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus MockCustom::Invoke(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n const int32_t* input_data = input->data.i32;\n const TfLiteTensor* weight;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &weight));\n const uint8_t* weight_data = weight->data.uint8;\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n int32_t* output_data = output->data.i32;\n output_data[0] =\n 0; // Catch output tensor sharing memory with an input tensor\n output_data[0] = input_data[0] + weight_data[0];\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus PrepareSimple(TfLiteContext* context, TfLiteNode* node) {\n // Inputs Tensor (dtype depends on quantization):\n // [0] = Input\n // [1] = Axis\n const TfLiteTensor* input = GetInput(context, node, 0);\n\n // Outputs Tensor (dtype depends on quantization):\n // [0] = Output\n\n // Validate number of inputs and outputs\n TF_LITE_ENSURE_EQ(context, node->inputs->size, 2);\n TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);\n\n // Validate axis type\n const TfLiteTensor* axis = GetInput(context, node, 1);\n TF_LITE_ENSURE(context, axis != nullptr);\n TF_LITE_ENSURE_TYPES_EQ(context, axis->type, kTfLiteInt32);\n\n if (input->type == kTfLiteInt8) {\n OpData* data = static_cast(node->user_data);\n const TfLiteTensor* output = GetOutput(context, node, 0);\n const double real_multiplier = static_cast(input->params.scale) /\n static_cast(output->params.scale);\n QuantizeMultiplier(real_multiplier, &data->multiplier, &data->shift);\n }\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus SoftmaxPrepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params = static_cast(node->builtin_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TF_LITE_ENSURE(context, input != nullptr);\n TF_LITE_ENSURE(context, NumDimensions(input) >= 1);\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE(context, output != nullptr);\n\n TFLITE_DCHECK(node->user_data != nullptr);\n SoftmaxParams* data = static_cast(node->user_data);\n return CalculateSoftmaxParams(context, input, output, params, data);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* axis = GetInput(context, node, 0);\n TF_LITE_ENSURE(context, axis != nullptr);\n\n // Dynamic output tensors are needed if axis tensor is not constant.\n // But Micro doesn't support dynamic memory allocation, so we only support\n // constant axis tensor for now.\n TF_LITE_ENSURE_MSG(context, IsConstantTensor(axis),\n \"Non constant axis tensor not supported\");\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus CalculateArithmeticOpData(TfLiteContext* context, TfLiteNode* node,\n OpData* data) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TF_LITE_ENSURE(context, input != nullptr);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n TF_LITE_ENSURE(context, output != nullptr);\n\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {\n static constexpr int kInputIntegerBits = 4;\n const double input_real_multiplier =\n static_cast(input->params.scale) *\n static_cast(1 << (31 - kInputIntegerBits));\n\n const double q = std::frexp(input_real_multiplier, &data->input_left_shift);\n data->input_multiplier = static_cast(TfLiteRound(q * (1ll << 31)));\n\n data->input_range_radius =\n CalculateInputRadius(kInputIntegerBits, data->input_left_shift, 31);\n }\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus ReluPrepare(TfLiteContext* context, TfLiteNode* node) {\n ReluOpData* data = reinterpret_cast(node->user_data);\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n if (input->type == kTfLiteInt8 || input->type == kTfLiteUInt8) {\n double real_multiplier = input->params.scale / output->params.scale;\n QuantizeMultiplier(real_multiplier, &data->output_multiplier,\n &data->output_shift);\n }\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n const TfLiteTensor* input1;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor1, &input1));\n const TfLiteTensor* input2;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor2, &input2));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) {\n EvalAdd(context, node, params, data, input1, input2, output);\n } else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_OK(context,\n EvalAddQuantized(context, node, params, data,\n input1, input2, output));\n } else {\n TF_LITE_UNSUPPORTED_TYPE(context, output->type, \"Add\");\n }\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n // TODO(b/137042749): TFLite infrastructure (converter, delegate) doesn't\n // fully support 0-output ops yet. Currently it works if we manually crfat\n // a TFLite graph that contains variable ops. Note:\n // * The TFLite Converter need to be changed to be able to produce an op\n // with 0 output.\n // * The delegation code need to be changed to handle 0 output ops. However\n // everything still works fine when variable ops aren't used.\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0);\n\n const TfLiteTensor* input_resource_id_tensor;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputVariableId,\n &input_resource_id_tensor));\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n Subgraph* subgraph = reinterpret_cast(context->impl_);\n\n const TfLiteTensor* input_resource_id_tensor;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputVariableId,\n &input_resource_id_tensor));\n const TfLiteTensor* input_value_tensor;\n TF_LITE_ENSURE_OK(\n context, GetInputSafe(context, node, kInputValue, &input_value_tensor));\n\n int resource_id = input_resource_id_tensor->data.i32[0];\n auto& resources = subgraph->resources();\n resource::CreateResourceVariableIfNotAvailable(&resources, resource_id);\n auto* variable = resource::GetResourceVariable(&resources, resource_id);\n TF_LITE_ENSURE(context, variable != nullptr);\n variable->AssignFrom(input_value_tensor);\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus NotEqualEval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input1;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor1, &input1));\n const TfLiteTensor* input2;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor2, &input2));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n bool requires_broadcast = !HaveSameShapes(input1, input2);\n switch (input1->type) {\n case kTfLiteBool:\n Comparison(input1, input2, output,\n requires_broadcast);\n break;\n case kTfLiteFloat32:\n Comparison(input1, input2, output,\n requires_broadcast);\n break;\n case kTfLiteInt32:\n Comparison(input1, input2, output,\n requires_broadcast);\n break;\n case kTfLiteInt64:\n Comparison(input1, input2, output,\n requires_broadcast);\n break;\n case kTfLiteUInt8:\n ComparisonQuantized(\n input1, input2, output, requires_broadcast);\n break;\n case kTfLiteInt8:\n ComparisonQuantized(\n input1, input2, output, requires_broadcast);\n break;\n case kTfLiteString:\n ComparisonString(reference_ops::StringRefNotEqualFn, input1, input2,\n output, requires_broadcast);\n break;\n default:\n context->ReportError(\n context,\n \"Does not support type %d, requires bool|float|int|uint8|string\",\n input1->type);\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* lookup;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &lookup));\n const TfLiteTensor* value;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &value));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n switch (value->type) {\n case kTfLiteFloat32:\n return EvalSimple(context, node, lookup, value, output);\n case kTfLiteUInt8:\n case kTfLiteInt8:\n if (output->type == kTfLiteFloat32) {\n return EvalHybrid(context, node, lookup, value, output);\n } else {\n return EvalSimple(context, node, lookup, value, output);\n }\n default:\n context->ReportError(context, \"Type not currently supported.\");\n return kTfLiteError;\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 5);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* ids;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &ids));\n TF_LITE_ENSURE_EQ(context, NumDimensions(ids), 1);\n TF_LITE_ENSURE_EQ(context, ids->type, kTfLiteInt32);\n\n const TfLiteTensor* indices;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &indices));\n TF_LITE_ENSURE_EQ(context, NumDimensions(indices), 2);\n TF_LITE_ENSURE_EQ(context, indices->type, kTfLiteInt32);\n\n const TfLiteTensor* shape;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &shape));\n TF_LITE_ENSURE_EQ(context, NumDimensions(shape), 1);\n TF_LITE_ENSURE_EQ(context, shape->type, kTfLiteInt32);\n\n const TfLiteTensor* weights;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 3, &weights));\n TF_LITE_ENSURE_EQ(context, NumDimensions(weights), 1);\n TF_LITE_ENSURE_EQ(context, weights->type, kTfLiteFloat32);\n\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(indices, 0),\n SizeOfDimension(ids, 0));\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(indices, 0),\n SizeOfDimension(weights, 0));\n\n const TfLiteTensor* value;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 4, &value));\n TF_LITE_ENSURE(context, NumDimensions(value) >= 2);\n\n // Mark the output as a dynamic tensor.\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);\n output->allocation_type = kTfLiteDynamic;\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n // Just copy input to output.\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInput, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n const TfLiteTensor* axis;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxis, &axis));\n if (IsDynamicTensor(output)) {\n int axis_value;\n TF_LITE_ENSURE_OK(context,\n GetAxisValueFromTensor(context, *axis, &axis_value));\n TF_LITE_ENSURE_OK(context,\n ExpandTensorDim(context, *input, axis_value, output));\n }\n if (output->type == kTfLiteString) {\n TfLiteTensorRealloc(input->bytes, output);\n }\n memcpy(output->data.raw, input->data.raw, input->bytes);\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInput, &input));\n const TfLiteTensor* axis;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxis, &axis));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n output->type = input->type;\n if (IsConstantTensor(axis)) {\n int axis_value;\n TF_LITE_ENSURE_OK(context,\n GetAxisValueFromTensor(context, *axis, &axis_value));\n return ExpandTensorDim(context, *input, axis_value, output);\n }\n SetTensorToDynamic(output);\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInput, &input));\n const TfLiteTensor* axis;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxis, &axis));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n output->type = input->type;\n if (IsConstantTensor(axis)) {\n int axis_value;\n TF_LITE_ENSURE_OK(context,\n GetAxisValueFromTensor(context, *axis, &axis_value));\n return ExpandTensorDim(context, *input, axis_value, output);\n }\n SetTensorToDynamic(output);\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);\n output->type = input->type;\n TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);\n return context->ResizeTensor(context, output, output_size);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n OpData* data = reinterpret_cast(node->user_data);\n\n const TfLiteTensor* input1;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor1, &input1));\n const TfLiteTensor* input2;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor2, &input2));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n switch (input1->type) {\n case kTfLiteInt32: {\n return EvalImpl(context, data->requires_broadcast, input1,\n input2, output);\n }\n case kTfLiteInt64: {\n return EvalImpl(context, data->requires_broadcast, input1,\n input2, output);\n }\n case kTfLiteFloat32: {\n return EvalImpl(context, data->requires_broadcast, input1, input2,\n output);\n }\n default: {\n context->ReportError(context, \"Type '%s' is not supported by floor_mod.\",\n TfLiteTypeGetName(input1->type));\n return kTfLiteError;\n }\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n FillDiagHelper(input, output);\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n OpData* data = reinterpret_cast(node->user_data);\n\n const TfLiteTensor* input1;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor1, &input1));\n const TfLiteTensor* input2;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor2, &input2));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n switch (output->type) {\n case kTfLiteInt32: {\n // TensorFlow does not support negative for int32.\n TF_LITE_ENSURE_OK(context, CheckValue(context, input2));\n PowImpl(input1, input2, output, data->requires_broadcast);\n break;\n }\n case kTfLiteFloat32: {\n PowImpl(input1, input2, output, data->requires_broadcast);\n break;\n }\n default: {\n context->ReportError(context, \"Unsupported data type: %d\", output->type);\n return kTfLiteError;\n }\n }\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n OpData* data = static_cast(node->user_data);\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n\n // TODO(b/128934713): Add support for fixed-point per-channel quantization.\n // Currently this only support affine per-layer quantization.\n TF_LITE_ENSURE_EQ(context, output->quantization.type,\n kTfLiteAffineQuantization);\n const auto* affine_quantization =\n static_cast(output->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE(context, affine_quantization->scale->size == 1);\n\n if (input->type == kTfLiteFloat32) {\n // Quantize use case.\n TF_LITE_ENSURE(context, output->type == kTfLiteUInt8 ||\n output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16);\n } else {\n // Requantize use case.\n if (input->type == kTfLiteInt16) {\n TF_LITE_ENSURE(\n context, output->type == kTfLiteInt8 || output->type == kTfLiteInt16);\n } else {\n TF_LITE_ENSURE(context,\n input->type == kTfLiteInt8 || input->type == kTfLiteUInt8);\n TF_LITE_ENSURE(\n context, output->type == kTfLiteUInt8 || output->type == kTfLiteInt8);\n }\n const double effective_output_scale =\n static_cast(input->params.scale) /\n static_cast(output->params.scale);\n QuantizeMultiplier(effective_output_scale, &data->output_multiplier,\n &data->output_shift);\n }\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n // There are two ways in which the 'output' can be made dynamic: it could be\n // a string tensor, or its shape cannot be calculated during Prepare(). In\n // either case, we now have all the information to calculate its shape.\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));\n }\n\n // Note that string tensors are always \"dynamic\" in the sense that their size\n // is not known until we have all the content. This applies even when their\n // shape is known ahead of time. As a result, a string tensor is never given\n // any memory by ResizeOutput(), and we need to do it manually here. Since\n // reshape doesn't change the data, the output tensor needs exactly as many\n // bytes as the input tensor.\n if (output->type == kTfLiteString) {\n auto bytes_required = input->bytes;\n TfLiteTensorRealloc(bytes_required, output);\n output->bytes = bytes_required;\n }\n\n memcpy(output->data.raw, input->data.raw, input->bytes);\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus ReverseSequenceImpl(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* seq_lengths_tensor;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kSeqLengthsTensor,\n &seq_lengths_tensor));\n const TS* seq_lengths = GetTensorData(seq_lengths_tensor);\n\n auto* params =\n reinterpret_cast(node->builtin_data);\n int seq_dim = params->seq_dim;\n int batch_dim = params->batch_dim;\n\n TF_LITE_ENSURE(context, seq_dim >= 0);\n TF_LITE_ENSURE(context, batch_dim >= 0);\n TF_LITE_ENSURE(context, seq_dim != batch_dim);\n TF_LITE_ENSURE(context, seq_dim < NumDimensions(input));\n TF_LITE_ENSURE(context, batch_dim < NumDimensions(input));\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(seq_lengths_tensor, 0),\n SizeOfDimension(input, batch_dim));\n for (int i = 0; i < NumDimensions(seq_lengths_tensor); ++i) {\n TF_LITE_ENSURE(context, seq_lengths[i] <= SizeOfDimension(input, seq_dim));\n }\n\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n reference_ops::ReverseSequence(\n seq_lengths, seq_dim, batch_dim, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(output),\n GetTensorData(output));\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);\n output->type = input->type;\n TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);\n return context->ResizeTensor(context, output, output_size);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n optimized_ops::Round(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n\n OpContext op_context(context, node);\n\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), op_context.params->num_splits);\n\n auto input_type = op_context.input->type;\n TF_LITE_ENSURE(context,\n input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||\n input_type == kTfLiteInt8 || input_type == kTfLiteInt16 ||\n input_type == kTfLiteInt32);\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteTensor* tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor));\n tensor->type = input_type;\n }\n\n // If we know the contents of the 'axis' tensor, resize all outputs.\n // Otherwise, wait until Eval().\n if (IsConstantTensor(op_context.axis)) {\n return ResizeOutputTensors(context, node, op_context.axis, op_context.input,\n op_context.params->num_splits);\n } else {\n return UseDynamicOutputTensors(context, node);\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);\n\n OpContext op_context(context, node);\n\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), op_context.params->num_splits);\n\n auto input_type = op_context.input->type;\n TF_LITE_ENSURE(context,\n input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||\n input_type == kTfLiteInt16 || input_type == kTfLiteInt32 ||\n input_type == kTfLiteInt64 || input_type == kTfLiteInt8);\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteTensor* tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor));\n tensor->type = input_type;\n }\n\n auto size_splits = op_context.size_splits;\n TF_LITE_ENSURE_EQ(context, NumDimensions(size_splits), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), NumElements(size_splits));\n\n // If we know the contents of the 'size_splits' tensor and the 'axis' tensor,\n // resize all outputs. Otherwise, wait until Eval().\n if (IsConstantTensor(op_context.size_splits) &&\n IsConstantTensor(op_context.axis)) {\n return ResizeOutputTensors(context, node, op_context.input,\n op_context.size_splits, op_context.axis);\n } else {\n return UseDynamicOutputTensors(context, node);\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) {\n for (int i = 0; i < NumOutputs(node); ++i) {\n TfLiteTensor* tensor;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor));\n SetTensorToDynamic(tensor);\n }\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n const TfLiteTensor* input1;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor1, &input1));\n const TfLiteTensor* input2;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kInputTensor2, &input2));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32 ||\n output->type == kTfLiteInt64) {\n EvalSub(context, node, params, data, input1, input2, output);\n } else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n EvalQuantized(context, node, params, data, input1, input2,\n output);\n } else {\n context->ReportError(\n context,\n \"output type %d is not supported, requires float|uint8|int32 types.\",\n output->type);\n return kTfLiteError;\n }\n\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " static port::StatusOr Create(\n GpuExecutor* parent, int max_seq_length, int batch_size, int data_size,\n cudnnDataType_t data_type) {\n if (max_seq_length <= 0) {\n return port::Status(port::error::INVALID_ARGUMENT, \"max_seq_length <= 0\");\n }\n int dims[] = {batch_size, data_size, 1};\n int strides[] = {dims[1] * dims[2], dims[2], 1};\n TensorDescriptor tensor_desc = CreateTensorDescriptor();\n RETURN_IF_CUDNN_ERROR(cudnnSetTensorNdDescriptor(\n /*tensorDesc=*/tensor_desc.get(), /*dataType=*/data_type,\n /*nbDims=*/sizeof(dims) / sizeof(dims[0]), /*dimA=*/dims,\n /*strideA=*/strides));\n return CudnnRnnSequenceTensorDescriptor(parent, max_seq_length, batch_size,\n data_size, data_type,\n nullptr,\n std::move(tensor_desc));\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,\n TF_DataType* out_tf_datatype) {\n PyObject* key;\n PyObject* value;\n Py_ssize_t pos = 0;\n\n // Return an error if the fields attribute is null.\n // Occurs with an improper conversion attempt to resource.\n if (descr->fields == nullptr) {\n return errors::Internal(\"Unexpected numpy data type\");\n }\n\n if (PyDict_Next(descr->fields, &pos, &key, &value)) {\n // In Python 3, the keys of numpy custom struct types are unicode, unlike\n // Python 2, where the keys are bytes.\n const char* key_string =\n PyBytes_Check(key) ? PyBytes_AsString(key)\n : PyBytes_AsString(PyUnicode_AsASCIIString(key));\n if (!key_string) {\n return errors::Internal(\"Corrupt numpy type descriptor\");\n }\n tensorflow::string key = key_string;\n // The typenames here should match the field names in the custom struct\n // types constructed in test_util.py.\n // TODO(mrry,keveman): Investigate Numpy type registration to replace this\n // hard-coding of names.\n if (key == \"quint8\") {\n *out_tf_datatype = TF_QUINT8;\n } else if (key == \"qint8\") {\n *out_tf_datatype = TF_QINT8;\n } else if (key == \"qint16\") {\n *out_tf_datatype = TF_QINT16;\n } else if (key == \"quint16\") {\n *out_tf_datatype = TF_QUINT16;\n } else if (key == \"qint32\") {\n *out_tf_datatype = TF_QINT32;\n } else if (key == \"resource\") {\n *out_tf_datatype = TF_RESOURCE;\n } else {\n return errors::Internal(\"Unsupported numpy data type\");\n }\n return Status::OK();\n }\n return errors::Internal(\"Unsupported numpy data type\");\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "safe"} {"code": "Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,\n TF_DataType* out_tf_datatype) {\n PyObject* key;\n PyObject* value;\n Py_ssize_t pos = 0;\n\n // Return an error if the fields attribute is null.\n // Occurs with an improper conversion attempt to resource.\n if (descr->fields == nullptr) {\n return errors::Internal(\"Unexpected numpy data type\");\n }\n\n if (PyDict_Next(descr->fields, &pos, &key, &value)) {\n // In Python 3, the keys of numpy custom struct types are unicode, unlike\n // Python 2, where the keys are bytes.\n const char* key_string =\n PyBytes_Check(key) ? PyBytes_AsString(key)\n : PyBytes_AsString(PyUnicode_AsASCIIString(key));\n if (!key_string) {\n return errors::Internal(\"Corrupt numpy type descriptor\");\n }\n tensorflow::string key = key_string;\n // The typenames here should match the field names in the custom struct\n // types constructed in test_util.py.\n // TODO(mrry,keveman): Investigate Numpy type registration to replace this\n // hard-coding of names.\n if (key == \"quint8\") {\n *out_tf_datatype = TF_QUINT8;\n } else if (key == \"qint8\") {\n *out_tf_datatype = TF_QINT8;\n } else if (key == \"qint16\") {\n *out_tf_datatype = TF_QINT16;\n } else if (key == \"quint16\") {\n *out_tf_datatype = TF_QUINT16;\n } else if (key == \"qint32\") {\n *out_tf_datatype = TF_QINT32;\n } else if (key == \"resource\") {\n *out_tf_datatype = TF_RESOURCE;\n } else {\n return errors::Internal(\"Unsupported numpy data type\");\n }\n return Status::OK();\n }\n return errors::Internal(\"Unsupported numpy data type\");\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-843", "cwe_name": "Access of Resource Using Incompatible Type ('Type Confusion')", "description": "The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.", "url": "https://cwe.mitre.org/data/definitions/843.html", "label_name": "safe"} {"code": " static void launch(OpKernelContext* context, bool cudnn_use_autotune,\n const Tensor& input, const Tensor& filter,\n const std::array& dilations,\n const std::array& strides, const Padding padding,\n TensorFormat data_format, Tensor* output) {\n OP_REQUIRES(context, data_format == FORMAT_NHWC,\n errors::InvalidArgument(\"CPU implementation of Conv3D \"\n \"currently only supports the NHWC \"\n \"tensor format.\"));\n OP_REQUIRES(context,\n dilations[0] == 1 && dilations[1] == 1 && dilations[2] == 1,\n errors::InvalidArgument(\"CPU implementation of Conv3D \"\n \"currently only supports dilated rates \"\n \"of 1.\"));\n OP_REQUIRES(context, filter.dim_size(3) == input.dim_size(input.dims() - 1),\n errors::InvalidArgument(\n \"Number of channels in filter (\", filter.dim_size(3),\n \") must match last dimension of input (\",\n input.dim_size(input.dims() - 1), \")\"));\n functor::CuboidConvolution()(\n context->eigen_device(), output->tensor(),\n input.tensor(), filter.tensor(), strides[2], strides[1],\n strides[0], BrainPadding2EigenPadding(padding));\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-369", "cwe_name": "Divide By Zero", "description": "The product divides a value by zero.", "url": "https://cwe.mitre.org/data/definitions/369.html", "label_name": "safe"} {"code": " void Compute(OpKernelContext* context) override {\n const auto& in_min_tensor = context->input(2);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(in_min_tensor.shape()),\n errors::InvalidArgument(\"min must be a scalar\"));\n const float in_min = in_min_tensor.flat()(0);\n const auto& in_max_tensor = context->input(3);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(in_max_tensor.shape()),\n errors::InvalidArgument(\"max must be a scalar\"));\n const float in_max = in_max_tensor.flat()(0);\n\n ImageResizerState st(align_corners_, false);\n st.ValidateAndCreateOutput(context);\n\n if (!context->status().ok()) return;\n\n // Return if the output is empty.\n if (st.output->NumElements() == 0) return;\n\n typename TTypes::ConstTensor image_data(\n context->input(0).tensor());\n typename TTypes::Tensor output_data(st.output->tensor());\n\n ResizeBilinear(image_data, st.height_scale, st.width_scale, in_min,\n in_max, half_pixel_centers_, &output_data);\n Tensor* out_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &out_min));\n out_min->flat()(0) = in_min;\n\n Tensor* out_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &out_max));\n out_max->flat()(0) = in_max;\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "TEST(FloatPoolingOpTest, MaxPoolWithZeroStride) {\n EXPECT_DEATH(\n FloatPoolingOpModel m(BuiltinOperator_MAX_POOL_2D,\n /*input=*/{TensorType_FLOAT32, {1, 2, 4, 1}},\n /*filter_width=*/2, /*filter_height=*/2,\n /*output=*/{TensorType_FLOAT32, {}},\n /*padding=*/Padding_VALID,\n /*stride_w=*/0, /*stride_h=*/0),\n \"Cannot allocate tensors\");\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-369", "cwe_name": "Divide By Zero", "description": "The product divides a value by zero.", "url": "https://cwe.mitre.org/data/definitions/369.html", "label_name": "safe"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n OpContext op_context(context, node);\n\n // If inputs have no element, shortcircuit.\n if (NumElements(op_context.input1) == 0 ||\n NumElements(op_context.input2) == 0) {\n return kTfLiteOk;\n }\n\n switch (op_context.output->type) {\n case kTfLiteFloat32:\n TFLiteOperation(context, node, op_context);\n break;\n case kTfLiteUInt8:\n TFLiteOperation(context, node, op_context);\n break;\n case kTfLiteInt8:\n TFLiteOperation(context, node, op_context);\n break;\n case kTfLiteInt32:\n TFLiteOperation(context, node, op_context);\n break;\n case kTfLiteInt64:\n TFLiteOperation(context, node, op_context);\n break;\n case kTfLiteInt16:\n TFLiteOperation(context, node, op_context);\n break;\n default:\n context->ReportError(context,\n \"Type %d is currently not supported by Maximum.\",\n op_context.output->type);\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n BatchToSpaceNDContext* op_context) {\n TfLiteIntArray* input_size = op_context->input->dims;\n const int* block_shape = GetTensorData(op_context->block_shape);\n const int* crops = GetTensorData(op_context->crops);\n\n int spatial_dims_num = input_size->size - 2;\n // Block_shape should be a 1D tensor with dimension [spatial_dims_num].\n TF_LITE_ENSURE_EQ(context, NumDimensions(op_context->block_shape), 1);\n TF_LITE_ENSURE_EQ(context, op_context->block_shape->dims->data[0],\n spatial_dims_num);\n // Crops should be a 2D tensor with dimension [spatial_dims_num, 2].\n TF_LITE_ENSURE_EQ(context, NumDimensions(op_context->crops), 2);\n TF_LITE_ENSURE_EQ(context, op_context->crops->dims->data[0],\n spatial_dims_num);\n TF_LITE_ENSURE_EQ(context, op_context->crops->dims->data[1], 2);\n\n for (int i = 0; i < spatial_dims_num * 2; ++i) {\n TF_LITE_ENSURE(context, crops[i] >= 0);\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCopy(input_size);\n int output_batch_size = input_size->data[0];\n for (int dim = 0; dim < spatial_dims_num; ++dim) {\n // Number of batch must be multiple of (block_shape[dim]).\n TF_LITE_ENSURE(context, block_shape[dim] != 0);\n TF_LITE_ENSURE_EQ(context, output_batch_size % block_shape[dim], 0);\n output_batch_size = output_batch_size / block_shape[dim];\n output_size->data[dim + 1] = input_size->data[dim + 1] * block_shape[dim] -\n crops[dim * 2] - crops[dim * 2 + 1];\n }\n\n output_size->data[0] = output_batch_size;\n output_size->data[input_size->size - 1] =\n input_size->data[input_size->size - 1];\n\n return context->ResizeTensor(context, op_context->output, output_size);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-369", "cwe_name": "Divide By Zero", "description": "The product divides a value by zero.", "url": "https://cwe.mitre.org/data/definitions/369.html", "label_name": "safe"} {"code": " ~SubgraphGuard() {\n // If tht original status was OK, recover the boolean flag.\n if (status_ == kTfLiteOk) {\n *is_subgraph_in_use_ = false;\n }\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-835", "cwe_name": "Loop with Unreachable Exit Condition ('Infinite Loop')", "description": "The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.", "url": "https://cwe.mitre.org/data/definitions/835.html", "label_name": "safe"} {"code": " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in = context->input(0);\n const Tensor& grad_in = context->input(1);\n const Tensor& argmax = context->input(2);\n\n PoolParameters params{context,\n ksize_,\n stride_,\n padding_,\n /*explicit_paddings=*/{},\n FORMAT_NHWC,\n tensor_in.shape()};\n if (!context->status().ok()) {\n return;\n }\n\n TensorShape out_shape({params.tensor_in_batch, params.tensor_in_rows,\n params.tensor_in_cols, params.depth});\n Tensor* grad_out = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 0, out_shape, &grad_out));\n\n if (out_shape.num_elements() == 0) return; // nothing to be done\n\n LaunchMaxPoolingGradWithArgmax::launch(\n context, params, grad_in, argmax, grad_out, include_batch_in_index_);\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-369", "cwe_name": "Divide By Zero", "description": "The product divides a value by zero.", "url": "https://cwe.mitre.org/data/definitions/369.html", "label_name": "safe"} {"code": " void readErr(const AsyncSocketException&) noexcept override {}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": " void readDataAvailable(size_t len) noexcept override {\n std::cerr << \"readDataAvailable, len \" << len << std::endl;\n\n currentBuffer.length = len;\n\n if (wcb_) {\n wcb_->setSocket(socket_);\n }\n\n // Write back the same data.\n socket_->write(wcb_, currentBuffer.buffer, len, writeFlags);\n\n buffers.push_back(currentBuffer);\n currentBuffer.reset();\n state = STATE_SUCCEEDED;\n }", "label": 1, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "safe"} {"code": "TEST_F(HeaderTableTests, varyCapacityMalignHeadIndex) {\n // Test checks for a previous bug/crash condition where due to resizing\n // the underlying table to a size lower than a previous max but up from the\n // current size and the position of the head_ index an out of bounds index\n // would occur\n\n // Initialize header table\n HPACKHeader accept(\"accept-encoding\", \"gzip\");\n uint32_t max = 6;\n uint32_t capacity = accept.bytes() * max;\n HeaderTable table(capacity);\n\n // Push head_ to last index in underlying table before potential wrap\n // This is our max table size for the duration of the test\n for (size_t i = 0; i < table.length(); ++i) {\n EXPECT_EQ(table.add(accept), true);\n }\n EXPECT_EQ(table.size(), max);\n EXPECT_EQ(table.bytes(), capacity);\n\n // Flush underlying table (head_ remains the same at the previous max index)\n // Header guranteed to cause a flush as header itself requires 32 bytes plus\n // the sizes of the name and value anyways (which themselves would cause a\n // flush)\n string strLargerThanTableCapacity = string(capacity + 1, 'a');\n HPACKHeader flush(\"flush\", strLargerThanTableCapacity);\n EXPECT_EQ(table.add(flush), false);\n EXPECT_EQ(table.size(), 0);\n\n // Now reduce capacity of table (in functional terms table.size() is lowered\n // but currently table.length() remains the same)\n max = 3;\n resizeTable(table, accept.bytes() * max, max);\n\n // Increase capacity of table (but smaller than all time max; head_ still at\n // previous max index). Previously (now fixed) this size up resulted in\n // incorrect resizing semantics\n max = 4;\n resizeTable(table, accept.bytes() * max, max);\n\n // Now try and add headers; there should be no crash with current position of\n // head_ in the underlying table. Note this is merely one possible way we\n // could force the test to crash as a result of the resize bug this test was\n // added for\n for (size_t i = 0; i <= table.length(); ++i) {\n EXPECT_EQ(table.add(accept), true);\n }\n EXPECT_EQ(table.size(), max);\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "safe"} {"code": "std::string encodeBase64(const std::string& input) {\n return Base64::encode(folly::ByteRange(\n reinterpret_cast(input.c_str()),\n input.length()));\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "selaComputeCompositeParameters(const char *fileout)\n{\nchar *str, *nameh1, *nameh2, *namev1, *namev2;\nchar buf[L_BUFSIZE];\nl_int32 size, size1, size2, len;\nSARRAY *sa;\nSELA *selabasic, *selacomb;\n\n selabasic = selaAddBasic(NULL);\n selacomb = selaAddDwaCombs(NULL);\n sa = sarrayCreate(64);\n for (size = 2; size < 64; size++) {\n selectComposableSizes(size, &size1, &size2);\n nameh1 = selaGetBrickName(selabasic, size1, 1);\n namev1 = selaGetBrickName(selabasic, 1, size1);\n if (size2 > 1) {\n nameh2 = selaGetCombName(selacomb, size1 * size2, L_HORIZ);\n namev2 = selaGetCombName(selacomb, size1 * size2, L_VERT);\n } else {\n nameh2 = stringNew(\"\");\n namev2 = stringNew(\"\");\n }\n snprintf(buf, L_BUFSIZE,\n \" { %d, %d, %d, \\\"%s\\\", \\\"%s\\\", \\\"%s\\\", \\\"%s\\\" },\",\n size, size1, size2, nameh1, nameh2, namev1, namev2);\n sarrayAddString(sa, buf, L_COPY);\n LEPT_FREE(nameh1);\n LEPT_FREE(nameh2);\n LEPT_FREE(namev1);\n LEPT_FREE(namev2);\n }\n str = sarrayToString(sa, 1);\n len = strlen(str);\n l_binaryWrite(fileout, \"w\", str, len + 1);\n LEPT_FREE(str);\n sarrayDestroy(&sa);\n selaDestroy(&selabasic);\n selaDestroy(&selacomb);\n return;\n}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "safe"} {"code": "\t\tvoid CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)\n\t\t{\n\t\t\tstd::string idx = request::findValue(&req, \"idx\");\n\t\t\tif (idx == \"\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstd::vector > result;\n\t\t\tresult = m_sql.safe_queryBlob(\"SELECT Image FROM Floorplans WHERE ID=%d\", atol(idx.c_str()));\n\t\t\tif (result.empty())\n\t\t\t\treturn;\n\t\t\treply::set_content(&rep, result[0][0].begin(), result[0][0].end());\n\t\t\tstd::string oname = \"floorplan\";\n\t\t\tif (result[0][0].size() > 10)\n\t\t\t{\n\t\t\t\tif (result[0][0][0] == 'P')\n\t\t\t\t\toname += \".png\";\n\t\t\t\telse if (result[0][0][0] == -1)\n\t\t\t\t\toname += \".jpg\";\n\t\t\t\telse if (result[0][0][0] == 'B')\n\t\t\t\t\toname += \".bmp\";\n\t\t\t\telse if (result[0][0][0] == 'G')\n\t\t\t\t\toname += \".gif\";\n\t\t\t}\n\t\t\treply::add_header_attachment(&rep, oname);\n\t\t}", "label": 1, "programming_language": "C++", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "Fraction::Fraction(int32_t num,int32_t den)\n{\n // Reduce resolution of fraction until we are in a safe range.\n // We need this as adding fractions may lead to very large denominators\n // (e.g. 0x10000 * 0x10000 > 0x100000000 -> overflow, leading to integer 0)\n\n while (denominator > MAX_FRACTION_VALUE || denominator < -MAX_FRACTION_VALUE) {\n numerator /= 2;\n denominator /= 2;\n }\n\n while (numerator > MAX_FRACTION_VALUE || numerator < -MAX_FRACTION_VALUE) {\n numerator /= 2;\n denominator /= 2;\n }\n}", "label": 1, "programming_language": "C++", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": "static int em_sysexit(struct x86_emulate_ctxt *ctxt)\n{\n\tconst struct x86_emulate_ops *ops = ctxt->ops;\n\tstruct desc_struct cs, ss;\n\tu64 msr_data;\n\tint usermode;\n\tu16 cs_sel = 0, ss_sel = 0;\n\n\t/* inject #GP if in real mode or Virtual 8086 mode */\n\tif (ctxt->mode == X86EMUL_MODE_REAL ||\n\t ctxt->mode == X86EMUL_MODE_VM86)\n\t\treturn emulate_gp(ctxt, 0);\n\n\tsetup_syscalls_segments(ctxt, &cs, &ss);\n\n\tif ((ctxt->rex_prefix & 0x8) != 0x0)\n\t\tusermode = X86EMUL_MODE_PROT64;\n\telse\n\t\tusermode = X86EMUL_MODE_PROT32;\n\n\tcs.dpl = 3;\n\tss.dpl = 3;\n\tops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);\n\tswitch (usermode) {\n\tcase X86EMUL_MODE_PROT32:\n\t\tcs_sel = (u16)(msr_data + 16);\n\t\tif ((msr_data & 0xfffc) == 0x0)\n\t\t\treturn emulate_gp(ctxt, 0);\n\t\tss_sel = (u16)(msr_data + 24);\n\t\tbreak;\n\tcase X86EMUL_MODE_PROT64:\n\t\tcs_sel = (u16)(msr_data + 32);\n\t\tif (msr_data == 0x0)\n\t\t\treturn emulate_gp(ctxt, 0);\n\t\tss_sel = cs_sel + 8;\n\t\tcs.d = 0;\n\t\tcs.l = 1;\n\t\tbreak;\n\t}\n\tcs_sel |= SELECTOR_RPL_MASK;\n\tss_sel |= SELECTOR_RPL_MASK;\n\n\tops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);\n\tops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);\n\n\tctxt->_eip = reg_read(ctxt, VCPU_REGS_RDX);\n\t*reg_write(ctxt, VCPU_REGS_RSP) = reg_read(ctxt, VCPU_REGS_RCX);\n\n\treturn X86EMUL_CONTINUE;\n}", "label": 0, "programming_language": "C++", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "static int em_ret_near_imm(struct x86_emulate_ctxt *ctxt)\n{\n\tint rc;\n\n\tctxt->dst.type = OP_REG;\n\tctxt->dst.addr.reg = &ctxt->_eip;\n\tctxt->dst.bytes = ctxt->op_bytes;\n\trc = emulate_pop(ctxt, &ctxt->dst.val, ctxt->op_bytes);\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\trsp_increment(ctxt, ctxt->src.val);\n\treturn X86EMUL_CONTINUE;\n}", "label": 0, "programming_language": "C++", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": "compat_mpt_command(struct file *filp, unsigned int cmd,\n\t\t\tunsigned long arg)\n{\n\tstruct mpt_ioctl_command32 karg32;\n\tstruct mpt_ioctl_command32 __user *uarg = (struct mpt_ioctl_command32 __user *) arg;\n\tstruct mpt_ioctl_command karg;\n\tMPT_ADAPTER *iocp = NULL;\n\tint iocnum, iocnumX;\n\tint nonblock = (filp->f_flags & O_NONBLOCK);\n\tint ret;\n\n\tif (copy_from_user(&karg32, (char __user *)arg, sizeof(karg32)))\n\t\treturn -EFAULT;\n\n\t/* Verify intended MPT adapter */\n\tiocnumX = karg32.hdr.iocnum & 0xFF;\n\tif (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||\n\t (iocp == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"::compat_mpt_command @%d - ioc%d not found!\\n\",\n\t\t\t__LINE__, iocnumX);\n\t\treturn -ENODEV;\n\t}\n\n\tif ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n\t\treturn ret;\n\n\tdctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT \"compat_mpt_command() called\\n\",\n\t iocp->name));\n\t/* Copy data to karg */\n\tkarg.hdr.iocnum = karg32.hdr.iocnum;\n\tkarg.hdr.port = karg32.hdr.port;\n\tkarg.timeout = karg32.timeout;\n\tkarg.maxReplyBytes = karg32.maxReplyBytes;\n\n\tkarg.dataInSize = karg32.dataInSize;\n\tkarg.dataOutSize = karg32.dataOutSize;\n\tkarg.maxSenseBytes = karg32.maxSenseBytes;\n\tkarg.dataSgeOffset = karg32.dataSgeOffset;\n\n\tkarg.replyFrameBufPtr = (char __user *)(unsigned long)karg32.replyFrameBufPtr;\n\tkarg.dataInBufPtr = (char __user *)(unsigned long)karg32.dataInBufPtr;\n\tkarg.dataOutBufPtr = (char __user *)(unsigned long)karg32.dataOutBufPtr;\n\tkarg.senseDataPtr = (char __user *)(unsigned long)karg32.senseDataPtr;\n\n\t/* Pass new structure to do_mpt_command\n\t */\n\tret = mptctl_do_mpt_command (karg, &uarg->MF);\n\n\tmutex_unlock(&iocp->ioctl_cmds.mutex);\n\n\treturn ret;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "mptctl_fw_download(unsigned long arg)\n{\n\tstruct mpt_fw_xfer __user *ufwdl = (void __user *) arg;\n\tstruct mpt_fw_xfer\t kfwdl;\n\n\tif (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::_ioctl_fwdl - \"\n\t\t\t\t\"Unable to copy mpt_fw_xfer struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, ufwdl);\n\t\treturn -EFAULT;\n\t}\n\n\treturn mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "vulnerable"} {"code": "void CZNC::ForceEncoding() {\n m_uiForceEncoding++;\n#ifdef HAVE_ICU\n for (Csock* pSock : GetManager()) {\n if (pSock->GetEncoding().empty()) {\n pSock->SetEncoding(\"UTF-8\");\n }\n }\n#endif\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "\tSilenceMessage(const std::string& mask, const std::string& flags)\n\t\t: ClientProtocol::Message(\"SILENCE\")\n\t{\n\t\tPushParam(mask);\n\t\tPushParamRef(flags);\n\t}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "\tPong(const std::string& cookie, const std::string& server = \"\")\n\t\t: ClientProtocol::Message(\"PONG\", ServerInstance->Config->GetServerName())\n\t{\n\t\tPushParamRef(ServerInstance->Config->GetServerName());\n\t\tif (!server.empty())\n\t\t\tPushParamRef(server);\n\t\tPushParamRef(cookie);\n\t}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-732", "cwe_name": "Incorrect Permission Assignment for Critical Resource", "description": "The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.", "url": "https://cwe.mitre.org/data/definitions/732.html", "label_name": "vulnerable"} {"code": "int CLASS parse_jpeg(int offset)\n{\n int len, save, hlen, mark;\n fseek(ifp, offset, SEEK_SET);\n if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)\n return 0;\n\n while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)\n {\n order = 0x4d4d;\n len = get2() - 2;\n save = ftell(ifp);\n if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)\n {\n fgetc(ifp);\n raw_height = get2();\n raw_width = get2();\n }\n order = get2();\n hlen = get4();\n if (get4() == 0x48454150) /* \"HEAP\" */\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n#endif\n parse_ciff(save + hlen, len - hlen, 0);\n }\n if (parse_tiff(save + 6))\n apply_tiff();\n fseek(ifp, save + len, SEEK_SET);\n }\n return 1;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,\n size_t mincodes, size_t numcodes, unsigned maxbitlen)\n{\n unsigned error = 0;\n while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/\n tree->maxbitlen = maxbitlen;\n tree->numcodes = (unsigned)numcodes; /*number of symbols*/\n tree->lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned));\n if(!tree->lengths) return 83; /*alloc fail*/\n /*initialize all lengths to 0*/\n memset(tree->lengths, 0, numcodes * sizeof(unsigned));\n\n error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);\n if(!error) error = HuffmanTree_makeFromLengths2(tree);\n return error;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-252", "cwe_name": "Unchecked Return Value", "description": "The software does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions.", "url": "https://cwe.mitre.org/data/definitions/252.html", "label_name": "vulnerable"} {"code": "void nego_process_negotiation_request(rdpNego* nego, wStream* s)\n{\n\tBYTE flags;\n\tUINT16 length;\n\tStream_Read_UINT8(s, flags);\n\tStream_Read_UINT16(s, length);\n\tStream_Read_UINT32(s, nego->RequestedProtocols);\n\tWLog_DBG(TAG, \"RDP_NEG_REQ: RequestedProtocol: 0x%08\" PRIX32 \"\", nego->RequestedProtocols);\n\tnego->state = NEGO_STATE_FINAL;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID, cmsUInt32Number n, cmsUInt32Number ColorantCount, const char* Prefix, const char* Suffix)\n{\n cmsNAMEDCOLORLIST* v = (cmsNAMEDCOLORLIST*) _cmsMallocZero(ContextID, sizeof(cmsNAMEDCOLORLIST));\n\n if (v == NULL) return NULL;\n\n v ->List = NULL;\n v ->nColors = 0;\n v ->ContextID = ContextID;\n\n while (v -> Allocated < n)\n GrowNamedColorList(v);\n\n strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix));\n strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix));\n v->Prefix[32] = v->Suffix[32] = 0;\n\n v -> ColorantCount = ColorantCount;\n\n return v;\n}", "label": 0, "programming_language": "C++", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static void exif_process_APP12(image_info_type *ImageInfo,\n char *buffer, size_t length) {\n size_t l1, l2=0;\n if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {\n exif_iif_add_tag(ImageInfo, SECTION_APP12, \"Company\",\n TAG_NONE, TAG_FMT_STRING, l1, buffer+2);\n if (length > 2+l1+1) {\n l2 = php_strnlen(buffer+2+l1+1, length-2-l1+1);\n exif_iif_add_tag(ImageInfo, SECTION_APP12, \"Info\",\n TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1);\n }\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": " static void setAppend(SetType& set, const VariantType& v) {\n auto value_type = type(v);\n if (value_type != HPHP::serialize::Type::INT64 &&\n value_type != HPHP::serialize::Type::STRING) {\n throw HPHP::serialize::UnserializeError(\n \"Unsupported keyset element of type \" +\n folly::to(value_type));\n }\n set.append(v);\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-674", "cwe_name": "Uncontrolled Recursion", "description": "The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.", "url": "https://cwe.mitre.org/data/definitions/674.html", "label_name": "vulnerable"} {"code": "gdImagePtr gdImageCreateTrueColor (int sx, int sy)\n{\n int i;\n gdImagePtr im;\n\n if (overflow2(sx, sy)) {\n return NULL;\n }\n\n if (overflow2(sizeof(unsigned char *), sy)) {\n return NULL;\n }\n\n if (overflow2(sizeof(int) + sizeof(unsigned char), sx * sy)) {\n return NULL;\n }\n\n // Check for OOM before doing a potentially large allocation.\n auto allocsz = sizeof(gdImage)\n + sy * (sizeof(int *) + sizeof(unsigned char *))\n + sx * sy * (sizeof(int) + sizeof(unsigned char));\n if (UNLIKELY(precheckOOM(allocsz))) {\n // Don't throw here because GD might need to do its own cleanup.\n return NULL;\n }\n\n im = (gdImage *) gdMalloc(sizeof(gdImage));\n memset(im, 0, sizeof(gdImage));\n im->tpixels = (int **) gdMalloc(sizeof(int *) * sy);\n im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);\n im->polyInts = 0;\n im->polyAllocated = 0;\n im->brush = 0;\n im->tile = 0;\n im->style = 0;\n for (i = 0; i < sy; i++) {\n im->tpixels[i] = (int *) gdCalloc(sx, sizeof(int));\n im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));\n }\n im->sx = sx;\n im->sy = sy;\n im->transparent = (-1);\n im->interlace = 0;\n im->trueColor = 1;\n /* 2.0.2: alpha blending is now on by default, and saving of alpha is\n * off by default. This allows font antialiasing to work as expected\n * on the first try in JPEGs -- quite important -- and also allows\n * for smaller PNGs when saving of alpha channel is not really\n * desired, which it usually isn't!\n */\n im->saveAlphaFlag = 0;\n im->alphaBlendingFlag = 1;\n im->thick = 1;\n im->AA = 0;\n im->AA_polygon = 0;\n im->cx1 = 0;\n im->cy1 = 0;\n im->cx2 = im->sx - 1;\n im->cy2 = im->sy - 1;\n im->interpolation = NULL;\n im->interpolation_id = GD_BILINEAR_FIXED;\n return im;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "inline int StringData::size() const { return m_len; }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static String HHVM_FUNCTION(bcpow, const String& left, const String& right,\n int64_t scale /* = -1 */) {\n if (scale < 0) scale = BCG(bc_precision);\n bc_num first, second, result;\n bc_init_num(&first);\n bc_init_num(&second);\n bc_init_num(&result);\n SCOPE_EXIT {\n bc_free_num(&first);\n bc_free_num(&second);\n bc_free_num(&result);\n };\n php_str2num(&first, (char*)left.data());\n php_str2num(&second, (char*)right.data());\n bc_raise(first, second, &result, scale);\n if (result->n_scale > scale) {\n result->n_scale = scale;\n }\n String ret(bc_num2str(result), AttachString);\n return ret;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "static String HHVM_FUNCTION(bcmul, const String& left, const String& right,\n int64_t scale /* = -1 */) {\n if (scale < 0) scale = BCG(bc_precision);\n bc_num first, second, result;\n bc_init_num(&first);\n bc_init_num(&second);\n bc_init_num(&result);\n php_str2num(&first, (char*)left.data());\n php_str2num(&second, (char*)right.data());\n bc_multiply(first, second, &result, scale);\n if (result->n_scale > scale) {\n result->n_scale = scale;\n }\n String ret(bc_num2str(result), AttachString);\n bc_free_num(&first);\n bc_free_num(&second);\n bc_free_num(&result);\n return ret;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b)\n\t{\n#ifdef BN_LLONG\n\tBN_ULLONG t;\n#else\n\tBN_ULONG bl,bh;\n#endif\n\tBN_ULONG t1,t2;\n\tBN_ULONG c1,c2,c3;\n\n\tc1=0;\n\tc2=0;\n\tc3=0;\n\tmul_add_c(a[0],b[0],c1,c2,c3);\n\tr[0]=c1;\n\tc1=0;\n\tmul_add_c(a[0],b[1],c2,c3,c1);\n\tmul_add_c(a[1],b[0],c2,c3,c1);\n\tr[1]=c2;\n\tc2=0;\n\tmul_add_c(a[2],b[0],c3,c1,c2);\n\tmul_add_c(a[1],b[1],c3,c1,c2);\n\tmul_add_c(a[0],b[2],c3,c1,c2);\n\tr[2]=c3;\n\tc3=0;\n\tmul_add_c(a[0],b[3],c1,c2,c3);\n\tmul_add_c(a[1],b[2],c1,c2,c3);\n\tmul_add_c(a[2],b[1],c1,c2,c3);\n\tmul_add_c(a[3],b[0],c1,c2,c3);\n\tr[3]=c1;\n\tc1=0;\n\tmul_add_c(a[3],b[1],c2,c3,c1);\n\tmul_add_c(a[2],b[2],c2,c3,c1);\n\tmul_add_c(a[1],b[3],c2,c3,c1);\n\tr[4]=c2;\n\tc2=0;\n\tmul_add_c(a[2],b[3],c3,c1,c2);\n\tmul_add_c(a[3],b[2],c3,c1,c2);\n\tr[5]=c3;\n\tc3=0;\n\tmul_add_c(a[3],b[3],c1,c2,c3);\n\tr[6]=c1;\n\tr[7]=c2;\n\t}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": "void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a)\n\t{\n#ifdef BN_LLONG\n\tBN_ULLONG t,tt;\n#else\n\tBN_ULONG bl,bh;\n#endif\n\tBN_ULONG t1,t2;\n\tBN_ULONG c1,c2,c3;\n\n\tc1=0;\n\tc2=0;\n\tc3=0;\n\tsqr_add_c(a,0,c1,c2,c3);\n\tr[0]=c1;\n\tc1=0;\n\tsqr_add_c2(a,1,0,c2,c3,c1);\n\tr[1]=c2;\n\tc2=0;\n\tsqr_add_c(a,1,c3,c1,c2);\n\tsqr_add_c2(a,2,0,c3,c1,c2);\n\tr[2]=c3;\n\tc3=0;\n\tsqr_add_c2(a,3,0,c1,c2,c3);\n\tsqr_add_c2(a,2,1,c1,c2,c3);\n\tr[3]=c1;\n\tc1=0;\n\tsqr_add_c(a,2,c2,c3,c1);\n\tsqr_add_c2(a,3,1,c2,c3,c1);\n\tsqr_add_c2(a,4,0,c2,c3,c1);\n\tr[4]=c2;\n\tc2=0;\n\tsqr_add_c2(a,5,0,c3,c1,c2);\n\tsqr_add_c2(a,4,1,c3,c1,c2);\n\tsqr_add_c2(a,3,2,c3,c1,c2);\n\tr[5]=c3;\n\tc3=0;\n\tsqr_add_c(a,3,c1,c2,c3);\n\tsqr_add_c2(a,4,2,c1,c2,c3);\n\tsqr_add_c2(a,5,1,c1,c2,c3);\n\tsqr_add_c2(a,6,0,c1,c2,c3);\n\tr[6]=c1;\n\tc1=0;\n\tsqr_add_c2(a,7,0,c2,c3,c1);\n\tsqr_add_c2(a,6,1,c2,c3,c1);\n\tsqr_add_c2(a,5,2,c2,c3,c1);\n\tsqr_add_c2(a,4,3,c2,c3,c1);\n\tr[7]=c2;\n\tc2=0;\n\tsqr_add_c(a,4,c3,c1,c2);\n\tsqr_add_c2(a,5,3,c3,c1,c2);\n\tsqr_add_c2(a,6,2,c3,c1,c2);\n\tsqr_add_c2(a,7,1,c3,c1,c2);\n\tr[8]=c3;\n\tc3=0;\n\tsqr_add_c2(a,7,2,c1,c2,c3);\n\tsqr_add_c2(a,6,3,c1,c2,c3);\n\tsqr_add_c2(a,5,4,c1,c2,c3);\n\tr[9]=c1;\n\tc1=0;\n\tsqr_add_c(a,5,c2,c3,c1);\n\tsqr_add_c2(a,6,4,c2,c3,c1);\n\tsqr_add_c2(a,7,3,c2,c3,c1);\n\tr[10]=c2;\n\tc2=0;\n\tsqr_add_c2(a,7,4,c3,c1,c2);\n\tsqr_add_c2(a,6,5,c3,c1,c2);\n\tr[11]=c3;\n\tc3=0;\n\tsqr_add_c(a,6,c1,c2,c3);\n\tsqr_add_c2(a,7,5,c1,c2,c3);\n\tr[12]=c1;\n\tc1=0;\n\tsqr_add_c2(a,7,6,c2,c3,c1);\n\tr[13]=c2;\n\tc2=0;\n\tsqr_add_c(a,7,c3,c1,c2);\n\tr[14]=c3;\n\tr[15]=c1;\n\t}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-310", "cwe_name": "Cryptographic Issues", "description": "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", "url": "https://cwe.mitre.org/data/definitions/310.html", "label_name": "vulnerable"} {"code": "static int parseFileInner(MaState *state, cchar *path)\n{\n MaDirective *directive;\n char *tok, *key, *line, *value;\n \n assert(state);\n assert(path && *path);\n\n if (openConfig(state, path) < 0) {\n return MPR_ERR_CANT_OPEN;\n }\n for (state->lineNumber = 1; state->file && (line = mprReadLine(state->file, 0, NULL)) != 0; state->lineNumber++) {\n for (tok = line; isspace((uchar) *tok); tok++) ;\n if (*tok == '\\0' || *tok == '#') {\n continue;\n }\n state->key = 0;\n key = getDirective(line, &value);\n if (!state->enabled) {\n if (key[0] != '<') {\n continue;\n }\n }\n if ((directive = mprLookupKey(directives, key)) == 0) {\n mprLog(\"error appweb config\", 0, \"Unknown directive \\\"%s\\\". At line %d in %s\", \n key, state->lineNumber, state->filename);\n return MPR_ERR_BAD_SYNTAX;\n }\n state->key = key;\n /*\n Allow directives to run commands and yield without worring about holding references.\n */\n mprPauseGC();\n if ((*directive)(state, key, value) < 0) {\n mprResumeGC();\n mprLog(\"error appweb config\", 0, \"Error with directive \\\"%s\\\". At line %d in %s\", \n state->key, state->lineNumber, state->filename);\n return MPR_ERR_BAD_SYNTAX;\n }\n mprResumeGC();\n mprYield(0);\n state = state->top->current;\n }\n /* EOF */\n if (state->prev && state->file == state->prev->file) {\n mprLog(\"error appweb config\", 0, \"Unclosed directives in %s\", state->filename);\n while (state->prev && state->file == state->prev->file) {\n state = state->prev;\n }\n }\n mprCloseFile(state->file);\n return 0;\n}", "label": 0, "programming_language": "C++", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": " bool PamBackend::start(const QString &user) {\n bool result;\n\n QString service = QStringLiteral(\"sddm\");\n\n if (user == QStringLiteral(\"sddm\") && m_greeter)\n service = QStringLiteral(\"sddm-greeter\");\n else if (m_app->session()->path().isEmpty())\n service = QStringLiteral(\"sddm-check\");\n else if (m_autologin)\n service = QStringLiteral(\"sddm-autologin\");\n result = m_pam->start(service, user);\n\n if (!result)\n m_app->error(m_pam->errorString(), Auth::ERROR_INTERNAL);\n\n return result;\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " bool PamBackend::start(const QString &user) {\n bool result;\n\n QString service = QStringLiteral(\"sddm\");\n\n if (user == QStringLiteral(\"sddm\") && m_greeter)\n service = QStringLiteral(\"sddm-greeter\");\n else if (m_app->session()->path().isEmpty())\n service = QStringLiteral(\"sddm-check\");\n else if (m_autologin)\n service = QStringLiteral(\"sddm-autologin\");\n result = m_pam->start(service, user);\n\n if (!result)\n m_app->error(m_pam->errorString(), Auth::ERROR_INTERNAL);\n\n return result;\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-613", "cwe_name": "Insufficient Session Expiration", "description": "According to WASC, \"Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization.\"", "url": "https://cwe.mitre.org/data/definitions/613.html", "label_name": "vulnerable"} {"code": "static inline ulong encode_twos_comp(long n, int prec)\n{\n\tulong result;\n\tassert(prec >= 2);\n\tjas_eprintf(\"warning: support for signed data is untested\\n\");\n\t// NOTE: Is this correct?\n\tif (n < 0) {\n\t\tresult = -n;\n\t\tresult = (result ^ 0xffffffffUL) + 1;\n\t\tresult &= (1 << prec) - 1;\n\t} else {\n\t\tresult = n;\n\t}\n\treturn result;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms,\n int clrspc)\n{\n\tjas_image_t *image;\n\tuint_fast32_t rawsize;\n\tuint_fast32_t inmem;\n\tint cmptno;\n\tjas_image_cmptparm_t *cmptparm;\n\n\tif (!(image = jas_image_create0())) {\n\t\treturn 0;\n\t}\n\n\timage->clrspc_ = clrspc;\n\timage->maxcmpts_ = numcmpts;\n\timage->inmem_ = true;\n\n\t/* Allocate memory for the per-component information. */\n\tif (!(image->cmpts_ = jas_alloc2(image->maxcmpts_,\n\t sizeof(jas_image_cmpt_t *)))) {\n\t\tjas_image_destroy(image);\n\t\treturn 0;\n\t}\n\t/* Initialize in case of failure. */\n\tfor (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {\n\t\timage->cmpts_[cmptno] = 0;\n\t}\n\n\t/* Compute the approximate raw size of the image. */\n\trawsize = 0;\n\tfor (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,\n\t ++cmptparm) {\n\t\trawsize += cmptparm->width * cmptparm->height *\n\t\t (cmptparm->prec + 7) / 8;\n\t}\n\t/* Decide whether to buffer the image data in memory, based on the\n\t raw size of the image. */\n\tinmem = (rawsize < JAS_IMAGE_INMEMTHRESH);\n\n\t/* Create the individual image components. */\n\tfor (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,\n\t ++cmptparm) {\n\t\tif (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,\n\t\t cmptparm->tly, cmptparm->hstep, cmptparm->vstep,\n\t\t cmptparm->width, cmptparm->height, cmptparm->prec,\n\t\t cmptparm->sgnd, inmem))) {\n\t\t\tjas_image_destroy(image);\n\t\t\treturn 0;\n\t\t}\n\t\t++image->numcmpts_;\n\t}\n\n\t/* Determine the bounding box for all of the components on the\n\t reference grid (i.e., the image area) */\n\tjas_image_setbbox(image);\n\n\treturn image;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "jas_image_t *jas_image_create0()\n{\n\tjas_image_t *image;\n\n\tif (!(image = jas_malloc(sizeof(jas_image_t)))) {\n\t\treturn 0;\n\t}\n\n\timage->tlx_ = 0;\n\timage->tly_ = 0;\n\timage->brx_ = 0;\n\timage->bry_ = 0;\n\timage->clrspc_ = JAS_CLRSPC_UNKNOWN;\n\timage->numcmpts_ = 0;\n\timage->maxcmpts_ = 0;\n\timage->cmpts_ = 0;\n\timage->inmem_ = true;\n\timage->cmprof_ = 0;\n\n\treturn image;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t *rowstart;\n\tint rowstep;\n\tjas_seqent_t *data;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t*data = val;\n\t\t\t}\n\t\t}\n\t}\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "void jas_matrix_divpow2(jas_matrix_t *matrix, int n)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t *rowstart;\n\tint rowstep;\n\tjas_seqent_t *data;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t*data = (*data >= 0) ? ((*data) >> n) :\n\t\t\t\t (-((-(*data)) >> n));\n\t\t\t}\n\t\t}\n\t}\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "void CSecurityTLS::shutdown(bool needbye)\n{\n if (session && needbye)\n if (gnutls_bye(session, GNUTLS_SHUT_RDWR) != GNUTLS_E_SUCCESS)\n vlog.error(\"gnutls_bye failed\");\n\n if (anon_cred) {\n gnutls_anon_free_client_credentials(anon_cred);\n anon_cred = 0;\n }\n\n if (cert_cred) {\n gnutls_certificate_free_credentials(cert_cred);\n cert_cred = 0;\n }\n\n if (session) {\n gnutls_deinit(session);\n session = 0;\n\n gnutls_global_deinit();\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "bool SSecurityTLS::processMsg(SConnection *sc)\n{\n rdr::InStream* is = sc->getInStream();\n rdr::OutStream* os = sc->getOutStream();\n\n vlog.debug(\"Process security message (session %p)\", session);\n\n if (!session) {\n initGlobal();\n\n if (gnutls_init(&session, GNUTLS_SERVER) != GNUTLS_E_SUCCESS)\n throw AuthFailureException(\"gnutls_init failed\");\n\n if (gnutls_set_default_priority(session) != GNUTLS_E_SUCCESS)\n throw AuthFailureException(\"gnutls_set_default_priority failed\");\n\n try {\n setParams(session);\n }\n catch(...) {\n os->writeU8(0);\n throw;\n }\n\n os->writeU8(1);\n os->flush();\n }\n\n rdr::TLSInStream *tlsis = new rdr::TLSInStream(is, session);\n rdr::TLSOutStream *tlsos = new rdr::TLSOutStream(os, session);\n\n int err;\n err = gnutls_handshake(session);\n if (err != GNUTLS_E_SUCCESS) {\n delete tlsis;\n delete tlsos;\n\n if (!gnutls_error_is_fatal(err)) {\n vlog.debug(\"Deferring completion of TLS handshake: %s\", gnutls_strerror(err));\n return false;\n }\n vlog.error(\"TLS Handshake failed: %s\", gnutls_strerror (err));\n shutdown();\n throw AuthFailureException(\"TLS Handshake failed\");\n }\n\n vlog.debug(\"Handshake completed\");\n\n sc->setStreams(fis = tlsis, fos = tlsos);\n\n return true;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "char *Hub::inflate(char *data, size_t &length) {\n dynamicInflationBuffer.clear();\n\n inflationStream.next_in = (Bytef *) data;\n inflationStream.avail_in = length;\n\n int err;\n do {\n inflationStream.next_out = (Bytef *) inflationBuffer;\n inflationStream.avail_out = LARGE_BUFFER_SIZE;\n err = ::inflate(&inflationStream, Z_FINISH);\n if (!inflationStream.avail_in) {\n break;\n }\n dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);\n } while (err == Z_BUF_ERROR);\n\n inflateReset(&inflationStream);\n\n if (err != Z_BUF_ERROR && err != Z_OK) {\n length = 0;\n return nullptr;\n }\n\n if (dynamicInflationBuffer.length()) {\n dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);\n\n length = dynamicInflationBuffer.length();\n return (char *) dynamicInflationBuffer.data();\n }\n\n length = LARGE_BUFFER_SIZE - inflationStream.avail_out;\n return inflationBuffer;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,\n Buffer* buf, int *err, gchar **err_info)\n{\n\tguint8 *pd;\n\tgchar\tline[COSINE_LINE_LENGTH];\n\tint\ti, hex_lines, n, caplen = 0;\n\n\t/* Make sure we have enough room for the packet */\n\tws_buffer_assure_space(buf, COSINE_MAX_PACKET_LEN);\n\tpd = ws_buffer_start_ptr(buf);\n\n\t/* Calculate the number of hex dump lines, each\n\t * containing 16 bytes of data */\n\thex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);\n\n\tfor (i = 0; i < hex_lines; i++) {\n\t\tif (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {\n\t\t\t*err = file_error(fh, err_info);\n\t\t\tif (*err == 0) {\n\t\t\t\t*err = WTAP_ERR_SHORT_READ;\n\t\t\t}\n\t\t\treturn FALSE;\n\t\t}\n\t\tif (empty_line(line)) {\n\t\t\tbreak;\n\t\t}\n\t\tif ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {\n\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t*err_info = g_strdup(\"cosine: hex dump line doesn't have 16 numbers\");\n\t\t\treturn FALSE;\n\t\t}\n\t\tcaplen += n;\n\t}\n\tphdr->caplen = caplen;\n\treturn TRUE;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": " void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)\n {\n SparseArraySegment* headSeg = (SparseArraySegment*)pArr->head;\n SparseArraySegment* pnewHeadSeg = (SparseArraySegment*)pnewArr->head;\n\n // Fill the newly created sliced array\n js_memcpy_s(pnewHeadSeg->elements, sizeof(T) * newLen, headSeg->elements + start, sizeof(T) * newLen);\n pnewHeadSeg->length = newLen;\n\n Assert(pnewHeadSeg->length <= pnewHeadSeg->size);\n // Prototype lookup for missing elements\n if (!pArr->HasNoMissingValues())\n {\n for (uint32 i = 0; i < newLen; i++)\n {\n // array type might be changed in the below call to DirectGetItemAtFull\n // need recheck array type before checking array item [i + start]\n if (pArr->IsMissingItem(i + start))\n {\n Var element;\n pnewArr->SetHasNoMissingValues(false);\n if (pArr->DirectGetItemAtFull(i + start, &element))\n {\n pnewArr->SetItem(i, element, PropertyOperation_None);\n }\n }\n }\n }\n#ifdef DBG\n else\n {\n for (uint32 i = 0; i < newLen; i++)\n {\n AssertMsg(!SparseArraySegment::IsMissingItem(&headSeg->elements[i+start]), \"Array marked incorrectly as having missing value\");\n }\n }\n\n#endif\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)\n{\n inspector.AddField(\"Configuration Version\", m_ConfigurationVersion);\n const char* profile_name = GetProfileName(m_Profile);\n if (profile_name) {\n inspector.AddField(\"Profile\", profile_name);\n } else {\n inspector.AddField(\"Profile\", m_Profile);\n }\n inspector.AddField(\"Profile Compatibility\", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);\n inspector.AddField(\"Level\", m_Level);\n inspector.AddField(\"NALU Length Size\", m_NaluLengthSize);\n for (unsigned int i=0; i 0) {\n\t\tstd::string cmdline = strprintf::fmt(\"%s '%s' %s %s %s\",\n\t\t bookmark_cmd,\n\t\t utils::replace_all(url,\"'\", \"%27\"),\n\t\t quote_empty(stfl::quote(title)),\n\t\t quote_empty(stfl::quote(description)),\n\t\t quote_empty(stfl::quote(feed_title)));\n\n\t\tLOG(level::DEBUG, \"controller::bookmark: cmd = %s\", cmdline);\n\n\t\tif (is_interactive) {\n\t\t\tv->push_empty_formaction();\n\t\t\tstfl::reset();\n\t\t\tutils::run_interactively(cmdline, \"controller::bookmark\");\n\t\t\tv->pop_current_formaction();\n\t\t\treturn \"\";\n\t\t} else {\n\t\t\tchar * my_argv[4];\n\t\t\tmy_argv[0] = const_cast(\"/bin/sh\");\n\t\t\tmy_argv[1] = const_cast(\"-c\");\n\t\t\tmy_argv[2] = const_cast(cmdline.c_str());\n\t\t\tmy_argv[3] = nullptr;\n\t\t\treturn utils::run_program(my_argv, \"\");\n\t\t}\n\t} else {\n\t\treturn _(\"bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly.\");\n\t}\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-943", "cwe_name": "Improper Neutralization of Special Elements in Data Query Logic", "description": "The application generates a query intended to access or manipulate data in a data store such as a database, but it does not neutralize or incorrectly neutralizes special elements that can modify the intended logic of the query.", "url": "https://cwe.mitre.org/data/definitions/943.html", "label_name": "vulnerable"} {"code": "R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;\n\tattr->size = offset;\n\treturn attr;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "vulnerable"} {"code": "R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 curpos, offset = 0;\n\tRBinJavaLineNumberAttribute *lnattr;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;\n\tattr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.line_number_table_attr.line_number_table = r_list_newf (free);\n\n\tut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;\n\tRList *linenum_list = attr->info.line_number_table_attr.line_number_table;\n\tif (linenum_len > sz) {\n\t\tfree (attr);\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < linenum_len; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\t// printf (\"%llx %llx \\n\", curpos, sz);\n\t\t// XXX if (curpos + 8 >= sz) break;\n\t\tlnattr = R_NEW0 (RBinJavaLineNumberAttribute);\n\t\tif (!lnattr) {\n\t\t\tbreak;\n\t\t}\n\t\tlnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->file_offset = curpos;\n\t\tlnattr->size = 4;\n\t\tr_list_append (linenum_list, lnattr);\n\t}\n\tattr->size = offset;\n\treturn attr;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static float *get_window(vorb *f, int len)\n{\n len <<= 1;\n if (len == f->blocksize_0) return f->window[0];\n if (len == f->blocksize_1) return f->window[1];\n assert(0);\n return NULL;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)\n{\n int dy = y1 - y0;\n int adx = x1 - x0;\n int ady = abs(dy);\n int base;\n int x=x0,y=y0;\n int err = 0;\n int sy;\n\n#ifdef STB_VORBIS_DIVIDE_TABLE\n if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {\n if (dy < 0) {\n base = -integer_divide_table[ady][adx];\n sy = base-1;\n } else {\n base = integer_divide_table[ady][adx];\n sy = base+1;\n }\n } else {\n base = dy / adx;\n if (dy < 0)\n sy = base - 1;\n else\n sy = base+1;\n }\n#else\n base = dy / adx;\n if (dy < 0)\n sy = base - 1;\n else\n sy = base+1;\n#endif\n ady -= abs(base) * adx;\n if (x1 > n) x1 = n;\n if (x < x1) {\n LINE_OP(output[x], inverse_db_table[y]);\n for (++x; x < x1; ++x) {\n err += ady;\n if (err >= adx) {\n err -= adx;\n y += sy;\n } else\n y += base;\n LINE_OP(output[x], inverse_db_table[y]);\n }\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "void RemoteFsDevice::serviceAdded(const QString &name)\n{\n if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) {\n sub=tr(\"Available\");\n updateStatus();\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "void RemoteFsDevice::unmount()\n{\n if (details.isLocalFile()) {\n return;\n }\n\n if (!isConnected() || proc) {\n return;\n }\n\n if (messageSent) {\n return;\n }\n if (constSambaProtocol==details.url.scheme() || constSambaAvahiProtocol==details.url.scheme()) {\n mounter()->umount(mountPoint(details, false), getpid());\n setStatusMessage(tr(\"Disconnecting...\"));\n messageSent=true;\n return;\n }\n\n QString cmd;\n QStringList args;\n if (!details.isLocalFile()) {\n QString mp=mountPoint(details, false);\n if (!mp.isEmpty()) {\n cmd=Utils::findExe(\"fusermount\");\n if (!cmd.isEmpty()) {\n args << QLatin1String(\"-u\") << QLatin1String(\"-z\") << mp;\n } else {\n emit error(tr(\"\\\"fusermount\\\" is not installed!\"));\n }\n }\n }\n\n if (!cmd.isEmpty()) {\n setStatusMessage(tr(\"Disconnecting...\"));\n proc=new QProcess(this);\n proc->setProperty(\"unmount\", true);\n connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int)));\n proc->start(cmd, args, QIODevice::ReadOnly);\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "static inline bool isValid(const RemoteFsDevice::Details &d)\n{\n return d.isLocalFile() || RemoteFsDevice::constSshfsProtocol==d.url.scheme() ||\n RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme();\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " int Bind(const Node& node, int max_retry) override {\n receiver_ = zmq_socket(context_, ZMQ_ROUTER);\n CHECK(receiver_ != NULL)\n << \"create receiver socket failed: \" << zmq_strerror(errno);\n int local = GetEnv(\"DMLC_LOCAL\", 0);\n std::string addr = local ? \"ipc:///tmp/\" : \"tcp://*:\";\n int port = node.port;\n unsigned seed = static_cast(time(NULL)+port);\n for (int i = 0; i < max_retry+1; ++i) {\n auto address = addr + std::to_string(port);\n if (zmq_bind(receiver_, address.c_str()) == 0) break;\n if (i == max_retry) {\n port = -1;\n } else {\n port = 10000 + rand_r(&seed) % 40000;\n }\n }\n return port;\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": "int __fastcall BatchSettings(TConsole * Console, TProgramParams * Params)\r\n{\r\n int Result = RESULT_SUCCESS;\r\n try\r\n {\r\n std::unique_ptr Arguments(new TStringList());\r\n if (!DebugAlwaysTrue(Params->FindSwitch(L\"batchsettings\", Arguments.get())))\r\n {\r\n Abort();\r\n }\r\n else\r\n {\r\n if (Arguments->Count < 1)\r\n {\r\n throw Exception(LoadStr(BATCH_SET_NO_MASK));\r\n }\r\n else if (Arguments->Count < 2)\r\n {\r\n throw Exception(LoadStr(BATCH_SET_NO_SETTINGS));\r\n }\r\n else\r\n {\r\n TFileMasks Mask(Arguments->Strings[0]);\r\n Arguments->Delete(0);\r\n\r\n std::unique_ptr OptionsStorage(new TOptionsStorage(Arguments.get(), false));\r\n\r\n int Matches = 0;\r\n int Changes = 0;\r\n\r\n for (int Index = 0; Index < StoredSessions->Count; Index++)\r\n {\r\n TSessionData * Data = StoredSessions->Sessions[Index];\r\n if (!Data->IsWorkspace &&\r\n Mask.Matches(Data->Name, false, false))\r\n {\r\n Matches++;\r\n std::unique_ptr OriginalData(new TSessionData(L\"\"));\r\n OriginalData->CopyDataNoRecrypt(Data);\r\n Data->ApplyRawSettings(OptionsStorage.get());\r\n bool Changed = !OriginalData->IsSame(Data, false);\r\n if (Changed)\r\n {\r\n Changes++;\r\n }\r\n UnicodeString StateStr = LoadStr(Changed ? BATCH_SET_CHANGED : BATCH_SET_NOT_CHANGED);\r\n Console->PrintLine(FORMAT(L\"%s - %s\", (Data->Name, StateStr)));\r\n }\r\n }\r\n\r\n StoredSessions->Save(false, true); // explicit\r\n Console->PrintLine(FMTLOAD(BATCH_SET_SUMMARY, (Matches, Changes)));\r\n }\r\n }\r\n }\r\n catch (Exception & E)\r\n {\r\n Result = HandleException(Console, E);\r\n }\r\n\r\n Console->WaitBeforeExit();\r\n return Result;\r\n}\r", "label": 0, "programming_language": "C++", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "void RunOneAveragePoolTest(const PoolParams& params,\n const RuntimeShape& input_shape,\n const int8* input_data,\n const RuntimeShape& output_shape) {\n const int buffer_size = output_shape.FlatSize();\n std::vector optimized_averagePool_output(buffer_size);\n std::vector reference_averagePool_output(buffer_size);\n\n reference_integer_ops::AveragePool(params, input_shape, input_data,\n output_shape,\n reference_averagePool_output.data());\n optimized_integer_ops::AveragePool(params, input_shape, input_data,\n output_shape,\n optimized_averagePool_output.data());\n\n for (int i = 0; i < buffer_size; i++) {\n EXPECT_TRUE(reference_averagePool_output[i] ==\n optimized_averagePool_output[i]);\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-835", "cwe_name": "Loop with Unreachable Exit Condition ('Infinite Loop')", "description": "The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.", "url": "https://cwe.mitre.org/data/definitions/835.html", "label_name": "vulnerable"} {"code": "void AverageEvalQuantizedInt8(TfLiteContext* context, TfLiteNode* node,\n TfLitePoolParams* params, OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n int32_t activation_min;\n int32_t activation_max;\n\n (void)CalculateActivationRangeQuantized(context, params->activation, output,\n &activation_min, &activation_max);\n#define TF_LITE_AVERAGE_POOL(type) \\\n tflite::PoolParams op_params; \\\n op_params.stride_height = params->stride_height; \\\n op_params.stride_width = params->stride_width; \\\n op_params.filter_height = params->filter_height; \\\n op_params.filter_width = params->filter_width; \\\n op_params.padding_values.height = data->padding.height; \\\n op_params.padding_values.width = data->padding.width; \\\n op_params.quantized_activation_min = activation_min; \\\n op_params.quantized_activation_max = activation_max; \\\n type::AveragePool(op_params, GetTensorShape(input), \\\n GetTensorData(input), GetTensorShape(output), \\\n GetTensorData(output))\n if (kernel_type == kReference) {\n TF_LITE_AVERAGE_POOL(reference_integer_ops);\n } else {\n TF_LITE_AVERAGE_POOL(optimized_integer_ops);\n }\n#undef TF_LITE_AVERAGE_POOL\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-835", "cwe_name": "Loop with Unreachable Exit Condition ('Infinite Loop')", "description": "The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.", "url": "https://cwe.mitre.org/data/definitions/835.html", "label_name": "vulnerable"} {"code": " Status CheckInputs(Tensor group_size_t, Tensor group_key_t) {\n if (group_size_t.dims() > 0) {\n return errors::Internal(\n \"Unexpected dimensions on input group_size. \"\n \"It shoulbe a scalar, got tensor with shape \",\n group_size_t.shape().DebugString());\n }\n if (group_key_t.dims() > 0) {\n return errors::Internal(\"Unexpected dimensions on input group_key, got \",\n group_key_t.shape().DebugString());\n }\n\n auto group_size = group_size_t.unaligned_flat()(0);\n if (group_size <= 0) {\n return errors::InvalidArgument(\n \"group_size must be positive integer but got \", group_size);\n }\n return Status::OK();\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-416", "cwe_name": "Use After Free", "description": "Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.", "url": "https://cwe.mitre.org/data/definitions/416.html", "label_name": "vulnerable"} {"code": "void PrivateThreadPoolDatasetOp::MakeDatasetFromOptions(OpKernelContext* ctx,\n DatasetBase* input,\n int32_t num_threads,\n DatasetBase** output) {\n OP_REQUIRES(ctx, num_threads >= 0,\n errors::InvalidArgument(\"`num_threads` must be >= 0\"));\n *output = new Dataset(ctx,\n DatasetContext(DatasetContext::Params(\n {PrivateThreadPoolDatasetOp::kDatasetType,\n PrivateThreadPoolDatasetOp::kDatasetOp})),\n input, num_threads);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "vulnerable"} {"code": "Status OpLevelCostEstimator::PredictAvgPool(const OpContext& op_context,\n NodeCosts* node_costs) const {\n bool found_unknown_shapes = false;\n const auto& op_info = op_context.op_info;\n // x: op_info.inputs(0)\n ConvolutionDimensions dims = OpDimensionsFromInputs(\n op_info.inputs(0).shape(), op_info, &found_unknown_shapes);\n\n // kx * ky - 1 additions and 1 multiplication per output.\n int64_t ops = dims.batch * dims.ox * dims.oy * dims.oz * dims.kx * dims.ky;\n node_costs->num_compute_ops = ops;\n\n int64_t input_size;\n if (dims.ky >= dims.sy) {\n input_size = CalculateTensorSize(op_info.inputs(0), &found_unknown_shapes);\n } else { // dims.ky < dims.sy\n // vertical stride is larger than vertical kernel; assuming row-major\n // format, skip unnecessary rows (or read every kx rows per sy rows, as the\n // others are not used for output).\n const auto data_size = DataTypeSize(BaseType(op_info.inputs(0).dtype()));\n input_size = data_size * dims.batch * dims.ix * dims.ky * dims.oy * dims.iz;\n }\n node_costs->num_input_bytes_accessed = {input_size};\n\n const int64_t output_size =\n CalculateOutputSize(op_info, &found_unknown_shapes);\n node_costs->num_output_bytes_accessed = {output_size};\n node_costs->max_memory = output_size;\n\n if (found_unknown_shapes) {\n node_costs->inaccurate = true;\n node_costs->num_nodes_with_unknown_shapes = 1;\n }\n return Status::OK();\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-369", "cwe_name": "Divide By Zero", "description": "The product divides a value by zero.", "url": "https://cwe.mitre.org/data/definitions/369.html", "label_name": "vulnerable"} {"code": "TEST_F(QuantizedConv2DTest, OddPadding) {\n const int stride = 2;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 4;\n const int image_batch_count = 1;\n AddInputFromArray(\n TensorShape({image_batch_count, image_height, image_width, depth}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});\n const int filter_size = 3;\n const int filter_count = 1;\n AddInputFromArray(\n TensorShape({filter_size, filter_size, depth, filter_count}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width / stride;\n const int expected_height = (image_height * filter_count) / stride;\n Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,\n expected_width, filter_count}));\n test::FillValues(&expected, {348, 252, 274, 175});\n test::ExpectTensorEqual(expected, *GetOutput(0));\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": "TEST_F(QuantizedConv2DTest, Small32Bit) {\n const int stride = 1;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 3;\n const int image_batch_count = 1;\n AddInputFromArray(\n TensorShape({image_batch_count, image_height, image_width, depth}),\n {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120});\n const int filter_size = 3;\n const int filter_count = 1;\n AddInputFromArray(\n TensorShape({filter_size, filter_size, depth, filter_count}),\n {10, 40, 70, 20, 50, 80, 30, 60, 90});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width;\n const int expected_height = image_height * filter_count;\n Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,\n expected_width, filter_count}));\n test::FillValues(\n &expected, {10500, 15000, 18300, 9500, 23500, 31200, 35700, 17800, 18700,\n 23400, 26100, 12100});\n test::ExpectTensorEqual(expected, *GetOutput(0));\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "TfLiteRegistration AddOpRegistration() {\n TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};\n\n reg.custom_name = \"my_add\";\n reg.builtin_code = tflite::BuiltinOperator_CUSTOM;\n\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n // Set output size to input size\n const TfLiteTensor* input1 = GetInput(context, node, 0);\n const TfLiteTensor* input2 = GetInput(context, node, 1);\n TfLiteTensor* output = GetOutput(context, node, 0);\n\n TF_LITE_ENSURE_EQ(context, input1->dims->size, input2->dims->size);\n for (int i = 0; i < input1->dims->size; ++i) {\n TF_LITE_ENSURE_EQ(context, input1->dims->data[i], input2->dims->data[i]);\n }\n\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(\n context, output, TfLiteIntArrayCopy(input1->dims)));\n return kTfLiteOk;\n };\n\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n // Copy input data to output data.\n const TfLiteTensor* a0 = GetInput(context, node, 0);\n TF_LITE_ENSURE(context, a0);\n TF_LITE_ENSURE(context, a0->data.f);\n const TfLiteTensor* a1 = GetInput(context, node, 1);\n TF_LITE_ENSURE(context, a1);\n TF_LITE_ENSURE(context, a1->data.f);\n TfLiteTensor* out = GetOutput(context, node, 0);\n TF_LITE_ENSURE(context, out);\n TF_LITE_ENSURE(context, out->data.f);\n int num = a0->dims->data[0];\n for (int i = 0; i < num; i++) {\n out->data.f[i] = a0->data.f[i] + a1->data.f[i];\n }\n return kTfLiteOk;\n };\n return reg;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "bool IsConvolutionOpSupported(const TfLiteRegistration* registration,\n const TfLiteNode* node, TfLiteContext* context) {\n if (node->builtin_data == nullptr) return false;\n\n TfLiteFusedActivation activation;\n\n if (registration->builtin_code == kTfLiteBuiltinConv2d) {\n const auto* conv_params =\n reinterpret_cast(node->builtin_data);\n activation = conv_params->activation;\n } else if (registration->builtin_code == kTfLiteBuiltinDepthwiseConv2d) {\n const auto* depthwise_conv_params =\n reinterpret_cast(node->builtin_data);\n activation = depthwise_conv_params->activation;\n } else if (registration->builtin_code == kTfLiteBuiltinTransposeConv) {\n activation = kTfLiteActNone;\n } else {\n TF_LITE_KERNEL_LOG(\n context,\n \"Invalid op: op must be Conv2D, DepthwiseConv2D or TransposeConv.\");\n return false;\n }\n\n if (activation == kTfLiteActSignBit) {\n return false;\n }\n\n const int kOutputShapeTensor = 0; // Only used for TransposeConv\n const int kWeightTensor = 1;\n const int kBiasTensor = 2; // Only used for non-TransposeConv\n const TfLiteTensor* weights = GetInput(context, node, kWeightTensor);\n const int max_kernel_size = 16384;\n if (!IsConstantTensor(weights)) {\n return false;\n }\n if (weights->dims->data[1] > max_kernel_size ||\n weights->dims->data[2] > max_kernel_size) {\n return false;\n }\n if (registration->builtin_code == kTfLiteBuiltinTransposeConv) {\n if (!IsConstantTensor(GetInput(context, node, kOutputShapeTensor))) {\n return false;\n }\n } else {\n if (node->inputs->size >= kBiasTensor &&\n !IsConstantTensor(GetInput(context, node, kBiasTensor))) {\n return false;\n }\n }\n\n return true;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "bool IsConvolutionOpSupported(const TfLiteRegistration* registration,\n const TfLiteNode* node, TfLiteContext* context) {\n if (node->builtin_data == nullptr) return false;\n\n TfLiteFusedActivation activation;\n\n if (registration->builtin_code == kTfLiteBuiltinConv2d) {\n const auto* conv_params =\n reinterpret_cast(node->builtin_data);\n activation = conv_params->activation;\n } else if (registration->builtin_code == kTfLiteBuiltinDepthwiseConv2d) {\n const auto* depthwise_conv_params =\n reinterpret_cast(node->builtin_data);\n activation = depthwise_conv_params->activation;\n } else if (registration->builtin_code == kTfLiteBuiltinTransposeConv) {\n activation = kTfLiteActNone;\n } else {\n TF_LITE_KERNEL_LOG(\n context,\n \"Invalid op: op must be Conv2D, DepthwiseConv2D or TransposeConv.\");\n return false;\n }\n\n if (activation == kTfLiteActSignBit) {\n return false;\n }\n\n const int kOutputShapeTensor = 0; // Only used for TransposeConv\n const int kWeightTensor = 1;\n const int kBiasTensor = 2; // Only used for non-TransposeConv\n const TfLiteTensor* weights = GetInput(context, node, kWeightTensor);\n const int max_kernel_size = 16384;\n if (!IsConstantTensor(weights)) {\n return false;\n }\n if (weights->dims->data[1] > max_kernel_size ||\n weights->dims->data[2] > max_kernel_size) {\n return false;\n }\n if (registration->builtin_code == kTfLiteBuiltinTransposeConv) {\n if (!IsConstantTensor(GetInput(context, node, kOutputShapeTensor))) {\n return false;\n }\n } else {\n if (node->inputs->size >= kBiasTensor &&\n !IsConstantTensor(GetInput(context, node, kBiasTensor))) {\n return false;\n }\n }\n\n return true;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "bool IsFullyConnectedOpSupported(const TfLiteRegistration* registration,\n const TfLiteNode* node,\n TfLiteContext* context) {\n if (node->builtin_data == nullptr) return false;\n const auto* fc_params =\n reinterpret_cast(node->builtin_data);\n const int kInput = 0;\n const int kWeights = 1;\n const int kBias = 2;\n\n if (fc_params->weights_format != kTfLiteFullyConnectedWeightsFormatDefault) {\n return false;\n }\n const TfLiteTensor* input = GetInput(context, node, kInput);\n const TfLiteTensor* weights = GetInput(context, node, kWeights);\n\n if (!IsFloatType(input->type)) {\n return false;\n }\n if (!IsFloatType(weights->type) || !IsConstantTensor(weights)) {\n return false;\n }\n // Core ML 2 only supports single-batch fully connected layer, thus dimensions\n // except the last one should be 1.\n if (input->dims->data[input->dims->size - 1] != NumElements(input)) {\n return false;\n }\n\n if (node->inputs->size > 2) {\n const TfLiteTensor* bias = GetInput(context, node, kBias);\n if (!IsFloatType(bias->type) || !IsConstantTensor(bias)) {\n return false;\n }\n }\n\n TfLiteFusedActivation activation = fc_params->activation;\n if (activation == kTfLiteActSignBit) {\n return false;\n }\n return true;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "bool IsPadOpSupported(const TfLiteRegistration* registration,\n const TfLiteNode* node, TfLiteContext* context) {\n // padding is d x 2 tensor, where d is the dimension of input.\n const TfLiteTensor* padding = GetInput(context, node, 1);\n if (!IsConstantTensor(padding)) {\n TF_LITE_KERNEL_LOG(context,\n \"%s: Only constant padding is supported for PAD.\",\n padding->name);\n return false;\n }\n if (padding->dims->data[0] != 4 || padding->dims->data[1] != 2) {\n TF_LITE_KERNEL_LOG(context, \"%s: Only 4D inputs are supported for PAD.\",\n padding->name);\n return false;\n }\n const int32_t* padding_data = GetTensorData(padding);\n if (!(padding_data[0] == 0 && padding_data[1] == 0)) {\n TF_LITE_KERNEL_LOG(\n context, \"%s: Padding for batch dimension is not supported in PAD.\",\n padding->name);\n return false;\n }\n\n if (!(padding_data[6] == 0 && padding_data[7] == 0)) {\n TF_LITE_KERNEL_LOG(\n context, \"%s: Padding for channel dimension is not supported in PAD.\",\n padding->name);\n return false;\n }\n return true;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* data =\n reinterpret_cast(node->user_data);\n FrontendReset(data->state);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (data->out_float) {\n GenerateFeatures(data, input, output);\n } else {\n GenerateFeatures(data, input, output);\n }\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus PrepareHashtable(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 0);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n TF_LITE_ENSURE(context, node->user_data != nullptr);\n const auto* params =\n reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE(context, !params->table_name.empty());\n TF_LITE_ENSURE(context, (params->key_dtype == kTfLiteInt64 &&\n params->value_dtype == kTfLiteString) ||\n (params->key_dtype == kTfLiteString &&\n params->value_dtype == kTfLiteInt64));\n\n TfLiteTensor* resource_handle_tensor =\n GetOutput(context, node, kResourceHandleTensor);\n TF_LITE_ENSURE(context, resource_handle_tensor != nullptr);\n TF_LITE_ENSURE_EQ(context, resource_handle_tensor->type, kTfLiteInt32);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);\n outputSize->data[0] = 1;\n return context->ResizeTensor(context, resource_handle_tensor, outputSize);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus PrepareHashtableImport(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputResourceIdTensor);\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1);\n\n const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor);\n const TfLiteTensor* value_tensor = GetInput(context, node, kValueTensor);\n TF_LITE_ENSURE(context, (key_tensor->type == kTfLiteInt64 &&\n value_tensor->type == kTfLiteString) ||\n (key_tensor->type == kTfLiteString &&\n value_tensor->type == kTfLiteInt64));\n // TODO(b/144731295): Tensorflow lookup ops support 1-D vector in storing\n // values.\n TF_LITE_ENSURE(context, HaveSameShapes(key_tensor, value_tensor));\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus SimpleStatefulOp::Prepare(TfLiteContext* context,\n TfLiteNode* node) {\n OpData* data = reinterpret_cast(node->user_data);\n\n // Make sure that the input is in uint8_t with at least 1 data entry.\n const TfLiteTensor* input = tflite::GetInput(context, node, kInputTensor);\n if (input->type != kTfLiteUInt8) return kTfLiteError;\n if (NumElements(input->dims) == 0) return kTfLiteError;\n\n // Allocate a temporary buffer with the same size of input for sorting.\n TF_LITE_ENSURE_STATUS(context->RequestScratchBufferInArena(\n context, sizeof(uint8_t) * NumElements(input->dims),\n &data->sorting_buffer));\n // We can interleave scratch / persistent buffer allocation.\n data->invoke_count = reinterpret_cast(\n context->AllocatePersistentBuffer(context, sizeof(int)));\n *data->invoke_count = 0;\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n TfLiteType output_type = GetOutput(context, node, kOutputTensor)->type;\n\n switch (output_type) { // Already know in/outtypes are same.\n case kTfLiteFloat32:\n EvalUnquantized(context, node);\n break;\n case kTfLiteInt32:\n EvalUnquantized(context, node);\n break;\n case kTfLiteUInt8:\n EvalQuantizedUInt8(context, node);\n break;\n case kTfLiteInt8:\n EvalUnquantized(context, node);\n break;\n case kTfLiteInt64:\n EvalUnquantized(context, node);\n break;\n\n default:\n TF_LITE_KERNEL_LOG(\n context, \"Op Concatenation does not currently support Type '%s'.\",\n TfLiteTypeGetName(output_type));\n return kTfLiteError;\n }\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus LeakyReluEval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const auto* params =\n reinterpret_cast(node->builtin_data);\n const LeakyReluOpData* data =\n reinterpret_cast(node->user_data);\n\n LeakyReluParams op_params;\n switch (input->type) {\n case kTfLiteFloat32: {\n op_params.alpha = params->alpha;\n optimized_ops::LeakyRelu(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n return kTfLiteOk;\n } break;\n case kTfLiteUInt8: {\n QuantizeLeakyRelu(input, output, data);\n return kTfLiteOk;\n } break;\n case kTfLiteInt8: {\n QuantizeLeakyRelu(input, output, data);\n return kTfLiteOk;\n } break;\n case kTfLiteInt16: {\n QuantizeLeakyRelu(input, output, data);\n return kTfLiteOk;\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context,\n \"Only float32, int8, int16 and uint8 is supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus LeakyReluPrepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n LeakyReluOpData* data = reinterpret_cast(node->user_data);\n\n if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n const auto* params =\n reinterpret_cast(node->builtin_data);\n\n double alpha_multiplier =\n input->params.scale * params->alpha / output->params.scale;\n QuantizeMultiplier(alpha_multiplier, &data->output_multiplier_alpha,\n &data->output_shift_alpha);\n double identity_multiplier = input->params.scale / output->params.scale;\n QuantizeMultiplier(identity_multiplier, &data->output_multiplier_identity,\n &data->output_shift_identity);\n }\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus ReluEval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const ReluOpData* data = reinterpret_cast(node->user_data);\n switch (input->type) {\n case kTfLiteFloat32: {\n optimized_ops::Relu(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } break;\n // TODO(renjieliu): We may revisit the quantization calculation logic,\n // the unbounded upper limit is actually hard to quantize.\n case kTfLiteUInt8: {\n QuantizedReluX(0.0f, std::numeric_limits::infinity(),\n input, output, data);\n } break;\n case kTfLiteInt8: {\n QuantizedReluX(0.0f, std::numeric_limits::infinity(),\n input, output, data);\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context, \"Only float32 & int8/uint8 is supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n int num_inputs = NumInputs(node);\n TF_LITE_ENSURE(context, num_inputs >= 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n output->type = input1->type;\n\n // Check that all input tensors have the same shape and type.\n for (int i = kInputTensor1 + 1; i < num_inputs; ++i) {\n const TfLiteTensor* input = GetInput(context, node, i);\n TF_LITE_ENSURE(context, HaveSameShapes(input1, input));\n TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input->type);\n }\n\n // Use the first input node's dimension to be the dimension of the output\n // node.\n TfLiteIntArray* input1_dims = input1->dims;\n TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input1_dims);\n return context->ResizeTensor(context, output, output_dims);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n // TODO(b/137042749): TFLite infrastructure (converter, delegate) doesn't\n // fully support 0-output ops yet. Currently it works if we manually crfat\n // a TFLite graph that contains variable ops. Note:\n // * The TFLite Converter need to be changed to be able to produce an op\n // with 0 output.\n // * The delegation code need to be changed to handle 0 output ops. However\n // everything still works fine when variable ops aren't used.\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputVariableId);\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n Subgraph* subgraph = reinterpret_cast(context->impl_);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputVariableId);\n const TfLiteTensor* input_value_tensor = GetInput(context, node, kInputValue);\n\n int resource_id = input_resource_id_tensor->data.i32[0];\n auto& resources = subgraph->resources();\n resource::CreateResourceVariableIfNotAvailable(&resources, resource_id);\n auto* variable = resource::GetResourceVariable(&resources, resource_id);\n TF_LITE_ENSURE(context, variable != nullptr);\n variable->AssignFrom(input_value_tensor);\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // TODO(ahentz): these two checks would make the new implementation\n // incompatible with some existing models, where params is not specified. It\n // is OK not to have them because toco would have set input and output types\n // to match the parameters.\n // auto* params = reinterpret_cast(node->builtin_data);\n // TF_LITE_ENSURE_EQ(context, input->type, params->in_data_type);\n // TF_LITE_ENSURE_EQ(context, output->type, params->out_data_type);\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n const int num_elements = NumElements(input);\n TF_LITE_ENSURE_EQ(context, num_elements, NumElements(output));\n switch (input->type) {\n case kTfLiteInt64:\n return copyToTensor(context, input->data.i64, output, num_elements);\n case kTfLiteInt32:\n return copyToTensor(context, input->data.i32, output, num_elements);\n case kTfLiteUInt8:\n return copyToTensor(context, input->data.uint8, output, num_elements);\n case kTfLiteFloat32:\n return copyToTensor(context, GetTensorData(input), output,\n num_elements);\n case kTfLiteBool:\n return copyToTensor(context, input->data.b, output, num_elements);\n case kTfLiteComplex64:\n return copyToTensor(\n context, reinterpret_cast*>(input->data.c64),\n output, num_elements);\n default:\n // Unsupported type.\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, \"Cast\");\n }\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus ComparisonPrepareCommon(TfLiteContext* context, TfLiteNode* node,\n bool is_string_allowed) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // Don't support string.\n if (!is_string_allowed) {\n TF_LITE_ENSURE(context, input1->type != kTfLiteString);\n }\n // Currently only support tensors have the same type.\n TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);\n output->type = kTfLiteBool;\n\n bool requires_broadcast = !HaveSameShapes(input1, input2);\n\n TfLiteIntArray* output_size = nullptr;\n if (requires_broadcast) {\n TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(\n context, input1, input2, &output_size));\n } else {\n output_size = TfLiteIntArrayCopy(input1->dims);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n if (!is_supported_type(input->type)) {\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, op_name);\n }\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* lookup = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(lookup), 1);\n TF_LITE_ENSURE_EQ(context, lookup->type, kTfLiteInt32);\n\n const TfLiteTensor* value = GetInput(context, node, 1);\n TF_LITE_ENSURE(context, NumDimensions(value) >= 2);\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(NumDimensions(value));\n\n outputSize->data[0] = SizeOfDimension(lookup, 0);\n outputSize->data[1] = SizeOfDimension(value, 1);\n for (int i = 2; i < NumDimensions(value); i++) {\n outputSize->data[i] = SizeOfDimension(value, i);\n }\n return context->ResizeTensor(context, output, outputSize);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* lookup = GetInput(context, node, 0);\n const TfLiteTensor* value = GetInput(context, node, 1);\n TfLiteTensor* output = GetOutput(context, node, 0);\n switch (value->type) {\n case kTfLiteFloat32:\n return EvalSimple(context, node, lookup, value, output);\n case kTfLiteUInt8:\n case kTfLiteInt8:\n if (output->type == kTfLiteFloat32) {\n return EvalHybrid(context, node, lookup, value, output);\n } else {\n return EvalSimple(context, node, lookup, value, output);\n }\n default:\n context->ReportError(context, \"Type not currently supported.\");\n return kTfLiteError;\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* value = GetInput(context, node, kValueTensor);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (IsDynamicTensor(output)) {\n const TfLiteTensor* dims = GetInput(context, node, kDimsTensor);\n TF_LITE_ENSURE_OK(context, ResizeOutput(context, dims, output));\n }\n#define TF_LITE_FILL(data_type) \\\n reference_ops::Fill(GetTensorShape(value), GetTensorData(value), \\\n GetTensorShape(output), \\\n GetTensorData(output))\n switch (output->type) {\n case kTfLiteInt32:\n TF_LITE_FILL(int32_t);\n break;\n case kTfLiteInt64:\n TF_LITE_FILL(int64_t);\n break;\n case kTfLiteFloat32:\n TF_LITE_FILL(float);\n break;\n case kTfLiteBool:\n TF_LITE_FILL(bool);\n break;\n case kTfLiteString:\n FillString(value, output);\n break;\n default:\n context->ReportError(\n context,\n \"Fill only currently supports int32, int64, float32, bool, string \"\n \"for input 1, got %d.\",\n value->type);\n return kTfLiteError;\n }\n#undef TF_LITE_FILL\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);\n output->type = input->type;\n TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);\n return context->ResizeTensor(context, output, output_size);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (output->type == kTfLiteFloat32) {\n#define TF_LITE_LOCAL_RESPONSE_NORM(type) \\\n tflite::LocalResponseNormalizationParams op_params; \\\n op_params.range = params->radius; \\\n op_params.bias = params->bias; \\\n op_params.alpha = params->alpha; \\\n op_params.beta = params->beta; \\\n type::LocalResponseNormalization( \\\n op_params, GetTensorShape(input), GetTensorData(input), \\\n GetTensorShape(output), GetTensorData(output))\n if (kernel_type == kReference) {\n TF_LITE_LOCAL_RESPONSE_NORM(reference_ops);\n }\n if (kernel_type == kGenericOptimized) {\n TF_LITE_LOCAL_RESPONSE_NORM(optimized_ops);\n }\n#undef TF_LITE_LOCAL_RESPONSE_NORM\n } else {\n context->ReportError(context, \"Output type is %d, requires float.\",\n output->type);\n return kTfLiteError;\n }\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Resize(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n TF_LITE_ENSURE(context, NumInputs(node) == 2 || NumInputs(node) == 3);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* hash = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(hash), 2);\n // Support up to 32 bits.\n TF_LITE_ENSURE(context, SizeOfDimension(hash, 1) <= 32);\n\n const TfLiteTensor* input = GetInput(context, node, 1);\n TF_LITE_ENSURE(context, NumDimensions(input) >= 1);\n\n if (NumInputs(node) == 3) {\n const TfLiteTensor* weight = GetInput(context, node, 2);\n TF_LITE_ENSURE_EQ(context, NumDimensions(weight), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(weight, 0),\n SizeOfDimension(input, 0));\n }\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);\n switch (params->type) {\n case kTfLiteLshProjectionSparse:\n outputSize->data[0] = SizeOfDimension(hash, 0);\n break;\n case kTfLiteLshProjectionDense:\n outputSize->data[0] = SizeOfDimension(hash, 0) * SizeOfDimension(hash, 1);\n break;\n default:\n return kTfLiteError;\n }\n return context->ResizeTensor(context, output, outputSize);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* diag = GetInput(context, node, kDiagonalTensor);\n FillDiagHelper(input, diag, output);\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteIntArray* input_dims = input->dims;\n int input_dims_size = input_dims->size;\n TF_LITE_ENSURE(context, input_dims_size >= 2);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(input_dims_size);\n for (int i = 0; i < input_dims_size; i++) {\n output_shape->data[i] = input_dims->data[i];\n }\n\n // Resize the output tensor to the same size as the input tensor.\n output->type = input->type;\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_shape));\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) {\n EvalMul(context, node, params, data, input1, input2, output);\n } else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_OK(\n context, EvalQuantized(context, node, params, data, input1,\n input2, output));\n } else {\n context->ReportError(context,\n \"Mul only supports FLOAT32, INT32 and quantized UINT8,\"\n \" INT8 and INT16 now, got %d.\",\n output->type);\n return kTfLiteError;\n }\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);\n\n const bool requires_broadcast = !HaveSameShapes(input1, input2);\n\n TfLiteIntArray* output_size = nullptr;\n if (requires_broadcast) {\n TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(\n context, input1, input2, &output_size));\n } else {\n output_size = TfLiteIntArrayCopy(input1->dims);\n }\n\n if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(\n context, params->activation, output, &data->output_activation_min,\n &data->output_activation_max));\n double real_multiplier =\n input1->params.scale * input2->params.scale / output->params.scale;\n QuantizeMultiplier(real_multiplier, &data->output_multiplier,\n &data->output_shift);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n switch (input->type) {\n case kTfLiteInt64:\n reference_ops::Negate(\n GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n break;\n case kTfLiteInt32:\n reference_ops::Negate(\n GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n break;\n case kTfLiteFloat32:\n reference_ops::Negate(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output),\n GetTensorData(output));\n break;\n default:\n context->ReportError(\n context,\n \"Neg only currently supports int64, int32, and float32, got %d.\",\n input->type);\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n const TfLiteTensor* input = GetInput(context, node, 0);\n switch (input->type) { // Already know in/out types are same.\n case kTfLiteFloat32:\n AverageEvalFloat(context, node, params, data, input, output);\n break;\n case kTfLiteUInt8:\n AverageEvalQuantizedUint8(context, node, params, data, input,\n output);\n break;\n case kTfLiteInt8:\n AverageEvalQuantizedInt8(context, node, params, data, input,\n output);\n break;\n case kTfLiteInt16:\n AverageEvalQuantizedInt16(context, node, params, data, input,\n output);\n break;\n default:\n TF_LITE_KERNEL_LOG(context, \"Type %s not currently supported.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus L2Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n const TfLiteTensor* input = GetInput(context, node, 0);\n switch (input->type) { // Already know in/out types are same.\n case kTfLiteFloat32:\n L2EvalFloat(context, node, params, data, input, output);\n break;\n case kTfLiteUInt8:\n // We don't have a quantized implementation, so just fall through to the\n // 'default' case.\n default:\n context->ReportError(context, \"Type %d not currently supported.\",\n input->type);\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "inline bool ShapeIsVector(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* shape = GetInput(context, node, kShapeTensor);\n return (shape->dims->size == 1 && shape->type == kTfLiteInt32);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n optimized_ops::Round(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n optimized_ops::Round(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n auto* params = reinterpret_cast(node->builtin_data);\n switch (params->out_type) {\n case kTfLiteInt32:\n output->type = kTfLiteInt32;\n break;\n case kTfLiteInt64:\n output->type = kTfLiteInt64;\n break;\n default:\n context->ReportError(context, \"Unknown shape output data type: %d\",\n params->out_type);\n return kTfLiteError;\n }\n\n // By design, the input shape is always known at the time of Prepare, even\n // if the preceding op that generates |input| is dynamic. Thus, we can\n // always compute the shape immediately, without waiting for Eval.\n SetTensorToPersistentRo(output);\n\n // Shape always produces a 1-dimensional output tensor, where each output\n // element is the length of the corresponding input tensor's dimension.\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(1);\n output_size->data[0] = NumDimensions(input);\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_size));\n\n TFLITE_DCHECK_EQ(NumDimensions(output), 1);\n TFLITE_DCHECK_EQ(SizeOfDimension(output, 0), NumDimensions(input));\n\n // Immediately propagate the known shape to the output tensor. This allows\n // downstream ops that rely on the value to use it during prepare.\n switch (output->type) {\n case kTfLiteInt32:\n ExtractShape(input, GetTensorData(output));\n break;\n case kTfLiteInt64:\n ExtractShape(input, GetTensorData(output));\n break;\n default:\n return kTfLiteError;\n }\n\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n\n auto data_type = output->type;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||\n data_type == kTfLiteInt64);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n const int block_size = params->block_size;\n const int input_height = input->dims->data[1];\n const int input_width = input->dims->data[2];\n int output_height = input_height / block_size;\n int output_width = input_width / block_size;\n\n TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size);\n TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size);\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = input->dims->data[0];\n output_size->data[1] = output_height;\n output_size->data[2] = output_width;\n output_size->data[3] = input->dims->data[3] * block_size * block_size;\n\n return context->ResizeTensor(context, output, output_size);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n OpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);\n output->type = input2->type;\n\n data->requires_broadcast = !HaveSameShapes(input1, input2);\n\n TfLiteIntArray* output_size = nullptr;\n if (data->requires_broadcast) {\n TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(\n context, input1, input2, &output_size));\n } else {\n output_size = TfLiteIntArrayCopy(input1->dims);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);\n\n const int num_dimensions = NumDimensions(input);\n const int num_multipliers = NumElements(multipliers);\n TF_LITE_ENSURE_EQ(context, num_dimensions, num_multipliers);\n switch (multipliers->type) {\n case kTfLiteInt32:\n return context->ResizeTensor(\n context, output,\n MultiplyShapeDims(*input->dims, multipliers,\n num_dimensions));\n case kTfLiteInt64:\n return context->ResizeTensor(\n context, output,\n MultiplyShapeDims(*input->dims, multipliers,\n num_dimensions));\n default:\n context->ReportError(\n context, \"Multipliers of type '%s' are not supported by tile.\",\n TfLiteTypeGetName(multipliers->type));\n return kTfLiteError;\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TfLiteStatus EvalImpl(TfLiteContext* context, const TfLiteTensor* input,\n TfLiteNode* node) {\n // Map from value, to index in the unique elements vector.\n // Note that we prefer to use map than unordered_map as it showed less\n // increase in the binary size.\n std::map unique_values;\n TfLiteTensor* output_indexes = GetOutput(context, node, 1);\n std::vector output_values;\n I* indexes = GetTensorData(output_indexes);\n const T* data = GetTensorData(input);\n const int num_elements = NumElements(input);\n\n for (int i = 0; i < num_elements; ++i) {\n const auto element_it = unique_values.find(data[i]);\n if (element_it != unique_values.end()) {\n indexes[i] = element_it->second;\n } else {\n const int unique_index = unique_values.size();\n unique_values[data[i]] = unique_index;\n indexes[i] = unique_index;\n output_values.push_back(data[i]);\n }\n }\n // Allocate output tensor.\n TfLiteTensor* unique_output = GetOutput(context, node, 0);\n std::unique_ptr shape(\n TfLiteIntArrayCreate(NumDimensions(input)), TfLiteIntArrayFree);\n shape->data[0] = unique_values.size();\n TF_LITE_ENSURE_STATUS(\n context->ResizeTensor(context, unique_output, shape.release()));\n // Set the values in the output tensor.\n T* output_unique_values = GetTensorData(unique_output);\n for (int i = 0; i < output_values.size(); ++i) {\n output_unique_values[i] = output_values[i];\n }\n return kTfLiteOk;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": " void Compute(OpKernelContext* ctx) override {\n const Tensor& val = ctx->input(0);\n int64 id = ctx->session_state()->GetNewId();\n TensorStore::TensorAndKey tk{val, id, requested_device()};\n OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));\n\n Tensor* handle = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));\n if (ctx->expected_output_dtype(0) == DT_RESOURCE) {\n ResourceHandle resource_handle = MakeResourceHandle(\n ctx, SessionState::kTensorHandleResourceTypeName,\n tk.GetHandle(name()));\n resource_handle.set_maybe_type_name(\n SessionState::kTensorHandleResourceTypeName);\n handle->scalar()() = resource_handle;\n } else {\n // Legacy behavior in V1.\n handle->flat().setConstant(tk.GetHandle(name()));\n }\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": " QUInt16() {}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-908", "cwe_name": "Use of Uninitialized Resource", "description": "The software uses or accesses a resource that has not been initialized.", "url": "https://cwe.mitre.org/data/definitions/908.html", "label_name": "vulnerable"} {"code": " QUInt8() {}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-908", "cwe_name": "Use of Uninitialized Resource", "description": "The software uses or accesses a resource that has not been initialized.", "url": "https://cwe.mitre.org/data/definitions/908.html", "label_name": "vulnerable"} {"code": " explicit DataFormatDimMapOp(OpKernelConstruction* context)\n : OpKernel(context) {\n string src_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"src_format\", &src_format));\n string dst_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"dst_format\", &dst_format));\n OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,\n errors::InvalidArgument(strings::StrCat(\n \"Source format must of length 4 or 5, received \"\n \"src_format = \",\n src_format)));\n OP_REQUIRES(\n context, dst_format.size() == 4 || dst_format.size() == 5,\n errors::InvalidArgument(strings::StrCat(\n \"Destination format must of length 4 or 5, received dst_format = \",\n dst_format)));\n dst_idx_ = Tensor(DT_INT32, {static_cast(src_format.size())});\n for (int i = 0; i < src_format.size(); ++i) {\n for (int j = 0; j < dst_format.size(); ++j) {\n if (dst_format[j] == src_format[i]) {\n dst_idx_.vec()(i) = j;\n break;\n }\n }\n }\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": " void Compute(OpKernelContext* ctx) override {\n const Tensor& handle = ctx->input(0);\n const string& name = handle.scalar()();\n OP_REQUIRES_OK(ctx, ctx->session_state()->DeleteTensor(name));\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": " void CreateNgrams(const tstring* data, tstring* output, int num_ngrams,\n int ngram_width) const {\n for (int ngram_index = 0; ngram_index < num_ngrams; ++ngram_index) {\n int pad_width = get_pad_width(ngram_width);\n int left_padding = std::max(0, pad_width - ngram_index);\n int right_padding =\n std::max(0, pad_width - (num_ngrams - (ngram_index + 1)));\n int num_tokens = ngram_width - (left_padding + right_padding);\n int data_start_index = left_padding > 0 ? 0 : ngram_index - pad_width;\n\n // Calculate the total expected size of the ngram so we can reserve the\n // correct amount of space in the string.\n int ngram_size = 0;\n // Size of the left padding.\n ngram_size += left_padding * left_pad_.length();\n // Size of the tokens.\n for (int n = 0; n < num_tokens; ++n) {\n ngram_size += data[data_start_index + n].length();\n }\n // Size of the right padding.\n ngram_size += right_padding * right_pad_.length();\n // Size of the separators.\n int num_separators = left_padding + right_padding + num_tokens - 1;\n ngram_size += num_separators * separator_.length();\n\n // Build the ngram.\n tstring* ngram = &output[ngram_index];\n ngram->reserve(ngram_size);\n for (int n = 0; n < left_padding; ++n) {\n ngram->append(left_pad_);\n ngram->append(separator_);\n }\n for (int n = 0; n < num_tokens - 1; ++n) {\n ngram->append(data[data_start_index + n]);\n ngram->append(separator_);\n }\n ngram->append(data[data_start_index + num_tokens - 1]);\n for (int n = 0; n < right_padding; ++n) {\n ngram->append(separator_);\n ngram->append(right_pad_);\n }\n\n // In debug mode only: validate that we've reserved enough space for the\n // ngram.\n DCHECK_EQ(ngram_size, ngram->size());\n }\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": "\t\tvoid CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)\n\t\t{\n\t\t\tstd::string idx = request::findValue(&req, \"idx\");\n\t\t\tif (idx == \"\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstd::vector > result;\n\t\t\tresult = m_sql.safe_queryBlob(\"SELECT Image FROM Floorplans WHERE ID=%s\", idx.c_str());\n\t\t\tif (result.empty())\n\t\t\t\treturn;\n\t\t\treply::set_content(&rep, result[0][0].begin(), result[0][0].end());\n\t\t\tstd::string oname = \"floorplan\";\n\t\t\tif (result[0][0].size() > 10)\n\t\t\t{\n\t\t\t\tif (result[0][0][0] == 'P')\n\t\t\t\t\toname += \".png\";\n\t\t\t\telse if (result[0][0][0] == -1)\n\t\t\t\t\toname += \".jpg\";\n\t\t\t\telse if (result[0][0][0] == 'B')\n\t\t\t\t\toname += \".bmp\";\n\t\t\t\telse if (result[0][0][0] == 'G')\n\t\t\t\t\toname += \".gif\";\n\t\t\t}\n\t\t\treply::add_header_attachment(&rep, oname);\n\t\t}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": "void CarbonProtocolReader::skip(const FieldType ft) {\n switch (ft) {\n case FieldType::True:\n case FieldType::False: {\n break;\n }\n case FieldType::Int8: {\n readRaw();\n break;\n }\n case FieldType::Int16: {\n readRaw();\n break;\n }\n case FieldType::Int32: {\n readRaw();\n break;\n }\n case FieldType::Int64: {\n readRaw();\n break;\n }\n case FieldType::Double: {\n readRaw();\n break;\n }\n case FieldType::Float: {\n readRaw();\n break;\n }\n case FieldType::Binary: {\n readRaw();\n break;\n }\n case FieldType::List: {\n skipLinearContainer();\n break;\n }\n case FieldType::Struct: {\n readStructBegin();\n while (true) {\n const auto fieldType = readFieldHeader().first;\n if (fieldType == FieldType::Stop) {\n break;\n }\n skip(fieldType);\n }\n readStructEnd();\n break;\n }\n case FieldType::Set: {\n skipLinearContainer();\n break;\n }\n case FieldType::Map: {\n skipKVContainer();\n break;\n }\n default: { break; }\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-674", "cwe_name": "Uncontrolled Recursion", "description": "The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.", "url": "https://cwe.mitre.org/data/definitions/674.html", "label_name": "vulnerable"} {"code": "folly::Optional EncryptedReadRecordLayer::read(\n folly::IOBufQueue& buf) {\n auto decryptedBuf = getDecryptedBuf(buf);\n if (!decryptedBuf) {\n return folly::none;\n }\n\n TLSMessage msg;\n // Iterate over the buffers while trying to find\n // the first non-zero octet. This is much faster than\n // first iterating and then trimming.\n auto currentBuf = decryptedBuf->get();\n bool nonZeroFound = false;\n do {\n currentBuf = currentBuf->prev();\n size_t i = currentBuf->length();\n while (i > 0 && !nonZeroFound) {\n nonZeroFound = (currentBuf->data()[i - 1] != 0);\n i--;\n }\n if (nonZeroFound) {\n msg.type = static_cast(currentBuf->data()[i]);\n }\n currentBuf->trimEnd(currentBuf->length() - i);\n } while (!nonZeroFound && currentBuf != decryptedBuf->get());\n if (!nonZeroFound) {\n throw std::runtime_error(\"No content type found\");\n }\n msg.fragment = std::move(*decryptedBuf);\n\n switch (msg.type) {\n case ContentType::handshake:\n case ContentType::alert:\n case ContentType::application_data:\n break;\n default:\n throw std::runtime_error(folly::to(\n \"received encrypted content type \",\n static_cast(msg.type)));\n }\n\n if (!msg.fragment) {\n if (msg.type == ContentType::application_data) {\n msg.fragment = folly::IOBuf::create(0);\n } else {\n throw std::runtime_error(\"received empty fragment\");\n }\n }\n\n return msg;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-770", "cwe_name": "Allocation of Resources Without Limits or Throttling", "description": "The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/770.html", "label_name": "vulnerable"} {"code": "void ConnectionImpl::onHeaderValue(const char* data, size_t length) {\n if (header_parsing_state_ == HeaderParsingState::Done) {\n // Ignore trailers.\n return;\n }\n\n const absl::string_view header_value = absl::string_view(data, length);\n\n if (strict_header_validation_) {\n if (!Http::HeaderUtility::headerIsValid(header_value)) {\n ENVOY_CONN_LOG(debug, \"invalid header value: {}\", connection_, header_value);\n error_code_ = Http::Code::BadRequest;\n sendProtocolError();\n throw CodecProtocolException(\"http/1.1 protocol error: header value contains invalid chars\");\n }\n } else if (header_value.find('\\0') != absl::string_view::npos) {\n // http-parser should filter for this\n // (https://tools.ietf.org/html/rfc7230#section-3.2.6), but it doesn't today. HeaderStrings\n // have an invariant that they must not contain embedded zero characters\n // (NUL, ASCII 0x0).\n throw CodecProtocolException(\"http/1.1 protocol error: header value contains NUL\");\n }\n\n header_parsing_state_ = HeaderParsingState::Value;\n current_header_value_.append(data, length);\n\n const uint32_t total =\n current_header_field_.size() + current_header_value_.size() + current_header_map_->byteSize();\n if (total > (max_request_headers_kb_ * 1024)) {\n error_code_ = Http::Code::RequestHeaderFieldsTooLarge;\n sendProtocolError();\n throw CodecProtocolException(\"headers size exceeds limit\");\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "int ConnectionImpl::saveHeader(const nghttp2_frame* frame, HeaderString&& name,\n HeaderString&& value) {\n StreamImpl* stream = getStream(frame->hd.stream_id);\n if (!stream) {\n // We have seen 1 or 2 crashes where we get a headers callback but there is no associated\n // stream data. I honestly am not sure how this can happen. However, from reading the nghttp2\n // code it looks possible that inflate_header_block() can safely inflate headers for an already\n // closed stream, but will still call the headers callback. Since that seems possible, we should\n // ignore this case here.\n // TODO(mattklein123): Figure out a test case that can hit this.\n stats_.headers_cb_no_stream_.inc();\n return 0;\n }\n\n stream->saveHeader(std::move(name), std::move(value));\n if (stream->headers_->byteSize() > max_request_headers_kb_ * 1024) {\n // This will cause the library to reset/close the stream.\n stats_.header_overflow_.inc();\n return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;\n } else {\n return 0;\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "void HttpIntegrationTest::waitForNextUpstreamRequest(uint64_t upstream_index) {\n waitForNextUpstreamRequest(std::vector({upstream_index}));\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "HttpIntegrationTest::waitForNextUpstreamRequest(const std::vector& upstream_indices) {\n uint64_t upstream_with_request;\n // If there is no upstream connection, wait for it to be established.\n if (!fake_upstream_connection_) {\n\n AssertionResult result = AssertionFailure();\n for (auto upstream_index : upstream_indices) {\n result = fake_upstreams_[upstream_index]->waitForHttpConnection(\n *dispatcher_, fake_upstream_connection_, TestUtility::DefaultTimeout,\n max_request_headers_kb_);\n if (result) {\n upstream_with_request = upstream_index;\n break;\n }\n }\n RELEASE_ASSERT(result, result.message());\n }\n // Wait for the next stream on the upstream connection.\n AssertionResult result =\n fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_);\n RELEASE_ASSERT(result, result.message());\n // Wait for the stream to be completely received.\n result = upstream_request_->waitForEndStream(*dispatcher_);\n RELEASE_ASSERT(result, result.message());\n\n return upstream_with_request;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "TEST_P(SslSocketTest, GetUriWithUriSan) {\n const std::string client_ctx_yaml = R\"EOF(\n common_tls_context:\n tls_certificates:\n certificate_chain:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem\"\n private_key:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_key.pem\"\n)EOF\";\n\n const std::string server_ctx_yaml = R\"EOF(\n common_tls_context:\n tls_certificates:\n certificate_chain:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/unittest_cert.pem\"\n private_key:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/unittest_key.pem\"\n validation_context:\n trusted_ca:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem\"\n match_subject_alt_names:\n exact: \"spiffe://lyft.com/test-team\"\n)EOF\";\n\n TestUtilOptions test_options(client_ctx_yaml, server_ctx_yaml, true, GetParam());\n testUtil(test_options.setExpectedClientCertUri(\"spiffe://lyft.com/test-team\")\n .setExpectedSerialNumber(TEST_SAN_URI_CERT_SERIAL));\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": "TEST_F(ListenerManagerImplQuicOnlyTest, QuicListenerFactoryWithWrongCodec) {\n const std::string yaml = TestEnvironment::substitute(R\"EOF(\naddress:\n socket_address:\n address: 127.0.0.1\n protocol: UDP\n port_value: 1234\nfilter_chains:\n- filter_chain_match:\n transport_protocol: \"quic\"\n filters: []\n transport_socket:\n name: envoy.transport_sockets.quic\n typed_config:\n \"@type\": type.googleapis.com/envoy.extensions.transport_sockets.quic.v3.QuicDownstreamTransport\n downstream_tls_context:\n common_tls_context:\n tls_certificates:\n - certificate_chain:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem\"\n private_key:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_key.pem\"\n validation_context:\n trusted_ca:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem\"\n match_subject_alt_names:\n - exact: localhost\n - exact: 127.0.0.1\nudp_listener_config:\n quic_options: {}\n )EOF\",\n Network::Address::IpVersion::v4);\n\n envoy::config::listener::v3::Listener listener_proto = parseListenerFromV3Yaml(yaml);\n\n#if defined(ENVOY_ENABLE_QUIC)\n EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(listener_proto, \"\", true), EnvoyException,\n \"error building network filter chain for quic listener: requires exactly \"\n \"one http_connection_manager filter.\");\n#else\n EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(listener_proto, \"\", true), EnvoyException,\n \"QUIC is configured but not enabled in the build.\");\n#endif\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": "void TightDecoder::FilterGradient(const rdr::U8* inbuf,\n const PixelFormat& pf, PIXEL_T* outbuf,\n int stride, const Rect& r)\n{\n int x, y, c;\n static rdr::U8 prevRow[TIGHT_MAX_WIDTH*3];\n static rdr::U8 thisRow[TIGHT_MAX_WIDTH*3];\n rdr::U8 pix[3]; \n int est[3]; \n\n memset(prevRow, 0, sizeof(prevRow));\n\n // Set up shortcut variables\n int rectHeight = r.height();\n int rectWidth = r.width();\n\n for (y = 0; y < rectHeight; y++) {\n /* First pixel in a row */\n pf.rgbFromBuffer(pix, &inbuf[y*rectWidth], 1);\n for (c = 0; c < 3; c++)\n pix[c] += prevRow[c];\n\n memcpy(thisRow, pix, sizeof(pix));\n\n pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride], pix, 1);\n\n /* Remaining pixels of a row */\n for (x = 1; x < rectWidth; x++) {\n for (c = 0; c < 3; c++) {\n est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c];\n if (est[c] > 255) {\n est[c] = 255;\n } else if (est[c] < 0) {\n est[c] = 0;\n }\n }\n\n pf.rgbFromBuffer(pix, &inbuf[y*rectWidth+x], 1);\n for (c = 0; c < 3; c++)\n pix[c] += est[c];\n\n memcpy(&thisRow[x*3], pix, sizeof(pix));\n\n pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride+x], pix, 1);\n }\n\n memcpy(prevRow, thisRow, sizeof(prevRow));\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "int FdInStream::overrun(int itemSize, int nItems, bool wait)\n{\n if (itemSize > bufSize)\n throw Exception(\"FdInStream overrun: max itemSize exceeded\");\n\n if (end - ptr != 0)\n memmove(start, ptr, end - ptr);\n\n offset += ptr - start;\n end -= ptr - start;\n ptr = start;\n\n int bytes_to_read;\n while (end < start + itemSize) {\n bytes_to_read = start + bufSize - end;\n if (!timing) {\n // When not timing, we must be careful not to read too much\n // extra data into the buffer. Otherwise, the line speed\n // estimation might stay at zero for a long time: All reads\n // during timing=1 can be satisfied without calling\n // readWithTimeoutOrCallback. However, reading only 1 or 2 bytes\n // bytes is ineffecient.\n bytes_to_read = vncmin(bytes_to_read, vncmax(itemSize*nItems, 8));\n }\n int n = readWithTimeoutOrCallback((U8*)end, bytes_to_read, wait);\n if (n == 0) return 0;\n end += n;\n }\n\n if (itemSize * nItems > end - ptr)\n nItems = (end - ptr) / itemSize;\n\n return nItems;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "int FdInStream::readWithTimeoutOrCallback(void* buf, int len, bool wait)\n{\n struct timeval before, after;\n if (timing)\n gettimeofday(&before, 0);\n\n int n;\n while (true) {\n do {\n fd_set fds;\n struct timeval tv;\n struct timeval* tvp = &tv;\n\n if (!wait) {\n tv.tv_sec = tv.tv_usec = 0;\n } else if (timeoutms != -1) {\n tv.tv_sec = timeoutms / 1000;\n tv.tv_usec = (timeoutms % 1000) * 1000;\n } else {\n tvp = 0;\n }\n\n FD_ZERO(&fds);\n FD_SET(fd, &fds);\n n = select(fd+1, &fds, 0, 0, tvp);\n } while (n < 0 && errno == EINTR);\n\n if (n > 0) break;\n if (n < 0) throw SystemException(\"select\",errno);\n if (!wait) return 0;\n if (!blockCallback) throw TimedOut();\n\n blockCallback->blockCallback();\n }\n\n do {\n n = ::recv(fd, (char*)buf, len, 0);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0) throw SystemException(\"read\",errno);\n if (n == 0) throw EndOfStream();\n\n if (timing) {\n gettimeofday(&after, 0);\n int newTimeWaited = ((after.tv_sec - before.tv_sec) * 10000 +\n (after.tv_usec - before.tv_usec) / 100);\n int newKbits = n * 8 / 1000;\n\n // limit rate to between 10kbit/s and 40Mbit/s\n\n if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;\n if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;\n\n timeWaitedIn100us += newTimeWaited;\n timedKbits += newKbits;\n }\n\n return n;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "FdOutStream::FdOutStream(int fd_, bool blocking_, int timeoutms_, int bufSize_)\n : fd(fd_), blocking(blocking_), timeoutms(timeoutms_),\n bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0)\n{\n ptr = start = sentUpTo = new U8[bufSize];\n end = start + bufSize;\n\n gettimeofday(&lastWrite, NULL);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "int FdOutStream::length()\n{\n return offset + ptr - sentUpTo;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "void ZlibInStream::setUnderlying(InStream* is, int bytesIn_)\n{\n underlying = is;\n bytesIn = bytesIn_;\n ptr = end = start;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": " void combine_list(String & res, const StringList & in)\n {\n res.clear();\n StringListEnumeration els = in.elements_obj();\n const char * s = 0;\n while ( (s = els.next()) != 0) \n {\n for (; *s; ++s) {\n if (*s == ':')\n res.append('\\\\');\n res.append(*s);\n }\n res.append(':');\n }\n if (res.back() == ':') res.pop_back();\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": " char * unescape(char * dest, const char * src)\n {\n while (*src) {\n if (*src == '\\\\') {\n\t++src;\n\tswitch (*src) {\n\tcase 'n': *dest = '\\n'; break;\n\tcase 'r': *dest = '\\r'; break;\n\tcase 't': *dest = '\\t'; break;\n\tcase 'f': *dest = '\\f'; break;\n\tcase 'v': *dest = '\\v'; break;\n\tdefault: *dest = *src;\n\t}\n } else {\n\t*dest = *src;\n }\n ++src;\n ++dest;\n }\n *dest = '\\0';\n return dest;\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static int bson_append_estart( bson *b, int type, const char *name, const int dataSize ) {\n const int len = strlen( name ) + 1;\n\n if ( b->finished ) {\n b->err |= BSON_ALREADY_FINISHED;\n return BSON_ERROR;\n }\n\n if ( bson_ensure_space( b, 1 + len + dataSize ) == BSON_ERROR ) {\n return BSON_ERROR;\n }\n\n if( bson_check_field_name( b, ( const char * )name, len - 1 ) == BSON_ERROR ) {\n bson_builder_error( b );\n return BSON_ERROR;\n }\n\n bson_append_byte( b, ( char )type );\n bson_append( b, name, len );\n return BSON_OK;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "MONGO_EXPORT int bson_append_code_w_scope_n( bson *b, const char *name,\n const char *code, int len, const bson *scope ) {\n\n int sl, size;\n if ( !scope ) return BSON_ERROR;\n sl = len + 1;\n size = 4 + 4 + sl + bson_size( scope );\n if ( bson_append_estart( b, BSON_CODEWSCOPE, name, size ) == BSON_ERROR )\n return BSON_ERROR;\n bson_append32( b, &size );\n bson_append32( b, &sl );\n bson_append( b, code, sl );\n bson_append( b, scope->data, bson_size( scope ) );\n return BSON_OK;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "vulnerable"} {"code": "snmp_process_data(void)\n{\n static unsigned char packet[SNMP_MAX_PACKET_SIZE];\n unsigned char *packet_end;\n static uint32_t packet_len;\n\n packet_end = packet + sizeof(packet) - 1;\n packet_len = 0;\n\n LOG_DBG(\"receiving UDP datagram from [\");\n LOG_DBG_6ADDR(&UIP_IP_BUF->srcipaddr);\n LOG_DBG_(\"]:%u\", uip_ntohs(UIP_UDP_BUF->srcport));\n LOG_DBG_(\" Length: %u\\n\", uip_datalen());\n\n /*\n * Handle the request\n */\n if((packet_end = snmp_engine(uip_appdata, uip_datalen(), packet_end, &packet_len)) == NULL) {\n LOG_DBG(\"Error while handling the request\\n\");\n } else {\n LOG_DBG(\"Sending response\\n\");\n /*\n * Send the response\n */\n uip_udp_packet_sendto(snmp_udp_conn, packet_end, packet_len, &UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport);\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-125", "cwe_name": "Out-of-bounds Read", "description": "The software reads data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/125.html", "label_name": "vulnerable"} {"code": "static ssize_t _consolefs_writev(\n oe_fd_t* desc,\n const struct oe_iovec* iov,\n int iovcnt)\n{\n ssize_t ret = -1;\n file_t* file = _cast_file(desc);\n void* buf = NULL;\n size_t buf_size = 0;\n\n if (!file || (!iov && iovcnt) || iovcnt < 0 || iovcnt > OE_IOV_MAX)\n OE_RAISE_ERRNO(OE_EINVAL);\n\n /* Flatten the IO vector into contiguous heap memory. */\n if (oe_iov_pack(iov, iovcnt, &buf, &buf_size) != 0)\n OE_RAISE_ERRNO(OE_ENOMEM);\n\n /* Call the host. */\n if (oe_syscall_writev_ocall(&ret, file->host_fd, buf, iovcnt, buf_size) !=\n OE_OK)\n {\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\ndone:\n\n if (buf)\n oe_free(buf);\n\n return ret;\n}", "label": 0, "programming_language": "C++", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "static ssize_t _hostfs_pread(\n oe_fd_t* desc,\n void* buf,\n size_t count,\n oe_off_t offset)\n{\n ssize_t ret = -1;\n file_t* file = _cast_file(desc);\n\n if (!file)\n OE_RAISE_ERRNO(OE_EINVAL);\n\n if (oe_syscall_pread_ocall(&ret, file->host_fd, buf, count, offset) !=\n OE_OK)\n OE_RAISE_ERRNO(OE_EINVAL);\n\ndone:\n return ret;\n}", "label": 0, "programming_language": "C++", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": "bool WindowsServiceControl::install( const QString& filePath, const QString& displayName )\n{\n\tm_serviceHandle = CreateService(\n\t\t\t\tm_serviceManager,\t\t// SCManager database\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( m_name ),\t// name of service\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( displayName ),// name to display\n\t\t\t\tSERVICE_ALL_ACCESS,\t// desired access\n\t\t\t\tSERVICE_WIN32_OWN_PROCESS,\n\t\t\t\t// service type\n\t\t\t\tSERVICE_AUTO_START,\t// start type\n\t\t\t\tSERVICE_ERROR_NORMAL,\t// error control type\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( filePath ),\t\t// service's binary\n\t\t\t\tnullptr,\t\t\t// no load ordering group\n\t\t\t\tnullptr,\t\t\t// no tag identifier\n\t\t\t\tL\"Tcpip\\0RpcSs\\0\\0\",\t\t// dependencies\n\t\t\t\tnullptr,\t\t\t// LocalSystem account\n\t\t\t\tnullptr );\t\t\t// no password\n\n\tif( m_serviceHandle == nullptr )\n\t{\n\t\tconst auto error = GetLastError();\n\t\tif( error == ERROR_SERVICE_EXISTS )\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" is already installed.\" ).arg( m_name ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" could not be installed.\" ).arg( m_name ) );\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tSC_ACTION serviceActions;\n\tserviceActions.Delay = 10000;\n\tserviceActions.Type = SC_ACTION_RESTART;\n\n\tSERVICE_FAILURE_ACTIONS serviceFailureActions;\n\tserviceFailureActions.dwResetPeriod = 0;\n\tserviceFailureActions.lpRebootMsg = nullptr;\n\tserviceFailureActions.lpCommand = nullptr;\n\tserviceFailureActions.lpsaActions = &serviceActions;\n\tserviceFailureActions.cActions = 1;\n\tChangeServiceConfig2( m_serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, &serviceFailureActions );\n\n\t// Everything went fine\n\tvInfo() << qUtf8Printable( tr( \"The service \\\"%1\\\" has been installed successfully.\" ).arg( m_name ) );\n\n\treturn true;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-428", "cwe_name": "Unquoted Search Path or Element", "description": "The product uses a search path that contains an unquoted element, in which the element contains whitespace or other separators. This can cause the product to access resources in a parent path.", "url": "https://cwe.mitre.org/data/definitions/428.html", "label_name": "vulnerable"} {"code": "void MainWindow::showUpgradePrompt()\n{\n if (Settings.checkUpgradeAutomatic()) {\n showStatusMessage(\"Checking for upgrade...\");\n QNetworkRequest request(QUrl(\"https://check.shotcut.org/version.json\"));\n QSslConfiguration sslConfig = request.sslConfiguration();\n sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);\n request.setSslConfiguration(sslConfig);\n m_network.get(request);\n } else {\n m_network.setStrictTransportSecurityEnabled(false);\n QAction* action = new QAction(tr(\"Click here to check for a new version of Shotcut.\"), 0);\n connect(action, SIGNAL(triggered(bool)), SLOT(on_actionUpgrade_triggered()));\n showStatusMessage(action, 15 /* seconds */);\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-295", "cwe_name": "Improper Certificate Validation", "description": "The software does not validate, or incorrectly validates, a certificate.", "url": "https://cwe.mitre.org/data/definitions/295.html", "label_name": "vulnerable"} {"code": "\t\tauto Phase3() -> Local final {\n\t\t\treturn Boolean::New(Isolate::GetCurrent(), did_set);\n\t\t}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-913", "cwe_name": "Improper Control of Dynamically-Managed Code Resources", "description": "The software does not properly restrict reading from or writing to dynamically-managed code resources such as variables, objects, classes, attributes, functions, or executable instructions or statements.", "url": "https://cwe.mitre.org/data/definitions/913.html", "label_name": "vulnerable"} {"code": " void runTest() override\r\n {\r\n beginTest (\"ZIP\");\r\n\r\n ZipFile::Builder builder;\r\n StringArray entryNames { \"first\", \"second\", \"third\" };\r\n HashMap blocks;\r\n\r\n for (auto& entryName : entryNames)\r\n {\r\n auto& block = blocks.getReference (entryName);\r\n MemoryOutputStream mo (block, false);\r\n mo << entryName;\r\n mo.flush();\r\n builder.addEntry (new MemoryInputStream (block, false), 9, entryName, Time::getCurrentTime());\r\n }\r\n\r\n MemoryBlock data;\r\n MemoryOutputStream mo (data, false);\r\n builder.writeToStream (mo, nullptr);\r\n MemoryInputStream mi (data, false);\r\n\r\n ZipFile zip (mi);\r\n\r\n expectEquals (zip.getNumEntries(), entryNames.size());\r\n\r\n for (auto& entryName : entryNames)\r\n {\r\n auto* entry = zip.getEntry (entryName);\r\n std::unique_ptr input (zip.createStreamForEntry (*entry));\r\n expectEquals (input->readEntireStreamAsString(), entryName);\r\n }\r\n }\r", "label": 0, "programming_language": "C++", "cwe_id": "CWE-59", "cwe_name": "Improper Link Resolution Before File Access ('Link Following')", "description": "The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.", "url": "https://cwe.mitre.org/data/definitions/59.html", "label_name": "vulnerable"} {"code": "RestStatus RestAuthHandler::execute() {\n auto const type = _request->requestType();\n if (type != rest::RequestType::POST) {\n generateError(rest::ResponseCode::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED);\n return RestStatus::DONE;\n }\n\n bool parseSuccess = false;\n VPackSlice slice = this->parseVPackBody(parseSuccess);\n if (!parseSuccess) { // error already set\n return RestStatus::DONE;\n }\n\n if (!slice.isObject()) {\n return badRequest();\n }\n\n VPackSlice usernameSlice = slice.get(\"username\");\n VPackSlice passwordSlice = slice.get(\"password\");\n\n if (!usernameSlice.isString() || !passwordSlice.isString()) {\n return badRequest();\n }\n\n _username = usernameSlice.copyString();\n std::string const password = passwordSlice.copyString();\n\n auth::UserManager* um = AuthenticationFeature::instance()->userManager();\n if (um == nullptr) {\n std::string msg = \"This server does not support users\";\n LOG_TOPIC(\"2e7d4\", ERR, Logger::AUTHENTICATION) << msg;\n generateError(rest::ResponseCode::UNAUTHORIZED, TRI_ERROR_HTTP_UNAUTHORIZED, msg);\n } else if (um->checkPassword(_username, password)) {\n VPackBuilder resultBuilder;\n {\n VPackObjectBuilder b(&resultBuilder);\n std::string jwt = generateJwt(_username, password);\n resultBuilder.add(\"jwt\", VPackValue(jwt));\n }\n\n _isValid = true;\n generateDocument(resultBuilder.slice(), true, &VPackOptions::Defaults);\n } else {\n // mop: rfc 2616 10.4.2 (if credentials wrong 401)\n generateError(rest::ResponseCode::UNAUTHORIZED, TRI_ERROR_HTTP_UNAUTHORIZED,\n \"Wrong credentials\");\n }\n return RestStatus::DONE;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-613", "cwe_name": "Insufficient Session Expiration", "description": "According to WASC, \"Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization.\"", "url": "https://cwe.mitre.org/data/definitions/613.html", "label_name": "vulnerable"} {"code": "TEST_CASE_METHOD(TestFixture, \"ECDSA AES keygen and signature test\", \"[ecdsa-aes-key-sig-gen]\") {\n vector errMsg(BUF_LEN, 0);\n int errStatus = 0;\n vector encrPrivKey(BUF_LEN, 0);\n vector pubKeyX(BUF_LEN, 0);\n vector pubKeyY(BUF_LEN, 0);\n\n uint32_t encLen = 0;\n PRINT_SRC_LINE\n auto status = trustedGenerateEcdsaKeyAES(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen,\n pubKeyX.data(),\n pubKeyY.data());\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n\n string hex = SAMPLE_HEX_HASH;\n vector signatureR(BUF_LEN, 0);\n vector signatureS(BUF_LEN, 0);\n uint8_t signatureV = 0;\n\n\n for (int i = 0; i < 50; i++) {\n PRINT_SRC_LINE\n status = trustedEcdsaSignAES(eid, &errStatus, errMsg.data(), encrPrivKey.data(), encLen,\n hex.data(),\n signatureR.data(),\n signatureS.data(), &signatureV, 16);\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n }\n\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "TEST_CASE_METHOD(TestFixture, \"ECDSA AES key gen\", \"[ecdsa-aes-key-gen]\") {\n vector errMsg(BUF_LEN, 0);\n int errStatus = 0;\n vector encrPrivKey(BUF_LEN, 0);\n vector pubKeyX(BUF_LEN, 0);\n vector pubKeyY(BUF_LEN, 0);\n uint32_t encLen = 0;\n PRINT_SRC_LINE\n auto status = trustedGenerateEcdsaKeyAES(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen,\n pubKeyX.data(),\n pubKeyY.data());\n\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "int HttpFileImpl::save(const std::string &path) const\n{\n assert(!path.empty());\n if (fileName_.empty())\n return -1;\n filesystem::path fsPath(utils::toNativePath(path));\n if (!fsPath.is_absolute() &&\n (!fsPath.has_parent_path() ||\n (fsPath.begin()->string() != \".\" && fsPath.begin()->string() != \"..\")))\n {\n filesystem::path fsUploadPath(utils::toNativePath(\n HttpAppFrameworkImpl::instance().getUploadPath()));\n fsPath = fsUploadPath / fsPath;\n }\n filesystem::path fsFileName(utils::toNativePath(fileName_));\n if (!filesystem::exists(fsPath))\n {\n LOG_TRACE << \"create path:\" << fsPath;\n drogon::error_code err;\n filesystem::create_directories(fsPath, err);\n if (err)\n {\n LOG_SYSERR;\n return -1;\n }\n }\n return saveTo(fsPath / fsFileName);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-552", "cwe_name": "Files or Directories Accessible to External Parties", "description": "The product makes files or directories accessible to unauthorized actors, even though they should not be.", "url": "https://cwe.mitre.org/data/definitions/552.html", "label_name": "vulnerable"} {"code": "ResponsePtr Server::ServeStatic(RequestPtr request) {\n assert(request->method() == methods::kGet);\n\n if (doc_root_.empty()) {\n LOG_INFO(\"The doc root was not specified\");\n return {};\n }\n\n fs::path path = doc_root_ / request->url().path();\n\n try {\n // NOTE: FileBody might throw Error::kFileError.\n auto body = std::make_shared(path, file_chunk_size_);\n\n auto response = std::make_shared(Status::kOK);\n\n std::string extension = path.extension().string();\n response->SetContentType(media_types::FromExtension(extension), \"\");\n\n // NOTE: Gzip compression is not supported.\n response->SetBody(body, true);\n\n return response;\n\n } catch (const Error& error) {\n LOG_ERRO(\"File error: %s\", error.message().c_str());\n return {};\n }\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "std::string DecodeUnsafe(string_view encoded) {\n std::string raw;\n if (Decode(encoded, &raw)) {\n return raw;\n }\n return ToString(encoded);\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": "std::string addEmoji(const Proxy &node, const RegexMatchConfigs &emoji_array, extra_settings &ext)\n{\n std::string real_rule, ret;\n\n for(const RegexMatchConfig &x : emoji_array)\n {\n if(!x.Script.empty())\n {\n std::string result;\n script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx)\n {\n std::string script = x.Script;\n if(startsWith(script, \"path:\"))\n script = fileGet(script.substr(5), true);\n try\n {\n ctx.eval(script);\n auto getEmoji = (std::function) ctx.eval(\"getEmoji\");\n ret = getEmoji(node);\n if(!ret.empty())\n result = ret + \" \" + node.Remark;\n }\n catch (qjs::exception)\n {\n script_print_stack(ctx);\n }\n }, global.scriptCleanContext);\n if(!result.empty())\n return result;\n continue;\n }\n if(x.Replace.empty())\n continue;\n if(applyMatcher(x.Match, real_rule, node) && real_rule.size() && regFind(node.Remark, real_rule))\n return x.Replace + \" \" + node.Remark;\n }\n return node.Remark;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-434", "cwe_name": "Unrestricted Upload of File with Dangerous Type", "description": "The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.", "url": "https://cwe.mitre.org/data/definitions/434.html", "label_name": "vulnerable"} {"code": " bool CFontFileType1::RemovePfbMarkers()\n {\n bool bSuccess = true;\n\n int nBlockType = 0;\n int nBlockLen = 0;\n int nChar = 0;\n\n unsigned char *sBuffer = NULL;\n int nBufLen = 0;\n\n while ( nBlockType != PFB_DONE )\n {\n while ( 0 == nBlockLen )\n {\n nChar = ReadU8( &bSuccess );\n if ( !bSuccess )\n return false;\n\n nBlockType = ReadU8( &bSuccess );\n if ( !bSuccess || PFB_MARKER != nChar || ( PFB_ASCII != nBlockType && PFB_BINARY != nBlockType && PFB_DONE != nBlockType ) )\n return false;\n\n if ( PFB_DONE == nBlockType )\n break;\n\n nBlockLen = ReadU32LE( &bSuccess );\n if ( !bSuccess )\n return false;\n }\n\n // \u0427\u0438\u0442\u0430\u0435\u043c \u0441\u0430\u043c \u0431\u043b\u043e\u043a \u0434\u0430\u043d\u043d\u044b\u0445\n if ( nBlockLen > 0 )\n {\n if ( !sBuffer )\n {\n sBuffer = (unsigned char*)MemUtilsMalloc( nBlockLen );\n if ( !sBuffer )\n return false;\n }\n else\n sBuffer = (unsigned char*)MemUtilsRealloc( sBuffer, nBufLen + nBlockLen );\n\n Read( sBuffer + nBufLen, nBlockLen );\n nBufLen += nBlockLen;\n }\n nBlockLen = 0;\n }\n\n if ( m_bFreeFileData )\n MemUtilsFree( m_sFile );\n\n m_bFreeFileData = true;\n m_sFile = (unsigned char*)sBuffer;\n m_sFileData = m_sFile;\n m_nLen = nBufLen;\n m_nPos = 0;\n\n return true;\n }", "label": 0, "programming_language": "C++", "cwe_id": "CWE-787", "cwe_name": "Out-of-bounds Write", "description": "The software writes data past the end, or before the beginning, of the intended buffer.", "url": "https://cwe.mitre.org/data/definitions/787.html", "label_name": "vulnerable"} {"code": "EntropyParser::EntropyParser(class Frame *frame,class Scan *scan)\n : JKeeper(scan->EnvironOf()), m_pScan(scan), m_pFrame(frame)\n{\n m_ucCount = scan->ComponentsInScan();\n\n // The residual scan uses all components here, not just for, but\n // it does not require the component count either.\n for(volatile UBYTE i = 0;i < m_ucCount && i < 4;i++) {\n JPG_TRY {\n m_pComponent[i] = scan->ComponentOf(i);\n } JPG_CATCH {\n m_pComponent[i] = NULL;\n } JPG_ENDTRY;\n }\n\n m_ulRestartInterval = m_pFrame->TablesOf()->RestartIntervalOf();\n m_usNextRestartMarker = 0xffd0;\n m_ulMCUsToGo = m_ulRestartInterval;\n m_bSegmentIsValid = true;\n m_bScanForDNL = (m_pFrame->HeightOf() == 0)?true:false;\n m_bDNLFound = false;\n}", "label": 0, "programming_language": "C++", "cwe_id": "CWE-476", "cwe_name": "NULL Pointer Dereference", "description": "A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.", "url": "https://cwe.mitre.org/data/definitions/476.html", "label_name": "vulnerable"} {"code": " def html_escape(s)\n s = s.to_s\n if s.html_safe?\n s\n else\n s.to_s.gsub(/&/, \"&\").gsub(/\\\"/, \""\").gsub(/>/, \">\").gsub(/ ignore\n end\n\n raise ArgumentError, \"too much information #{hash.inspect}\" if hash.present?\n r\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-862", "cwe_name": "Missing Authorization", "description": "The software does not perform an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/862.html", "label_name": "safe"} {"code": " def test_delete_flags_through_xml\n User.current = users( :Iggy )\n\n #check precondition\n assert_equal 2, @project.type_flags('build').size\n assert_equal 2, @project.type_flags('publish').size\n \n #project is given as axml\n axml = Xmlhash.parse(\n \"\n Iggy's Home Project\n dummy\n \"\n ) \n \n @project.update_all_flags(axml)\n assert_equal 0, @project.type_flags('build').size\n assert_equal 0, @project.type_flags('publish').size\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-275", "cwe_name": "Permission Issues", "description": "Weaknesses in this category are related to improper assignment or handling of permissions.", "url": "https://cwe.mitre.org/data/definitions/275.html", "label_name": "safe"} {"code": " def deliver!(mail)\n if ::File.respond_to?(:makedirs)\n ::File.makedirs settings[:location]\n else\n ::FileUtils.mkdir_p settings[:location]\n end\n\n mail.destinations.uniq.each do |to|\n ::File.open(::File.join(settings[:location], File.basename(to.to_s)), 'a') { |f| \"#{f.write(mail.encoded)}\\r\\n\\r\\n\" }\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " def initialize(name, value = nil, charset = 'utf-8')\n case\n when name =~ /:/ # Field.new(\"field-name: field data\")\n @charset = value.blank? ? charset : value\n @name = name[FIELD_PREFIX]\n @raw_value = name\n when name !~ /:/ && value.blank? # Field.new(\"field-name\")\n @name = name\n @value = nil\n @charset = charset\n else # Field.new(\"field-name\", \"value\")\n @name = name\n @value = value\n @charset = charset\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-93", "cwe_name": "Improper Neutralization of CRLF Sequences ('CRLF Injection')", "description": "The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs.", "url": "https://cwe.mitre.org/data/definitions/93.html", "label_name": "safe"} {"code": " def name\n @name\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-93", "cwe_name": "Improper Neutralization of CRLF Sequences ('CRLF Injection')", "description": "The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs.", "url": "https://cwe.mitre.org/data/definitions/93.html", "label_name": "safe"} {"code": " def find(request)\n get_terminus(request).find(request)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " it \"should use a certificate type of :ca\" do\n Puppet::SSL::CertificateFactory.expects(:build).with do |*args|\n args[0].should == :ca\n end.returns \"my real cert\"\n @ca.sign(@name, :ca, @request)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " it \"should reject CSRs whose CN doesn't match the name for which we're signing them\" do\n # Shorten this so the test doesn't take too long\n Puppet[:keylength] = 1024\n key = Puppet::SSL::Key.new('the_certname')\n key.generate\n\n csr = Puppet::SSL::CertificateRequest.new('the_certname')\n csr.generate(key)\n\n expect do\n @ca.check_internal_signing_policies('not_the_certname', csr, false)\n end.to raise_error(\n Puppet::SSL::CertificateAuthority::CertificateSigningError,\n /common name \"the_certname\" does not match expected certname \"not_the_certname\"/\n )\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " it \"should pass the next serial as the serial number\" do\n Puppet::SSL::CertificateFactory.expects(:build).with do |*args|\n args[3].should == @serial\n end.returns \"my real cert\"\n @ca.sign(@name, :ca, @request)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "safe"} {"code": " def handle_unverified_request\n raise Console::AccessDenied, \"Request authenticity token does not match session #{session.inspect}\"\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " def self.search_by_host(key, operator, value)\n conditions = sanitize_sql_for_conditions([\"hosts.name #{operator} ?\", value_to_sql(operator, value)])\n direct = Puppetclass.joins(:hosts).where(conditions).select('puppetclasses.id').map(&:id).uniq\n hostgroup = Hostgroup.joins(:hosts).where(conditions).first\n indirect = HostgroupClass.where(:hostgroup_id => hostgroup.path_ids).pluck(:puppetclass_id).uniq\n return { :conditions => \"1=0\" } if direct.blank? && indirect.blank?\n\n puppet_classes = (direct + indirect).uniq\n { :conditions => \"puppetclasses.id IN(#{puppet_classes.join(',')})\" }\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def require_smart_proxy_or_login(features = nil)\n features = features.call if features.respond_to?(:call)\n allowed_smart_proxies = if features.blank?\n SmartProxy.unscoped.all\n else\n SmartProxy.unscoped.with_features(*features)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " def any_context?(taxonomy)\n taxonomy.blank?\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " def taxable_ids(loc = which_location, org = which_organization, inner_method = which_ancestry_method)\n # Return everything (represented by nil), including objects without\n # taxonomies. This value should only be returned for admin users.\n return nil if any_context?(loc) && any_context?(org) &&\n User.current.try(:admin?)\n\n ids = unscoped.pluck(:id)\n ids &= inner_ids(loc, Location, inner_method) if SETTINGS[:locations_enabled]\n ids &= inner_ids(org, Organization, inner_method) if SETTINGS[:organizations_enabled]\n\n if self == User\n # In the case of users we want the taxonomy scope to get both the users\n # of the taxonomy, admins, and the current user.\n ids.concat(admin_ids)\n ids << User.current.id if User.current.present?\n end\n\n ids\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " def self.taxonomy_conditions\n org = Organization.expand(Organization.current) if SETTINGS[:organizations_enabled]\n loc = Location.expand(Location.current) if SETTINGS[:locations_enabled]\n conditions = {}\n conditions[:organization_id] = Array(org).map { |o| o.subtree_ids }.flatten.uniq unless org.nil?\n conditions[:location_id] = Array(loc).map { |l| l.subtree_ids }.flatten.uniq unless loc.nil?\n conditions\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " def selected_ids\n return @selected_ids if @selected_ids\n ids = default_ids_hash\n #types NOT ignored - get ids that are selected\n hash_keys.each do |col|\n ids[col] = Array(taxonomy.send(col)).uniq\n end\n #types that ARE ignored - get ALL ids for object\n Array(taxonomy.ignore_types).each do |taxonomy_type|\n ids[\"#{taxonomy_type.tableize.singularize}_ids\"] = taxonomy_type.constantize.pluck(:id).uniq\n end\n\n ids[\"#{opposite_taxonomy_type}_ids\"] = Array(taxonomy.send(\"#{opposite_taxonomy_type}_ids\"))\n @selected_ids = ids\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " it \"updates a hostgroup with a parent parameter\" do\n child = FactoryGirl.create(:hostgroup, :parent => @base)\n as_admin do\n assert_equal \"original\", child.parameters[\"x\"]\n end\n post :update, {\"id\" => child.id, \"hostgroup\" => {\"name\" => child.name,\n :group_parameters_attributes => {\"0\" => {:name => \"x\", :value =>\"overridden\", :_destroy => \"\"}}}}, set_session_user\n assert_redirected_to hostgroups_url\n as_admin do\n child.reload\n assert_equal \"overridden\", child.parameters[\"x\"]\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " def fast_forward_to_first_boundary\n loop do\n content = @io.read(BUFSIZE)\n raise EOFError, \"bad content body\" unless content\n @buf << content\n\n while @buf.gsub!(/\\A([^\\n]*\\n)/, '')\n read_buffer = $1\n return if read_buffer == full_boundary\n end\n\n raise EOFError, \"bad content body\" if Utils.bytesize(@buf) >= BUFSIZE\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-119", "cwe_name": "Improper Restriction of Operations within the Bounds of a Memory Buffer", "description": "The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.", "url": "https://cwe.mitre.org/data/definitions/119.html", "label_name": "safe"} {"code": " def digest_match?(data, digest)\n return unless data && digest\n @secrets.any? do |secret|\n Rack::Utils.secure_compare(digest, generate_hmac(data, secret))\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " def _call(env)\n unless ALLOWED_VERBS.include? env[\"REQUEST_METHOD\"]\n return fail(405, \"Method Not Allowed\")\n end\n\n path_info = Utils.unescape(env[\"PATH_INFO\"])\n parts = path_info.split SEPS\n\n clean = []\n\n parts.each do |part|\n next if part.empty? || part == '.'\n part == '..' ? clean.pop : clean << part\n end\n\n @path = F.join(@root, *clean)\n\n available = begin\n F.file?(@path) && F.readable?(@path)\n rescue SystemCallError\n false\n end\n\n if available\n serving(env)\n else\n fail(404, \"File not found: #{path_info}\")\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " def render_step(the_step, options = {})\n if the_step.nil? || the_step.to_s == Wicked::FINISH_STEP\n redirect_to_finish_wizard options\n else\n render ERB::Util.url_encode(the_step), options\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "safe"} {"code": " def authorize_params\n super.tap do |params|\n %w[display scope].each do |v|\n if request.params[v]\n params[v.to_sym] = request.params[v]\n end\n end\n\n params[:scope] ||= DEFAULT_SCOPE\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "safe"} {"code": " it \"doesn't recognize #destroy\" do\n { :delete => \"/users/1\" }.should_not be_routable\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "safe"} {"code": " it \"should not update an arbitary model (sanitizes input)\" do\n where_stub = double\n where_stub.should_receive(:update_all).with(:state => \"Expanded\")\n Comment.should_receive(:where).and_return(where_stub)\n xhr :get, :timeline, :id => \"1,2,3,4+\", :state => \"Expanded\"\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def assemble_params(sanitized_params)\n sanitized_params.collect do |pair|\n pair_joiner = pair.first.to_s.end_with?(\"=\") ? \"\" : \" \"\n pair.flatten.compact.join(pair_joiner)\n end.join(\" \")\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " it \"handles Symbol keys with underscore and tailing '='\" do\n cl = subject.build(\"true\", :abc_def= => \"ghi\")\n expect(cl).to eq \"true --abc-def=ghi\"\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "safe"} {"code": " def annotate(path, identifier=nil)\n p = CGI.escape(scm_iconv(@path_encoding, 'UTF-8', path))\n blame = Annotate.new\n hg 'rhannotate', '-ncu', '-r', CGI.escape(hgrev(identifier)), '--', hgtarget(p) do |io|\n io.each_line do |line|\n line.force_encoding('ASCII-8BIT')\n next unless line =~ %r{^([^:]+)\\s(\\d+)\\s([0-9a-f]+):\\s(.*)$}\n r = Revision.new(:author => $1.strip, :revision => $2, :scmid => $3,\n :identifier => $3)\n blame.add_line($4.rstrip, r)\n end\n end\n blame\n rescue HgCommandAborted\n # means not found or cannot be annotated\n Annotate.new\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " def hg(*args, &block)\n # as of hg 4.4.1, early parsing of bool options is not terminated at '--'\n if args.any? { |s| s =~ HG_EARLY_BOOL_ARG }\n raise HgCommandArgumentError, \"malicious command argument detected\"\n end\n if args.take_while { |s| s != '--' }.any? { |s| s =~ HG_EARLY_LIST_ARG }\n raise HgCommandArgumentError, \"malicious command argument detected\"\n end\n\n repo_path = root_url || url\n full_args = [\"-R#{repo_path}\", '--encoding=utf-8']\n # don't use \"--config=\" form for compatibility with ancient Mercurial\n full_args << '--config' << \"extensions.redminehelper=#{HG_HELPER_EXT}\"\n full_args << '--config' << 'diff.git=false'\n full_args += args\n ret = shellout(\n self.class.sq_bin + ' ' + full_args.map { |e| shell_quote e.to_s }.join(' '),\n &block\n )\n if $? && $?.exitstatus != 0\n raise HgCommandAborted, \"hg exited with non-zero status: #{$?.exitstatus}\"\n end\n ret\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "safe"} {"code": " def grep(query, options={})\n ref = options[:ref] ? options[:ref] : \"HEAD\"\n query = Shellwords.split(query).select {|q| !(q =~ /^(-O)|(--open-files-in-pager)/) }\n query = Shellwords.join(query)\n args = [{}, '-I', '-i', '-c', query, ref, '--']\n args << options[:path] if options[:path]\n result = @git.grep(*args).split(\"\\n\")\n result.map do |line|\n branch_and_name, _, count = line.rpartition(\":\")\n branch, _, name = branch_and_name.partition(':')\n {:name => name, :count => count}\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-284", "cwe_name": "Improper Access Control", "description": "The software does not restrict or incorrectly restricts access to a resource from an unauthorized actor.", "url": "https://cwe.mitre.org/data/definitions/284.html", "label_name": "safe"} {"code": " def media_type_mismatch?\n supplied_type_mismatch? || calculated_type_mismatch?\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " def validate_each(record, attribute, value)\n adapter = Paperclip.io_adapters.for(value)\n if Paperclip::MediaTypeSpoofDetector.using(adapter, value.original_filename, value.content_type).spoofed?\n record.errors.add(attribute, :spoofed_media_type)\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "safe"} {"code": " def change_team_status\n Log.add_info(request, params.inspect)\n\n SqlHelper.validate_token([params[:status]])\n\n team_id = params[:team_id]\n begin\n team = Team.find(team_id)\n team.update_status(params[:status])\n\n @item = team.item\n\n flash[:notice] = t('msg.update_success')\n\n rescue => evar\n Log.add_error(request, evar)\n flash[:notice] = evar.to_s\n end\n\n render(:partial => 'ajax_team_status', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def users\n if params[:action] == 'users'\n Log.add_info(request, params.inspect)\n end\n\n con = ['User.id > 0']\n unless params[:keyword].blank?\n key_array = params[:keyword].split(nil)\n key_array.each do |key| \n con << SqlHelper.get_sql_like([:name, :email, :fullname, :address, :organization, :tel1, :tel2, :tel3, :fax, :url, :postalcode, :title], key)\n end\n end\n\n @group_id = nil\n if !params[:thetisBoxSelKeeper].nil?\n @group_id = params[:thetisBoxSelKeeper].split(':').last\n elsif !params[:group_id].blank?\n @group_id = params[:group_id]\n end\n SqlHelper.validate_token([@group_id])\n\n unless @group_id.nil?\n if @group_id == '0'\n con << \"((groups like '%|0|%') or (groups is null))\"\n else\n con << SqlHelper.get_sql_like([:groups], \"|#{@group_id}|\")\n end\n end\n\n where = ''\n unless con.empty?\n where = ' where ' + con.join(' and ')\n end\n\n order_by = nil\n @sort_col = params[:sort_col]\n @sort_type = params[:sort_type]\n\n if @sort_col.blank? or @sort_type.blank?\n @sort_col = \"xorder\"\n @sort_type = \"ASC\"\n end\n\n if @sort_col == 'name' and $thetis_config[:user]['by_full_name'] == '1'\n @sort_col == 'fullname'\n end\n\n SqlHelper.validate_token([@sort_col, @sort_type])\n order_by = ' order by ' + @sort_col + ' ' + @sort_type\n\n if @sort_col != 'xorder'\n order_by << ', xorder ASC'\n end\n if @sort_col != 'name'\n order_by << ', name ASC'\n end\n\n sql = 'select distinct User.* from users User'\n sql << where + order_by\n\n @user_pages, @users, @total_num = paginate_by_sql(User, sql, 50)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def edit_timecard\n Log.add_info(request, params.inspect)\n\n date_s = params[:date]\n\n if date_s.blank?\n @date = Date.today\n date_s = @date.strftime(Schedule::SYS_DATE_FORM)\n else\n @date = Date.parse(date_s)\n end\n\n @timecard = Timecard.get_for(@login_user.id, date_s)\n\n render(:partial => 'timecard', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def edit\n Log.add_info(request, params.inspect)\n\n date_s = params[:date]\n\n if date_s.blank?\n @date = Date.today\n date_s = @date.strftime(Schedule::SYS_DATE_FORM)\n else\n @date = Date.parse(date_s)\n end\n\n if params[:user_id].nil?\n @selected_user = @login_user\n else\n @selected_user = User.find(params[:user_id])\n end\n\n @timecard = Timecard.get_for(@selected_user.id, date_s)\n\n if @selected_user == @login_user\n @schedules = Schedule.get_user_day(@login_user, @date)\n end\n\n if !params[:display].nil? and params[:display].split('_').first == 'group'\n @group_id = params[:display].split('_').last\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def delete_attachment\n Log.add_info(request, '') # Not to show passwords.\n\n target_user = nil\n\n user_id = params[:user_id]\n zeptair_id = params[:zeptair_id]\n attachment_id = params[:attachment_id]\n SqlHelper.validate_token([user_id, zeptair_id, attachment_id])\n\n unless user_id.blank?\n if @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id.to_s == user_id.to_s\n target_user = User.find(user_id)\n end\n end\n\n unless zeptair_id.blank?\n\n target_user = User.where(\"zeptair_id=#{zeptair_id}\").first\n\n unless @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id == target_user.id\n target_user = nil\n end\n end\n\n if target_user.nil?\n if attachment_id.blank?\n\n query\n unless @post_items.nil?\n @post_items.each do |post_item|\n post_item.attachments_without_content.each do |attach|\n attach.destroy\n end\n post_item.update_attribute(:updated_at, Time.now)\n end\n end\n\n else\n attach = Attachment.find(attachment_id)\n\n item = Item.find(attach.item_id)\n\n if !@login_user.admin?(User::AUTH_ZEPTAIR) and item.user_id != @login_user.id\n raise t('msg.need_to_be_owner')\n end\n\n if item.xtype != Item::XTYPE_ZEPTAIR_POST\n raise t('msg.system_error')\n end\n\n attach.destroy\n\n item.update_attribute(:updated_at, Time.now)\n end\n else\n\n post_item = ZeptairPostHelper.get_item_for(target_user)\n post_item.attachments_without_content.each do |attach|\n attach.destroy\n end\n post_item.update_attribute(:updated_at, Time.now)\n end\n\n render(:text => t('msg.delete_success'))\n\n rescue => evar\n Log.add_error(request, evar)\n render(:text => 'ERROR:' + t('msg.system_error'))\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.count_completed_users(item_id)\n SqlHelper.validate_token([item_id])\n ack_msg = ZeptairDistHelper.completed_ack_message(item_id)\n return Comment.where(\"(item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}') and (message='#{ack_msg}')\").count\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.get_for_group(group_id)\n\n SqlHelper.validate_token([group_id])\n if group_id.nil?\n con = 'group_id is null'\n else\n con = \"group_id=#{group_id}\"\n end\n\n Location.do_expire(con)\n\n return Location.where(con).to_a\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.get_carried_over(user_id, year)\n\n SqlHelper.validate_token([user_id, year])\n\n yaml = ApplicationHelper.get_config_yaml\n unless yaml[:timecard].nil?\n paidhld_carry_over = yaml[:timecard]['paidhld_carry_over']\n end\n\n return 0 if paidhld_carry_over.nil? or paidhld_carry_over.empty? or paidhld_carry_over == PaidHoliday::CARRY_OVER_NONE\n\n begin\n con = \"(user_id=#{user_id}) and (year < #{year})\"\n paidhlds = PaidHoliday.where(con).order('year ASC').to_a\n rescue\n end\n return 0 if paidhlds.nil? or paidhlds.empty?\n\n sum = 0\n year_begins_from, month_begins_at = TimecardsHelper.get_fiscal_params\n\n if paidhld_carry_over == PaidHoliday::CARRY_OVER_1_YEAR\n\n last_carried_out = 0\n\n for y in paidhlds.first.year .. year - 1\n paidhld = paidhlds.find { |hld| hld.year == y }\n given_num = (paidhld.nil?)?0:paidhld.num\n\n start_date, end_date = TimecardsHelper.get_year_span(y, year_begins_from, month_begins_at)\n applied_paid_hlds = Timecard.applied_paid_hlds(user_id, start_date, end_date)\n\n if applied_paid_hlds >= last_carried_out\n last_carried_out = given_num - (applied_paid_hlds - last_carried_out)\n else\n last_carried_out = given_num\n end\n end\n\n return last_carried_out\n\n elsif paidhld_carry_over == PaidHoliday::CARRY_OVER_NO_EXPIRATION\n\n paidhlds.each do |paidhld|\n sum += paidhld.num\n end\n\n start_date, dummy = TimecardsHelper.get_year_span(paidhlds.first.year, year_begins_from, month_begins_at)\n dummy, end_date = TimecardsHelper.get_year_span(year - 1, year_begins_from, month_begins_at)\n applied_paid_hlds = Timecard.applied_paid_hlds(user_id, start_date, end_date)\n\n return (sum - applied_paid_hlds)\n else\n return 0\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.get_team_folder(team_id)\n\n SqlHelper.validate_token([team_id])\n begin\n return Folder.where(\"(owner_id=#{team_id}) and (xtype='#{Folder::XTYPE_TEAM}')\").first\n rescue => evar\n Log.add_error(nil, evar)\n return nil\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.applied_paid_hlds(user_id, start_date, end_date)\n\n SqlHelper.validate_token([user_id])\n\n start_s = start_date.strftime(Schedule::SYS_DATE_FORM)\n end_s = end_date.strftime(Schedule::SYS_DATE_FORM)\n\n sql = \"SELECT COUNT(*) FROM timecards WHERE user_id = #{user_id} AND date >= '#{start_s}' AND date <= '#{end_s}'\"\n\n sum = 0.0\n self.workcodes.each do |key, params|\n paidhld_rate = params[WKCODE_PARAM_PAIDHLD]\n if paidhld_rate > 0.0\n num = Timecard.count_by_sql(sql + \" AND workcode='#{key}'\")\n sum += num * paidhld_rate\n end\n end\n\n return sum\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def get_order\n Log.add_info(request, params.inspect)\n\n mail_account_id = params[:mail_account_id]\n SqlHelper.validate_token([mail_account_id])\n\n @mail_account = MailAccount.find(mail_account_id)\n\n if @mail_account.user_id != @login_user.id\n flash[:notice] = t('msg.need_to_be_owner')\n redirect_to(:controller => 'desktop', :action => 'show')\n return\n end\n\n @mail_filters = MailFilter.get_for(mail_account_id)\n\n render(:partial => 'ajax_order', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n render(:partial => 'ajax_order', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update_folders_order\n Log.add_info(request, params.inspect)\n\n order_arr = params[:folders_order]\n\n SqlHelper.validate_token([params[:id]])\n folders = MailFolder.get_childs(params[:id], false, false)\n # folders must be ordered by xorder ASC.\n\n folders.sort! { |id_a, id_b|\n\n idx_a = order_arr.index(id_a)\n idx_b = order_arr.index(id_b)\n\n if idx_a.nil? or idx_b.nil?\n idx_a = folders.index(id_a)\n idx_b = folders.index(id_b)\n end\n\n idx_a - idx_b\n }\n\n idx = 1\n folders.each do |folder_id|\n begin\n folder = MailFolder.find(folder_id)\n next if folder.user_id != @login_user.id\n\n folder.update_attribute(:xorder, idx)\n\n if folder.xtype == MailFolder::XTYPE_ACCOUNT_ROOT\n mail_account = MailAccount.find_by_id(folder.mail_account_id)\n unless mail_account.nil?\n mail_account.update_attribute(:xorder, idx)\n end\n end\n\n idx += 1\n rescue => evar\n Log.add_error(request, evar)\n end\n end\n\n render(:text => '')\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def ajax_move_mails\n Log.add_info(request, params.inspect)\n\n folder_id = params[:thetisBoxSelKeeper].split(':').last\n SqlHelper.validate_token([folder_id])\n begin\n mail_folder = MailFolder.find(folder_id)\n rescue => evar\n end\n\n if folder_id == '0' \\\n or mail_folder.nil? \\\n or mail_folder.user_id != @login_user.id\n flash[:notice] = 'ERROR:' + t('msg.cannot_save_in_folder')\n get_mails\n return\n end\n\n unless params[:check_mail].blank?\n count = 0\n params[:check_mail].each do |email_id, value|\n if value == '1'\n\n begin\n email = Email.find(email_id)\n next if email.user_id != @login_user.id\n\n email.update_attribute(:mail_folder_id, folder_id)\n\n rescue => evar\n Log.add_error(request, evar)\n end\n\n count += 1\n end\n end\n flash[:notice] = t('mail.moved', :count => count)\n end\n\n get_mails\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update_label\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n msg = params[:thetisBoxEdit]\n\n if params[:thetisBoxEdit].empty?\n render(:partial => 'ajax_label', :layout => false)\n return\n end\n\n if @login_user.nil?\n @toy = Toy.new\n @toy.id = params[:id]\n @toy.xtype = Toy::XTYPE_LABEL\n @toy.x = params[:x]\n @toy.y = params[:y]\n @toy.message = msg\n else\n @toy = Toy.find(params[:id])\n @toy.update_attribute(:message, msg)\n end\n\n render(:partial => 'ajax_label', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n \n render(:partial => 'ajax_label', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update_config\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n @yaml = ApplicationHelper.get_config_yaml\n\n unless params[:desktop].blank?\n @yaml[:desktop] = Hash.new if @yaml[:desktop].nil?\n\n params[:desktop].each do |key, val|\n @yaml[:desktop][key] = val\n end\n ApplicationHelper.save_config_yaml(@yaml)\n end\n\n flash[:notice] = t('msg.update_success')\n render(:partial => 'ajax_user_before_login', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def schedule_all\n Log.add_info(request, params.inspect)\n\n date_s = params[:date]\n if date_s.blank?\n @date = Date.today\n else\n @date = Date.parse(date_s)\n end\n\n if @login_user.nil? or params[:display].nil? or params[:display] == 'all'\n params[:display] = 'all'\n con = EquipmentHelper.get_scope_condition_for(@login_user)\n else\n display_type = params[:display].split('_').first\n display_id = params[:display].split('_').last\n\n case display_type\n when 'group'\n if @login_user.get_groups_a(true).include?(display_id)\n con = SqlHelper.get_sql_like([:groups], \"|#{display_id}|\")\n end\n when 'team'\n if @login_user.get_teams_a.include?(display_id)\n con = SqlHelper.get_sql_like([:teams], \"|#{display_id}|\")\n end\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def set_auth_teams\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n @folder = Folder.find(params[:id])\n\n if Folder.check_user_auth(@folder.id, @login_user, 'w', true)\n read_teams = []\n write_teams = []\n teams_auth = params[:teams_auth]\n unless teams_auth.nil?\n teams_auth.each do |auth_param|\n user_id = auth_param.split(':').first\n auths = auth_param.split(':').last.split('+')\n if auths.include?('r')\n read_teams << user_id\n end\n if auths.include?('w')\n write_teams << user_id\n end\n end\n end\n\n @folder.set_read_teams(read_teams)\n @folder.set_write_teams(write_teams)\n\n @folder.save\n\n flash[:notice] = t('msg.register_success')\n else\n flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')\n end\n\n target_user_id = (@login_user.admin?(User::AUTH_TEAM))?(nil):(@login_user.id)\n @teams = Team.get_for(target_user_id, true)\n render(:partial => 'ajax_auth_teams', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n render(:partial => 'ajax_auth_teams', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def get_group_users\n Log.add_info(request, params.inspect)\n\n SqlHelper.validate_token([params[:id]])\n begin\n @folder = Folder.find(params[:id])\n rescue => evar\n @folder = nil\n Log.add_error(request, evar)\n end\n\n @group_id = nil\n if !params[:thetisBoxSelKeeper].nil?\n @group_id = params[:thetisBoxSelKeeper].split(':').last\n elsif !params[:group_id].blank?\n @group_id = params[:group_id]\n end\n SqlHelper.validate_token([@group_id])\n\n @users = Group.get_users(@group_id)\n\n render(:partial => 'ajax_select_users', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update_folders_order\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n order_ary = params[:folders_order]\n\n folders = Folder.get_childs(params[:id], nil, false, true, false)\n # folders must be ordered by xorder ASC.\n\n folders.sort! { |id_a, id_b|\n\n idx_a = order_ary.index(id_a)\n idx_b = order_ary.index(id_b)\n\n if idx_a.nil? or idx_b.nil?\n idx_a = folders.index(id_a)\n idx_b = folders.index(id_b)\n end\n\n idx_a - idx_b\n }\n\n idx = 1\n folders.each do |folder_id|\n begin\n folder = Folder.find(folder_id)\n folder.update_attribute(:xorder, idx)\n idx += 1\n rescue => evar\n folder = nil\n Log.add_error(request, evar)\n end\n end\n\n render(:text => '')\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update_items_order\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n folder_id = params[:id]\n\n if Folder.check_user_auth(folder_id, @login_user, 'w', true)\n\n order_ary = params[:items_order]\n\n if !@login_user.nil? and @login_user.admin?(User::AUTH_ITEM)\n items = Folder.get_items_admin(folder_id)\n else\n items = Folder.get_items(@login_user, folder_id)\n end\n items.each do |item|\n item.update_attribute(:xorder, order_ary.index(item.id.to_s) + 1)\n end\n else\n Log.add_error(request, nil, 'No Authority Error')\n end\n\n render(:text => '')\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def create\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n if params[:thetisBoxEdit].blank?\n @group = nil\n else\n @group = Group.new\n @group.name = params[:thetisBoxEdit]\n @group.parent_id = params[:selectedGroupId]\n @group.save!\n\n @group.create_group_folder\n end\n render(:partial => 'ajax_group_entry', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def get_groups_order\n Log.add_info(request, params.inspect)\n\n @group_id = params[:id]\n SqlHelper.validate_token([@group_id])\n\n if @group_id != '0'\n @group = Group.find(@group_id)\n end\n\n @groups = Group.get_childs(@group_id, false, true)\n\n session[:group_id] = @group_id\n session[:group_option] = 'groups_order'\n\n render(:partial => 'ajax_groups_order', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n render(:partial => 'ajax_groups_order', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def get_attachment\n Log.add_info(request, params.inspect)\n\n attach = Attachment.find(params[:id])\n if attach.nil?\n redirect_to(THETIS_RELATIVE_URL_ROOT + '/404.html')\n return\n end\n\n parent_item = (attach.item || ((attach.comment.nil?) ? nil : attach.comment.item))\n if parent_item.nil? or !parent_item.check_user_auth(@login_user, 'r', true)\n Log.add_check(request, '[Item.check_user_auth]'+request.to_s)\n redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')\n return\n end\n\n attach_name = attach.name\n\n agent = request.env['HTTP_USER_AGENT']\n unless agent.nil?\n ie_ver = nil\n agent.scan(/\\sMSIE\\s?(\\d+)[.](\\d+)/){|m|\n ie_ver = m[0].to_i + (0.1 * m[1].to_i)\n }\n attach_name = CGI::escape(attach_name) unless ie_ver.nil?\n end\n\n begin\n attach_location = attach.location\n rescue\n attach_location = Attachment::LOCATION_DB # for lower versions\n end\n\n if attach_location == Attachment::LOCATION_DIR\n\n filepath = AttachmentsHelper.get_path(attach)\n\n send_file(filepath, :filename => attach_name, :stream => true, :disposition => 'attachment')\n else\n send_data(attach.content, :type => (attach.content_type || 'application/octet-stream')+';charset=UTF-8', :disposition => 'attachment;filename=\"'+attach_name+'\"')\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def add_comment_attachment\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n unless params[:comment_file].nil?\n attach_params = { :file => params[:comment_file] }\n params.delete(:comment_file)\n end\n\n unless attach_params.nil? or attach_params[:file].size <= 0\n @comment = Comment.find(params[:comment_id])\n\n @comment.attachments << Attachment.create(attach_params, @comment, 0)\n @comment.update_attribute(:updated_at, Time.now)\n end\n\n render(:partial => 'ajax_comment', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def bbs\n Log.add_info(request, params.inspect)\n\n unless params[:select_sorting].nil?\n sort_a = params[:select_sorting].split(' ')\n params[:sort_col] = sort_a.first\n params[:sort_type] = sort_a.last\n end\n\n list\n render(:action => 'bbs')\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def destroy_all\n\n return unless request.post?\n\n Log.delete_all\n\n flash[:notice] = t('msg.delete_success')\n redirect_to(:action => 'list')\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update\n Log.add_info(request, '') # Not to show passwords.\n\n return unless request.post?\n\n @mail_account = MailAccount.find(params[:id])\n\n if params[:mail_account][:smtp_auth].nil? or params[:mail_account][:smtp_auth] != '1'\n params[:mail_account].delete(:smtp_username)\n params[:mail_account].delete(:smtp_password)\n end\n\n if @mail_account.update_attributes(params.require(:mail_account).permit(MailAccount::PERMIT_BASE))\n\n flash[:notice] = t('msg.update_success')\n if request.xhr?\n render(:partial => 'common/flash_notice', :layout => false)\n else\n prms = ApplicationHelper.get_fwd_params(params)\n prms[:controller] = 'mail_folders'\n prms[:action] = 'show_tree'\n redirect_to(prms)\n end\n else\n Log.add_error(request, nil, @mail_account.errors.inspect)\n if request.xhr?\n render(:partial => 'mail_account_error', :layout => false)\n else\n prms = ApplicationHelper.get_fwd_params(params)\n prms[:controller] = 'mail_folders'\n prms[:action] = 'show_tree'\n redirect_to(prms)\n end\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update_order\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n mail_account_id = params[:mail_account_id]\n order_arr = params[:mail_filters_order]\n\n SqlHelper.validate_token([mail_account_id])\n\n @mail_account = MailAccount.find(mail_account_id)\n\n if @mail_account.user_id != @login_user.id\n render(:text => 'ERROR:' + t('msg.need_to_be_owner'))\n return\n end\n\n filters = MailFilter.get_for(mail_account_id)\n # filters must be ordered by xorder ASC.\n\n filters.sort! { |filter_a, filter_b|\n id_a = filter_a.id.to_s\n id_b = filter_b.id.to_s\n\n idx_a = order_arr.index(id_a)\n idx_b = order_arr.index(id_b)\n\n if idx_a.nil? or idx_b.nil?\n idx_a = filters.index(id_a)\n idx_b = filters.index(id_b)\n end\n\n idx_a - idx_b\n }\n\n idx = 1\n filters.each do |filter|\n next if filter.mail_account_id != mail_account_id.to_i\n\n filter.update_attribute(:xorder, idx)\n\n idx += 1\n end\n\n render(:text => '')\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n @group_id = params[:group_id]\n official_title_id = params[:id]\n SqlHelper.validate_token([@group_id, official_title_id])\n\n if official_title_id.blank?\n @official_title = OfficialTitle.new(params.require(:official_title).permit(OfficialTitle::PERMIT_BASE))\n @official_title.group_id = @group_id\n\n @official_title.save!\n else\n @official_title = OfficialTitle.find(official_title_id)\n @official_title.update_attributes(params.require(:official_title).permit(OfficialTitle::PERMIT_BASE))\n end\n\n @official_titles = OfficialTitle.get_for(@group_id, false, true)\n\n render(:partial => 'groups/ajax_group_official_titles', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update_order\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n order_ary = params[:official_titles_order]\n\n @group_id = params[:group_id]\n SqlHelper.validate_token([@group_id])\n\n parent_titles = OfficialTitle.get_for(Group.find(@group_id).parent_id, true, true)\n order_offset = parent_titles.length\n\n @official_titles = OfficialTitle.get_for(@group_id, false, true)\n\n @official_titles.each do |official_title|\n official_title.update_attribute(:xorder, order_offset + order_ary.index(official_title.id.to_s) + 1)\n end\n\n render(:text => '')\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def copy\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n tmpl_id = params[:thetisBoxSelKeeper].split(':').last\n tmpl_item = Item.find(tmpl_id)\n\n item = tmpl_item.copy(@login_user.id, @login_user.get_my_folder.id)\n if item.public != false\n item.update_attribute(:public, false)\n end\n\n redirect_to(:controller => 'items', :action => 'edit', :id => item.id)\n\n rescue => evar\n Log.add_error(request, evar)\n\n redirect_to(:controller => 'items', :action => 'new')\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def destroy\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n begin\n timecard = Timecard.find(params[:id])\n\n if timecard.user_id != @login_user.id and !@login_user.admin?(User::AUTH_TIMECARD)\n Log.add_check(request, '[User::AUTH_TIMECARD]'+request.to_s)\n redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')\n return\n end\n\n date = timecard.date\n timecard.destroy unless timecard.nil?\n rescue => evar\n end\n\n flash[:notice] = t('msg.delete_success')\n\n prms = ApplicationHelper.get_fwd_params(params)\n prms.delete(:id)\n prms[:action] = 'edit'\n prms[:date] = date unless date.nil?\n\n redirect_to(prms)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def update_default_break\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n start_t = Time.local(2000, 1, 1, params[:start_hour].to_i, params[:start_min].to_i)\n end_t = Time.local(2000, 1, 1, params[:end_hour].to_i, params[:end_min].to_i)\n\n if start_t == end_t\n flash[:notice] = 'ERROR:' + t('timecard.break_without_span')\n render(:partial => 'ajax_config_break', :layout => false)\n return\n end\n\n if params[:org_start].nil?\n org_start = nil\n else\n org_start = UtilDateTime.parse(params[:org_start]).to_time\n end\n\n yaml = ApplicationHelper.get_config_yaml\n\n yaml[:timecard] = Hash.new if yaml[:timecard].nil?\n spans = yaml[:timecard]['default_breaks']\n spans = [] if spans.nil?\n\n found = false\n spans.each do |span|\n if span.first == org_start\n span[0] = start_t\n span[1] = end_t\n found = true\n break\n end\n end\n unless found\n spans << [start_t, end_t]\n end\n\n begin\n spans = Timecard.sort_breaks(spans)\n\n yaml[:timecard]['default_breaks'] = spans\n\n ApplicationHelper.save_config_yaml(yaml)\n\n rescue\n yaml = ApplicationHelper.get_config_yaml\n flash[:notice] = 'ERROR:' + t('timecard.break_overlap')\n end\n\n @yaml_timecard = yaml[:timecard]\n @yaml_timecard = Hash.new if @yaml_timecard.nil?\n\n render(:partial => 'ajax_config_break', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def remove_official_titles\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n @user = User.find(params[:user_id])\n\n unless params[:official_titles].nil?\n params[:official_titles].each do |official_title_id|\n idx = @user.user_titles.index{|user_title| user_title.official_title_id.to_s == official_title_id}\n unless idx.nil?\n user_title = @user.user_titles[idx]\n @user.user_titles.delete(user_title)\n end\n end\n end\n\n render(:partial => 'ajax_user_titles', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def _process_user_attrs(user, attrs)\n\n if attrs[:birthday].nil?\n begin\n attrs[:birthday] = attrs[:birthday_y] + '-' + attrs[:birthday_m] + '-' + attrs[:birthday_d]\n rescue\n end\n attrs.delete(:birthday_y)\n attrs.delete(:birthday_m)\n attrs.delete(:birthday_d)\n end\n\n if !attrs[:name].nil? or !attrs[:password].nil?\n user_name = attrs[:name]\n user_name ||= user.name unless user.nil?\n password = attrs[:password]\n if password.blank?\n password = UsersHelper.generate_password\n attrs[:password] = password\n end\n attrs[:pass_md5] = UsersHelper.generate_digest_pass(user_name, password)\n end\n return attrs\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def rename_title\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n org_title = params[:org_title]\n new_title = params[:new_title]\n\n if org_title.nil? or new_title.nil? or org_title == new_title\n render(:partial => 'ajax_title', :layout => false)\n return\n end\n\n titles = User.get_config_titles\n unless titles.nil?\n if titles.include?(new_title)\n flash[:notice] = 'ERROR:' + t('user.title_duplicated')\n else\n idx = titles.index(org_title)\n unless idx.nil?\n titles[idx] = new_title\n User.save_config_titles(titles)\n\n User.rename_title(org_title, new_title)\n User.update_xorder(new_title, idx)\n end\n end\n end\n\n render(:partial => 'ajax_title', :layout => false)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.stacktrace\n begin\n raise('')\n rescue => evar\n paths = Rails.root.split('/')\n paths.delete('')\n stacktrace = evar.backtrace.select {|line| !(line.match(paths.last).nil?)}.join(\"\\n\")\n stacktrace.pop # Remove current stack.\n end\n return stacktrace\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.exists_copies_folder?(user_id)\n\n my_folder = User.get_my_folder(user_id)\n\n unless my_folder.nil?\n folder_name_quot = SqlHelper.quote(Item.copies_folder)\n con = \"(parent_id=#{my_folder.id}) and (name=#{folder_name_quot})\"\n\n begin\n copies_folder = Folder.where(con).first\n rescue\n end\n end\n\n return !copies_folder.nil?\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.destroy_by_user(user_id, add_con=nil)\n\n SqlHelper.validate_token([user_id])\n\n con = \"(user_id=#{user_id.to_i})\"\n con << \" and (#{add_con})\" unless add_con.nil? or add_con.empty?\n emails = Email.where(con).to_a\n\n emails.each do |email|\n email.destroy\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.get_childs(folder_id, conditions, recursive, admin, ret_obj)\n\n SqlHelper.validate_token([folder_id])\n arr = []\n\n if recursive\n\n folder_tree = Folder.get_tree(Hash.new, conditions, folder_id, admin)\n return [] if folder_tree.nil?\n\n folder_tree.each do |parent_id, childs|\n if ret_obj\n arr |= childs\n else\n childs.each do |folder|\n folder_id = folder.id.to_s\n arr << folder_id unless arr.include?(folder_id)\n end\n end\n end\n\n else\n\n con = Marshal.load(Marshal.dump(conditions))\n if con.nil?\n con = ''\n else\n con << ' and '\n end\n con << \"parent_id=#{folder_id.to_i}\"\n\n unless admin\n con << \" and (xtype is null or not (xtype='#{Folder::XTYPE_SYSTEM}'))\"\n end\n\n folders = Folder.where(con).order('xorder ASC').to_a\n if ret_obj\n arr = folders\n else\n folders.each do |folder|\n arr << folder.id.to_s\n end\n end\n end\n\n return arr\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.get_for_group(group_id, incl_img_content=false)\n\n SqlHelper.validate_token([group_id])\n\n if group_id.nil?\n office_map = nil\n else\n if incl_img_content\n office_map = OfficeMap.where(\"group_id=#{group_id.to_i}\").first\n else\n sql = 'select id, group_id, img_enabled, img_name, img_size, img_content_type, created_at, updated_at from office_maps'\n sql << \" where group_id=#{group_id.to_i}\"\n begin\n office_map = OfficeMap.find_by_sql(sql).first\n rescue\n end\n end\n end\n\n if office_map.nil?\n office_map = OfficeMap.new\n office_map.group_id = group_id.to_i unless group_id.nil?\n office_map.img_enabled = false\n end\n\n return office_map\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def remove_application(user_ids)\n\n return if user_ids.nil? or user_ids.empty?\n\n SqlHelper.validate_token([user_ids])\n\n con = [\"(xtype='#{Comment::XTYPE_APPLY}')\"]\n con << \"(item_id=#{self.item_id})\"\n\n user_con_a = []\n user_ids.each do |user_id|\n user_con_a << \"(user_id=#{user_id.to_i})\"\n end\n\n con << '(' + user_con_a.join(' or ') + ')'\n\n Comment.destroy_all(con.join(' and '))\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.get_by_email(mail_addr, user, book=Address::BOOK_BOTH)\n\n mail_quote = SqlHelper.quote(mail_addr)\n\n email_con = []\n email_con.push(\"(email1=#{mail_quote})\")\n email_con.push(\"(email2=#{mail_quote})\")\n email_con.push(\"(email3=#{mail_quote})\")\n con = []\n con.push('('+email_con.join(' or ')+')')\n con.push(AddressbookHelper.get_scope_condition_for(user, book))\n\n return Address.where(con.join(' and ')).to_a\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": " def self.from_yaml(input)\n Gem.load_yaml\n\n input = normalize_yaml_input input\n spec = Gem::SafeYAML.safe_load input\n\n if spec && spec.class == FalseClass then\n raise Gem::EndOfYAMLException\n end\n\n unless Gem::Specification === spec then\n raise Gem::Exception, \"YAML data doesn't evaluate to gem specification\"\n end\n\n spec.specification_version ||= NONEXISTENT_SPECIFICATION_VERSION\n spec.reset_nil_attributes_to_default\n\n spec\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "safe"} {"code": " def test_validate_homepage\n util_setup_validate\n\n Dir.chdir @tempdir do\n @a1.homepage = nil\n\n use_ui @ui do\n @a1.validate\n end\n\n assert_match \"#{w}: no homepage specified\\n\", @ui.error, 'error'\n\n @ui = Gem::MockGemUi.new\n\n @a1.homepage = ''\n\n use_ui @ui do\n @a1.validate\n end\n\n assert_match \"#{w}: no homepage specified\\n\", @ui.error, 'error'\n\n @a1.homepage = 'over at my cool site'\n\n e = assert_raises Gem::InvalidSpecificationException do\n @a1.validate\n end\n\n assert_equal '\"over at my cool site\" is not a URI', e.message\n\n @a1.homepage = 'ftp://rubygems.org'\n\n e = assert_raises Gem::InvalidSpecificationException do\n @a1.validate\n end\n\n assert_equal '\"ftp://rubygems.org\" is not a URI', e.message\n\n @a1.homepage = 'http://rubygems.org'\n\n assert_equal true, @a1.validate\n\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " it \"adds the require param for the gem\" do\n bundle \"add 'foo' --require=foo/engine\"\n expect(bundled_app_gemfile.read).to match(%r{gem \"foo\",(?: .*,) :require => \"foo\\/engine\"})\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-88", "cwe_name": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", "description": "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", "url": "https://cwe.mitre.org/data/definitions/88.html", "label_name": "safe"} {"code": " def from_string(string)\n raise Errors::InvalidObjectId.new(string) unless legal?(string)\n data = \"\"\n 12.times { |i| data << string[i*2, 2].to_i(16) }\n from_data data\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def next\n @mutex.lock\n begin\n counter = @counter = (@counter + 1) % 0xFFFFFF\n ensure\n @mutex.unlock rescue nil\n end\n\n generate(Time.new.to_i, counter)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def generation_time\n Time.at(data.unpack(\"N\")[0]).utc\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def connected?\n !!@sock\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def get_more\n reply = @node.get_more @database, @collection, @cursor_id, @limit\n\n @limit -= reply.count if limited?\n @cursor_id = reply.cursor_id\n\n reply.documents\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def initialize(session, query_operation)\n @session = session\n\n @database = query_operation.database\n @collection = query_operation.collection\n @selector = query_operation.selector\n\n @cursor_id = 0\n @limit = query_operation.limit\n @limited = @limit > 0\n\n @options = {\n request_id: query_operation.request_id,\n flags: query_operation.flags,\n limit: query_operation.limit,\n skip: query_operation.skip,\n fields: query_operation.fields\n }\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def kill\n @node.kill_cursors [@cursor_id]\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def limited?\n @limited\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def drop\n session.with(consistency: :strong) do |session|\n session.context.command name, dropDatabase: 1\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def initialize(string)\n super(\"'#{string}' is not a valid object id.\")\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def apply_auth(credentials)\n unless auth == credentials\n logouts = auth.keys - credentials.keys\n\n logouts.each do |database|\n logout database\n end\n\n credentials.each do |database, (username, password)|\n login(database, username, password) unless auth[database] == [username, password]\n end\n end\n\n self\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def remove(database, collection, selector, options = {})\n process Protocol::Delete.new(database, collection, selector, options)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def remove(database, collection, selector, options = {})\n process Protocol::Delete.new(database, collection, selector, options)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def initialize_copy(_)\n @connection = nil\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def flush(ops = queue)\n operations, callbacks = ops.transpose\n\n logging(operations) do\n ensure_connected do\n connection.write operations\n replies = connection.receive_replies(operations)\n\n replies.zip(callbacks).map do |reply, callback|\n callback ? callback[reply] : reply\n end.last\n end\n end\n ensure\n ops.clear\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def initialize(database, command, options = {})\n super database, :$cmd, command, options.merge(limit: -1)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def remove_all\n session.with(consistency: :strong) do |session|\n session.context.remove operation.database,\n operation.collection,\n operation.selector\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def update(change, flags = nil)\n session.with(consistency: :strong) do |session|\n session.context.update operation.database,\n operation.collection,\n operation.selector,\n change,\n flags: flags\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def first\n limit(-1).each.first\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def consistency\n options[:consistency]\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def new(options = {})\n session = with(options)\n session.instance_variable_set(:@cluster, cluster.dup)\n\n if block_given?\n yield session\n else\n session\n end\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def initialize(seeds, options = {})\n @cluster = Cluster.new(seeds, {})\n @context = Context.new(self)\n @options = options\n @options[:consistency] ||= :eventual\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def logout(database)\n cluster.auth.delete database.to_s\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " it \"sets the generation time\" do\n time = Time.at((Time.now.utc - 64800).to_i).utc\n Moped::BSON::ObjectId.from_time(time).generation_time.should == time\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " it \"returns true\" do\n Moped::BSON::ObjectId.from_data(bytes).should == Moped::BSON::ObjectId.from_data(bytes)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " it \"insert multiple documents\" do\n documents = [\n { \"_id\" => Moped::BSON::ObjectId.new, \"scope\" => scope },\n { \"_id\" => Moped::BSON::ObjectId.new, \"scope\" => scope }\n ]\n\n session[:users].insert(documents)\n session[:users].find(scope: scope).entries.should eq documents\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " it \"raises a connection error\" do\n lambda do\n node.ensure_connected do\n node.command(\"admin\", ping: 1)\n end\n end.should raise_exception(Moped::Errors::ConnectionFailure)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " it \"respects #sort\" do\n users.find(scope: scope).sort(_id: -1).one.should eq documents.last\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " it \"sets the slave ok flag\" do\n stats = Support::Stats.collect do\n session.with(consistency: :eventual)[:users].find(scope: scope).one\n end\n\n query = stats[:secondary].grep(Moped::Protocol::Query).first\n query.flags.should include :slave_ok\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " it \"limits the query\" do\n users.insert(documents)\n users.find(scope: scope).limit(1).to_a.should eq [documents.first]\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " it \"updates the document\" do\n users.find(scope: scope).upsert(\"$inc\" => { counter: 1 })\n users.find(scope: scope).one[\"counter\"].should eq 2\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " it \"returns a session with the provided options\" do\n safe = session.with(safe: true)\n safe.options[:safe].should eq true\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def auth_session(auth = true)\n session = Moped::Session.new auth_seeds, database: auth_database\n session.login *auth_credentials if auth\n session\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def message\n %Q{\n ---------------------------------------------------------------------\n Moped runs specs for authentication and replica sets against MongoHQ.\n\n If you want to run these specs and need the credentials, contact\n durran at gmail dot com.\n ---------------------------------------------------------------------\n }\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def replica_set_configured?\n ENV[\"MONGOHQ_REPL_PASS\"]\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def replica_set_session(auth = true)\n session = Moped::Session.new replica_set_seeds, database: replica_set_database\n session.login *replica_set_credentials if auth\n session\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def initiate\n primary, *secondaries = @nodes.shuffle\n\n primary.promote\n secondaries.each &:demote\n\n return primary, secondaries\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def secondary?\n @secondary\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def shutdown\n @servers.each &:close\n @clients.each &:close\n @shutdown = true\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def initialize(servers)\n @timeout = 0.1\n @servers = servers\n @clients = []\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def collect\n @stats = Hash.new { |hash, key| hash[key] = [] }\n yield\n @stats\n ensure\n @stats = nil\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def install!\n Moped::Node.class_eval <<-EOS\n alias _logging logging\n\n def logging(operations, &block)\n Support::Stats.record(self, operations)\n _logging(operations, &block)\n end\n EOS\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def logging(operations, &block)\n Support::Stats.record(self, operations)\n _logging(operations, &block)\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": " def <=>(other)\n to_bson <=> other.to_bson\n end", "label": 1, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "safe"} {"code": " def html_escape(s)\n s = s.to_s\n if s.html_safe?\n s\n else\n s.gsub(/[&\"><]/) { |special| HTML_ESCAPE[special] }.html_safe\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " def build_query(path, details)\n query = @pattern.dup\n query.gsub!(/\\:prefix(\\/)?/, path.prefix.empty? ? \"\" : \"#{path.prefix}\\\\1\") # prefix can be empty...\n query.gsub!(/\\:action/, path.partial? ? \"_#{path.name}\" : path.name)\n\n details.each do |ext, variants|\n query.gsub!(/\\:#{ext}/, \"{#{variants.compact.uniq.join(',')}}\")\n end\n\n File.expand_path(query, @path)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def remote_address\n @request.forwarded_for || socket_address\n rescue Exception\n log_error\n nil\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def package_index\n valid_http_methods :get\n required_parameters :project, :repository, :arch, :package\n\n # read access permission check\n if params[:package] == \"_repository\"\n prj = DbProject.get_by_name params[:project], use_source=false\n else\n pkg = DbPackage.get_by_project_and_name params[:project], params[:package], use_source=false\n end\n\n pass_to_backend\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-434", "cwe_name": "Unrestricted Upload of File with Dangerous Type", "description": "The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.", "url": "https://cwe.mitre.org/data/definitions/434.html", "label_name": "vulnerable"} {"code": " def Sendmail.call(path, arguments, destinations, mail)\n IO.popen(\"#{path} #{arguments} #{destinations}\", \"w+\") do |io|\n io.puts mail.encoded.to_lf\n io.flush\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " it \"should escape evil haxxor attemptes\" do\n Mail.defaults do\n delivery_method :sendmail, :arguments => nil\n end\n \n mail = Mail.new do\n from '\"foo\\\";touch /tmp/PWNED;\\\"\"@blah.com'\n to 'marcel@test.lindsaar.net'\n subject 'invalid RFC2822'\n end\n \n Mail::Sendmail.should_receive(:call).with('/usr/sbin/sendmail', \n \"-f \\\"\\\\\\\"foo\\\\\\\\\\\\\\\"\\\\;touch /tmp/PWNED\\\\;\\\\\\\\\\\\\\\"\\\\\\\"@blah.com\\\"\", \n 'marcel@test.lindsaar.net', \n mail)\n mail.deliver!\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def split_path(request)\n # Reparse the configuration if necessary.\n readconfig\n\n mount_name, path = request.key.split(File::Separator, 2)\n\n raise(ArgumentError, \"Cannot find file: Invalid path '#{mount_name}'\") unless mount_name =~ %r{^[-\\w]+$}\n\n return nil unless mount = find_mount(mount_name, request.environment)\n if mount.name == \"modules\" and mount_name != \"modules\"\n # yay backward-compatibility\n path = \"#{mount_name}/#{path}\"\n end\n\n if path == \"\"\n path = nil\n elsif path\n # Remove any double slashes that might have occurred\n path = path.gsub(/\\/+/, \"/\")\n end\n\n return mount, path\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " it \"should return :file if the URI protocol is set to 'file'\" do\n @request.expects(:protocol).returns \"file\"\n @object.select_terminus(@request).should == :file\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " def authenticate!\n unless Setting['oauth_active']\n Rails.logger.warn 'Trying to authenticate with OAuth, but OAuth is not active'\n return nil\n end\n\n unless (incoming_key = OAuth::RequestProxy.proxy(request).oauth_consumer_key) == Setting['oauth_consumer_key']\n Rails.logger.warn \"oauth_consumer_key should be '#{Setting['oauth_consumer_key']}' but was '#{incoming_key}'\"\n return nil\n end\n\n if OAuth::Signature.verify(request, :consumer_secret => Setting['oauth_consumer_secret'])\n if Setting['oauth_map_users']\n user_name = request.headers['HTTP_FOREMAN_USER'].to_s\n User.find_by_login(user_name).tap do |obj|\n Rails.logger.warn \"Oauth: mapping to user '#{user_name}' failed\" if obj.nil?\n end.try(:login)\n else\n User::ANONYMOUS_API_ADMIN\n end\n else\n Rails.logger.warn \"OAuth signature verification failed.\"\n return nil\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " def test_clone\n get :clone, {:id => Hostgroup.first}, set_session_user\n assert_template 'new'\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " def setup\n FactoryGirl.create(:host)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " def create\n File.open(resource[:path], \"w\") { |f| f << expected_content }\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-264", "cwe_name": "Permissions, Privileges, and Access Controls", "description": "Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.", "url": "https://cwe.mitre.org/data/definitions/264.html", "label_name": "vulnerable"} {"code": " def authorize_params\n super.tap do |params|\n %w[display state scope].each do |v|\n if request.params[v]\n params[v.to_sym] = request.params[v]\n\n # to support omniauth-oauth2's auto csrf protection\n session['omniauth.state'] = params[:state] if v == 'state'\n end\n end\n\n params[:scope] ||= DEFAULT_SCOPE\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-352", "cwe_name": "Cross-Site Request Forgery (CSRF)", "description": "The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.", "url": "https://cwe.mitre.org/data/definitions/352.html", "label_name": "vulnerable"} {"code": " def create_event(comment)\n Event.create! bug_id: comment.bug_id, kind: 'comment', data: {'comment_id' => comment.id}, user_id: comment.user_id\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-94", "cwe_name": "Improper Control of Generation of Code ('Code Injection')", "description": "The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.", "url": "https://cwe.mitre.org/data/definitions/94.html", "label_name": "vulnerable"} {"code": " it \"recognizes and generates #index\" do\n { :get => \"/users\" }.should route_to(:controller => \"users\", :action => \"index\")\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " def timeline\n unless params[:type].empty?\n model = params[:type].camelize.constantize\n item = model.find(params[:id])\n item.update_attribute(:state, params[:state])\n else\n comments, emails = params[:id].split(\"+\")\n Comment.update_all(\"state = '#{params[:state]}'\", \"id IN (#{comments})\") unless comments.blank?\n Email.update_all(\"state = '#{params[:state]}'\", \"id IN (#{emails})\") unless emails.blank?\n end\n\n render :nothing => true\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " it \"should find a user by first name or last name\" do\n @cur_user.stub(:pref).and_return(:activity_user => 'Billy')\n controller.instance_variable_set(:@current_user, @cur_user)\n User.should_receive(:where).with(\"upper(first_name) LIKE upper('%Billy%') OR upper(last_name) LIKE upper('%Billy%')\").and_return([@user])\n controller.send(:activity_user).should == 1\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " it \"with Pathname command\" do\n cl = subject.build_command_line(Pathname.new(\"/usr/bin/ruby\"))\n expect(cl).to eq \"/usr/bin/ruby\"\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "vulnerable"} {"code": " def column_content(column, item)\n value = column.value_object(item)\n if value.is_a?(Array)\n value.collect {|v| column_value(column, item, v)}.compact.join(', ').html_safe\n else\n column_value(column, item, value)\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " def cat(path, identifier=nil)\n p = CGI.escape(scm_iconv(@path_encoding, 'UTF-8', path))\n hg 'rhcat', '-r', CGI.escape(hgrev(identifier)), '--', hgtarget(p) do |io|\n io.binmode\n io.read\n end\n rescue HgCommandAborted\n nil # means not found\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " def diff(path, identifier_from, identifier_to=nil)\n hg_args = %w|rhdiff|\n if identifier_to\n hg_args << '-r' << hgrev(identifier_to) << '-r' << hgrev(identifier_from)\n else\n hg_args << '-c' << hgrev(identifier_from)\n end\n unless path.blank?\n p = scm_iconv(@path_encoding, 'UTF-8', path)\n hg_args << '--' << CGI.escape(hgtarget(p))\n end\n diff = []\n hg *hg_args do |io|\n io.each_line do |line|\n diff << line\n end\n end\n diff\n rescue HgCommandAborted\n nil # means not found\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " def mapped_content_type\n Paperclip.options[:content_type_mappings][filename_extension]\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-79", "cwe_name": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "description": "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", "url": "https://cwe.mitre.org/data/definitions/79.html", "label_name": "vulnerable"} {"code": " def get_users\n if params[:action] == 'get_users'\n Log.add_info(request, params.inspect)\n end\n\n @group_id = params[:id]\n\n=begin\n# @users = Group.get_users(params[:id])\n=end\n\n# FEATURE_PAGING_IN_TREE >>>\n con = ['User.id > 0']\n\n unless @group_id.nil?\n if @group_id == '0'\n con << \"((groups like '%|0|%') or (groups is null))\"\n else\n con << ApplicationHelper.get_sql_like([:groups], \"|#{@group_id}|\")\n end\n end\n\n unless params[:keyword].blank?\n key_array = params[:keyword].split(nil)\n key_array.each do |key| \n con << SqlHelper.get_sql_like([:name, :email, :fullname, :address, :organization, :tel1, :tel2, :tel3, :fax, :url, :postalcode, :title], key)\n end\n end\n\n where = ''\n unless con.empty?\n where = ' where ' + con.join(' and ')\n end\n\n order_by = nil\n @sort_col = params[:sort_col]\n @sort_type = params[:sort_type]\n\n if @sort_col.blank? or @sort_type.blank?\n @sort_col = 'OfficialTitle.xorder'\n @sort_type = 'ASC'\n end\n\n SqlHelper.validate_token([@sort_col, @sort_type])\n order_by = @sort_col + ' ' + @sort_type\n\n if @sort_col == 'OfficialTitle.xorder'\n order_by = '(OfficialTitle.xorder is null) ' + @sort_type + ', ' + order_by\n else\n order_by << ', (OfficialTitle.xorder is null) ASC, OfficialTitle.xorder ASC'\n end\n if @sort_col != 'name'\n order_by << ', name ASC'\n end\n\n sql = 'select distinct User.* from (users User left join user_titles UserTitle on User.id=UserTitle.user_id)'\n sql << ' left join official_titles OfficialTitle on UserTitle.official_title_id=OfficialTitle.id'\n\n sql << where + ' order by ' + order_by\n\n @user_pages, @users, @total_num = paginate_by_sql(User, sql, 50)\n# FEATURE_PAGING_IN_TREE <<<\n\n session[:group_id] = @group_id\n session[:group_option] = 'user'\n\n render(:partial => 'ajax_group_users', :layout => false)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def self.validate_token(tokens, extra_chars=nil)\n\n extra_chars ||= []\n regexp = Regexp.new(\"^\\s*[a-zA-Z0-9_.#{extra_chars.join()}]+\\s*$\")\n\n [tokens].flatten.each do |token|\n next if token.blank?\n\n if token.to_s.match(regexp).nil?\n raise(\"[ERROR] SqlHelper.validate_token failed: #{token}\")\n end\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def self.find_term(user_id, start_date, end_date)\n con = \"(user_id=#{user_id}) and (date >= '#{start_date}') and (date <= '#{end_date}')\"\n ary = Timecard.where(con).order('date ASC').to_a\n timecards_h = Hash.new\n unless ary.nil?\n ary.each do |timecard|\n timecards_h[timecard.date.strftime(Schedule::SYS_DATE_FORM)] = timecard\n end\n end\n return timecards_h\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def self.applied_paid_hlds(user_id, start_date, end_date)\n\n SqlHelper.validate_token([user_id, start_date, end_date])\n\n sql = \"SELECT COUNT(*) FROM timecards WHERE user_id = #{user_id} AND date >= '#{start_date}' AND date <= '#{end_date}'\"\n\n sum = 0.0\n self.workcodes.each do |key, params|\n paidhld_rate = params[WKCODE_PARAM_PAIDHLD]\n if paidhld_rate > 0.0\n num = Timecard.count_by_sql(sql + \" AND workcode='#{key}'\")\n sum += num * paidhld_rate\n end\n end\n\n return sum\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def get_order\n Log.add_info(request, params.inspect)\n\n mail_account_id = params[:mail_account_id]\n\n @mail_account = MailAccount.find_by_id(mail_account_id)\n\n if @mail_account.user_id != @login_user.id\n flash[:notice] = t('msg.need_to_be_owner')\n redirect_to(:controller => 'desktop', :action => 'show')\n return\n end\n\n @mail_filters = MailFilter.get_for(mail_account_id)\n\n render(:partial => 'ajax_order', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n render(:partial => 'ajax_order', :layout => false)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def ajax_delete_mails\n Log.add_info(request, params.inspect)\n\n folder_id = params[:id]\n mail_account_id = params[:mail_account_id]\n\n unless params[:check_mail].blank?\n mail_folder = MailFolder.find(folder_id)\n trash_folder = MailFolder.get_for(@login_user, mail_account_id, MailFolder::XTYPE_TRASH)\n\n count = 0\n params[:check_mail].each do |email_id, value|\n next if value != '1'\n\n email = Email.find_by_id(email_id)\n next if email.nil? or (email.user_id != @login_user.id)\n\n if trash_folder.nil? \\\n or folder_id == trash_folder.id.to_s \\\n or mail_folder.get_parents(false).include?(trash_folder.id.to_s)\n email.destroy\n flash[:notice] ||= t('msg.delete_success')\n else\n begin\n email.update_attribute(:mail_folder_id, trash_folder.id)\n flash[:notice] ||= t('msg.moved_to_trash')\n rescue => evar\n Log.add_error(request, evar)\n email.destroy\n flash[:notice] ||= t('msg.delete_success')\n end\n end\n\n count += 1\n end\n end\n\n get_mails\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def get_auth_groups\n Log.add_info(request, params.inspect)\n\n begin\n @folder = Folder.find(params[:id])\n rescue\n @folder = nil\n end\n\n @groups = Group.where(nil).to_a\n\n session[:folder_id] = params[:id]\n\n render(:partial => 'ajax_auth_groups', :layout => false)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def create\n Log.add_info(request, params.inspect)\n\n if params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?\n @group = nil\n else\n @group = Group.new\n @group.name = params[:thetisBoxEdit]\n @group.parent_id = params[:selectedGroupId]\n @group.save!\n\n @group.create_group_folder\n end\n render(:partial => 'ajax_group_entry', :layout => false)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def check_owner\n\n return if params[:id].nil? or params[:id].empty? or @login_user.nil?\n\n mail_account = MailAccount.find(params[:id])\n\n if !@login_user.admin?(User::AUTH_MAIL) and mail_account.user_id != @login_user.id\n Log.add_check(request, '[check_owner]'+request.to_s)\n\n flash[:notice] = t('msg.need_to_be_owner')\n redirect_to(:controller => 'desktop', :action => 'show')\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def create\n Log.add_info(request, params.inspect)\n\n parent_id = params[:selectedFolderId]\n\n if params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?\n @mail_folder = nil\n else\n @mail_folder = MailFolder.new\n @mail_folder.name = params[:thetisBoxEdit]\n @mail_folder.parent_id = parent_id\n @mail_folder.user_id = @login_user.id\n @mail_folder.xtype = nil\n @mail_folder.save!\n end\n render(:partial => 'ajax_folder_entry', :layout => false)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def edit\n Log.add_info(request, params.inspect)\n\n @group_id = params[:group_id]\n official_title_id = params[:id]\n\n unless official_title_id.nil? or official_title_id.empty?\n @official_title = OfficialTitle.find(official_title_id)\n end\n\n render(:partial => 'ajax_official_title_form', :layout => (!request.xhr?))\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def team\n Log.add_info(request, params.inspect)\n\n date_s = params[:date]\n if date_s.nil? or date_s.empty?\n @date = Date.today\n else\n @date = Date.parse(date_s)\n end\n\n begin\n team = Team.find(params[:id])\n team_users = team.get_users_a\n rescue => evar\n Log.add_error(request, evar)\n end\n\n @user_schedule_hash = {}\n unless team_users.nil?\n @holidays = Schedule.get_holidays\n team_users.each do |user_id|\n @user_schedule_hash[user_id] = Schedule.get_somebody_week(@login_user, user_id, @date, @holidays)\n end\n end\n\n params[:display] = params[:action] + '_' + params[:id]\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def new\n Log.add_info(request, params.inspect)\n\n mail_account_id = params[:mail_account_id]\n\n if mail_account_id.nil? or mail_account_id.empty?\n account_xtype = params[:mail_account_xtype]\n @mail_account = MailAccount.get_default_for(@login_user.id, account_xtype)\n else\n @mail_account = MailAccount.find(mail_account_id)\n if @mail_account.user_id != @login_user.id\n flash[:notice] = 'ERROR:' + t('msg.need_to_be_owner')\n render(:partial => 'common/flash_notice', :layout => false)\n return\n end\n end\n\n if $thetis_config[:menu]['disp_user_list'] == '1'\n unless params[:to_user_ids].blank?\n @email = Email.new\n to_addrs = []\n @user_obj_cache ||= {}\n params[:to_user_ids].each do |user_id|\n user = User.find_with_cache(user_id, @user_obj_cache)\n user_emails = user.get_emails_by_type(nil)\n user_emails.each do |user_email|\n disp = EmailsHelper.format_address_exp(user.get_name, user_email, false)\n entry_val = \"#{disp}\" # \"#{disp}#{Email::ADDR_ORDER_SEPARATOR}#{user.get_xorder(@group_id)}\"\n\n to_addrs << entry_val\n end\n end\n @email.to_addresses = to_addrs.join(Email::ADDRESS_SEPARATOR)\n end\n end\n\n render(:action => 'edit', :layout => (!request.xhr?))\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def create_title\n\n titles = User.get_config_titles\n titles = [] if titles.nil?\n titles << t('user.new_title')\n User.save_config_titles titles\n\n render(:partial => 'ajax_title', :layout => false)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def update_auth\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n auth = nil\n\n if params[:check_auth_all] == '1'\n\n auth = User::AUTH_ALL\n\n else\n\n auth_selected = params[:auth_selected]\n\n unless auth_selected.nil? or auth_selected.empty?\n auth = '|' + auth_selected.join('|') + '|'\n end\n\n if auth_selected.nil? or !auth_selected.include?(User::AUTH_USER)\n\n user_admin_err = false\n\n user_admins = User.where(\"auth like '%|#{User::AUTH_USER}|%' or auth='#{User::AUTH_ALL}'\").to_a\n\n if user_admins.nil? or user_admins.empty?\n\n user_admin_err = true\n\n elsif user_admins.length == 1\n\n if user_admins.first.id.to_s == params[:id]\n user_admin_err = true\n end\n\n end\n\n if user_admin_err\n render(:text => t('user.no_user_auth'))\n return\n end\n end\n\n end\n\n begin\n user = User.find(params[:id])\n rescue => evar\n Log.add_error(request, evar)\n end\n\n if user.nil?\n\n render(:text => t('msg.already_deleted', :name => User.model_name.human))\n else\n\n user.update_attribute(:auth, auth)\n\n if user.id == @login_user.id\n @login_user = user\n end\n\n render(:text => '')\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def self.count_completed_users(item_id)\n SqlHelper.validate_token([item_id])\n ack_msg = ZeptairDistHelper.completed_ack_message(item_id)\n return Comment.where(\"(item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}') and (message='#{ack_msg}')\").count\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def self.get_for_group(group_id, incl_img_content=false)\n\n SqlHelper.validate_token([group_id])\n\n if group_id.nil?\n office_map = nil\n else\n if incl_img_content\n office_map = OfficeMap.where(\"group_id=#{group_id}\").first\n else\n sql = 'select id, group_id, img_enabled, img_name, img_size, img_content_type, created_at, updated_at from office_maps'\n sql << \" where group_id=#{group_id}\"\n begin\n office_map = OfficeMap.find_by_sql(sql).first\n rescue\n end\n end\n end\n\n if office_map.nil?\n office_map = OfficeMap.new\n office_map.group_id = group_id.to_i unless group_id.nil?\n office_map.img_enabled = false\n end\n\n return office_map\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "vulnerable"} {"code": " def read_checksums gem\n Gem.load_yaml\n\n @checksums = gem.seek 'checksums.yaml.gz' do |entry|\n Zlib::GzipReader.wrap entry do |gz_io|\n YAML.load gz_io.read\n end\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-502", "cwe_name": "Deserialization of Untrusted Data", "description": "The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.", "url": "https://cwe.mitre.org/data/definitions/502.html", "label_name": "vulnerable"} {"code": " def test_extract_symlink_parent\n skip 'symlink not supported' if Gem.win_platform?\n\n package = Gem::Package.new @gem\n\n tgz_io = util_tar_gz do |tar|\n tar.mkdir 'lib', 0755\n tar.add_symlink 'lib/link', '../..', 0644\n tar.add_file 'lib/link/outside.txt', 0644 do |io| io.write 'hi' end\n end\n\n # Extract into a subdirectory of @destination; if this test fails it writes\n # a file outside destination_subdir, but we want the file to remain inside\n # @destination so it will be cleaned up.\n destination_subdir = File.join @destination, 'subdir'\n FileUtils.mkdir_p destination_subdir\n\n e = assert_raises Gem::Package::PathError do\n package.extract_tar_gz tgz_io, destination_subdir\n end\n\n assert_equal(\"installing into parent path ../outside.txt of \" +\n \"#{destination_subdir} is not allowed\", e.message)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " def to_s\n @@string_format % data\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def initialize\n # Generate and cache 3 bytes of identifying information from the current\n # machine.\n @machine_id = Digest::MD5.digest(Socket.gethostname).unpack(\"C3\")\n\n @mutex = Mutex.new\n @last_timestamp = nil\n @counter = 0\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def generation_time\n Time.at(@data.pack(\"C4\").unpack(\"N\")[0]).utc\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def initialize(data = nil, time = nil)\n if data\n @data = data\n elsif time\n @data = @@generator.generate(time.to_i)\n else\n @data = @@generator.next\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " def login(database, username, password)\n auth[database.to_s] = [username, password]\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " def sync\n known = known_addresses.shuffle\n seen = {}\n\n sync_seed = ->(seed) do\n server = Server.new seed\n\n unless seen[server.resolved_address]\n seen[server.resolved_address] = true\n\n hosts = sync_server(server)\n\n hosts.each do |host|\n sync_seed[host]\n end\n end\n end\n\n known.each do |seed|\n sync_seed[seed]\n end\n\n unless servers.empty?\n @dynamic_seeds = servers.map(&:address)\n end\n\n true\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " def each\n documents = query @query_op\n documents.each { |doc| yield doc }\n\n while more?\n return kill if limited? && @get_more_op.limit <= 0\n\n documents = query @get_more_op\n documents.each { |doc| yield doc }\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " def initialize(string)\n super(\"'#{string}' is not a valid object id.\")\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def new(options = {})\n session = with(options)\n session.cluster.reconnect\n\n if block_given?\n yield session\n else\n session\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " it \"adds the node to the master set\" do\n cluster.sync_server server\n cluster.primaries.should include server\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"adds the credentials to the auth cache\" do\n cluster.login(\"admin\", \"username\", \"password\")\n cluster.auth.should eq(\"admin\" => [\"username\", \"password\"])\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"has an empty list of primaries\" do\n cluster.primaries.should be_empty\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"removes the stored credentials\" do\n cluster.logout :admin\n cluster.auth.should be_empty\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"returns a random slave connection\" do\n secondaries = [server]\n cluster.stub(secondaries: secondaries)\n secondaries.should_receive(:sample).and_return(server)\n cluster.socket_for(:read).should eq socket\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"returns the master connection\" do\n cluster.socket_for(:read).should eq socket\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"defaults to an empty selector\" do\n Moped::Query.should_receive(:new).\n with(collection, {}).and_return(query)\n collection.find.should eq query\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"returns false\" do\n indexes.drop(other: 1).should be_false\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " it \"creates an index\" do\n indexes.create(key, background: true)\n indexes[key][\"background\"].should eq true\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"executes a count command\" do\n database.should_receive(:command).with(\n count: collection.name,\n query: selector\n ).and_return(\"n\" => 4)\n\n query.count\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"upserts the record matching selector with change\" do\n query.should_receive(:update).with(change, [:upsert])\n query.upsert change\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " it \"changes the $orderby\" do\n query.sort(a: 1)\n query.sort(a: 2)\n query.operation.selector.should eq(\n \"$query\" => selector,\n \"$orderby\" => { a: 2 }\n )\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"executes a simple query\" do\n session.should_receive(:simple_query).with(query.operation)\n query.one\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " it \"yields all documents in the cursor\" do\n cursor = Moped::Cursor.allocate\n cursor.stub(:to_enum).and_return([1, 2].to_enum)\n\n Moped::Cursor.stub(new: cursor)\n\n query.to_a.should eq [1, 2]\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " it \"yields a session\" do\n session.with(new_options) do |new_session|\n new_session.should be_a Moped::Session\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"stores the cluster\" do\n session.cluster.should be_a(Moped::Cluster)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"limits the query\" do\n session.should_receive(:query) do |query|\n query.limit.should eq(-1)\n reply\n end\n\n session.simple_query(query)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"unmemoizes the current database\" do\n db = session.current_database\n session.with(new_options) do |new_session|\n new_session.current_database.should_not eql db\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " it \"sets the :database option\" do\n session.use :admin\n session.options[:database].should eq(:admin)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": " it \"returns the database from the options\" do\n session.current_database.should eq(database)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-400", "cwe_name": "Uncontrolled Resource Consumption", "description": "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", "url": "https://cwe.mitre.org/data/definitions/400.html", "label_name": "vulnerable"} {"code": "def getFenceAgents(session, fence_agent = nil)\n fence_agent_list = {}\n agents = Dir.glob('/usr/sbin/fence_' + '*')\n agents.each { |a|\n fa = FenceAgent.new\n fa.name = a.sub(/.*\\//,\"\")\n next if fa.name == \"fence_ack_manual\"\n\n if fence_agent and a.sub(/.*\\//,\"\") == fence_agent.sub(/.*:/,\"\")\n required_options, optional_options, advanced_options, info = getFenceAgentMetadata(session, fa.name)\n fa.required_options = required_options\n fa.optional_options = optional_options\n fa.advanced_options = advanced_options\n fa.info = info\n end\n fence_agent_list[fa.name] = fa\n }\n fence_agent_list\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def get_corosync_nodes()\n stdout, stderror, retval = run_cmd(\n PCSAuth.getSuperuserSession, PCS, \"status\", \"nodes\", \"corosync\"\n )\n if retval != 0\n return []\n end\n\n stdout.each {|x| x.strip!}\n corosync_online = stdout[1].sub(/^.*Online:/,\"\").strip\n corosync_offline = stdout[2].sub(/^.*Offline:/,\"\").strip\n corosync_nodes = (corosync_online.split(/ /)) + (corosync_offline.split(/ /))\n\n return corosync_nodes\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def disable_cluster(session)\n stdout, stderror, retval = run_cmd(session, PCS, \"cluster\", \"disable\")\n return false if retval != 0\n return true\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def add_location_constraint_rule(\n session, resource, rule, score, force=false, autocorrect=true\n)\n cmd = [PCS, \"constraint\", \"location\", resource, \"rule\"]\n if score != ''\n if is_score(score.upcase)\n cmd << \"score=#{score.upcase}\"\n else\n cmd << \"score-attribute=#{score}\"\n end\n end\n cmd.concat(rule.shellsplit())\n cmd << '--force' if force\n cmd << '--autocorrect' if autocorrect\n stdout, stderr, retval = run_cmd(session, *cmd)\n return retval, stderr.join(' ')\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def get_sync_capabilities(params, request, session)\n return JSON.generate({\n 'syncable_configs' => Cfgsync::get_cfg_classes_by_name().keys,\n })\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def add_group(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n rg = params[\"resource_group\"]\n resources = params[\"resources\"]\n output, errout, retval = run_cmd(\n session, PCS, \"resource\", \"group\", \"add\", rg, *(resources.split(\" \"))\n )\n if retval == 0\n return 200\n else\n return 400, errout\n end\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def fence_device_metadata(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::READ)\n return 403, 'Permission denied'\n end\n return 200 if not params[:resourcename] or params[:resourcename] == \"\"\n @fenceagent = FenceAgent.new(params[:resourcename])\n @fenceagent.required_options, @fenceagent.optional_options, @fenceagent.advanced_options, @fenceagent.info = getFenceAgentMetadata(session, params[:resourcename])\n @new_fenceagent = params[:new]\n \n erb :fenceagentform\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def add_fence_level_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n retval, stdout, stderr = add_fence_level(\n session, params[\"level\"], params[\"devices\"], params[\"node\"], params[\"remove\"]\n )\n if retval == 0\n return [200, \"Successfully added fence level\"]\n else\n return [400, stderr]\n end\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def get_permissions_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::GRANT)\n return 403, 'Permission denied'\n end\n\n pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())\n data = {\n 'user_types' => Permissions::get_user_types(),\n 'permission_types' => Permissions::get_permission_types(),\n 'permissions_dependencies' => Permissions::permissions_dependencies(),\n 'users_permissions' => pcs_config.permissions_local.to_hash(),\n }\n return [200, JSON.generate(data)]\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": "def remove_acl_roles_remote(params, request, session)\n if not allowed_for_local_cluster(session, Permissions::GRANT)\n return 403, 'Permission denied'\n end\n errors = \"\"\n params.each { |name, value|\n if name.index(\"role-\") == 0\n out, errout, retval = run_cmd(\n session, PCS, \"acl\", \"role\", \"delete\", value.to_s, \"--autodelete\"\n )\n if retval != 0\n errors += \"Unable to remove role #{value}\"\n unless errout.include?(\"cib_replace failure\")\n errors += \": #{errout.join(\" \").strip()}\"\n end\n errors += \"\\n\"\n $logger.info errors\n end\n end\n }\n if errors == \"\"\n return [200, \"Successfully removed ACL roles\"]\n else\n return [400, errors]\n end\nend", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-384", "cwe_name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.", "url": "https://cwe.mitre.org/data/definitions/384.html", "label_name": "vulnerable"} {"code": " it 'should overwrite the existing public key if overwrite_stored_key is set' do\n @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')\n @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')\n @plugin.stubs(:lookup_config_option).with('overwrite_stored_keys', 'n').returns('1')\n File.stubs(:directory?).with('ssh/pkd').returns(true)\n File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(true)\n File.stubs(:read).with('ssh/pkd/rspec_pub.pem').returns('ssh-rsa dcba')\n file = mock\n File.expects(:open).with('ssh/pkd/rspec_pub.pem', 'w').yields(file)\n file.expects(:puts).with('ssh-rsa abcd')\n Log.expects(:warn)\n @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "vulnerable"} {"code": " def ffi_lib(*names)\n raise LoadError.new(\"library names list must not be empty\") if names.empty?\n\n lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL\n ffi_libs = names.map do |name|\n\n if name == FFI::CURRENT_PROCESS\n FFI::DynamicLibrary.open(nil, FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL)\n\n else\n libnames = (name.is_a?(::Array) ? name : [ name ]).map(&:to_s).map { |n| [ n, FFI.map_library_name(n) ].uniq }.flatten.compact\n lib = nil\n errors = {}\n\n libnames.each do |libname|\n begin\n orig = libname\n lib = FFI::DynamicLibrary.open(libname, lib_flags)\n break if lib\n\n rescue Exception => ex\n ldscript = false\n if ex.message =~ /(([^ \\t()])+\\.so([^ \\t:()])*):([ \\t])*(invalid ELF header|file too short|invalid file format)/\n if File.read($1) =~ /(?:GROUP|INPUT) *\\( *([^ \\)]+)/\n libname = $1\n ldscript = true\n end\n end\n\n if ldscript\n retry\n else\n # TODO better library lookup logic\n unless libname.start_with?(\"/\")\n path = ['/usr/lib/','/usr/local/lib/'].find do |pth|\n File.exist?(pth + libname)\n end\n if path\n libname = path + libname\n retry\n end\n end\n\n libr = (orig == libname ? orig : \"#{orig} #{libname}\")\n errors[libr] = ex\n end\n end\n end\n\n if lib.nil?\n raise LoadError.new(errors.values.join(\".\\n\"))\n end\n\n # return the found lib\n lib\n end\n end\n\n @ffi_libs = ffi_libs\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-426", "cwe_name": "Untrusted Search Path", "description": "The application searches for critical resources using an externally-supplied search path that can point to resources that are not under the application's direct control.", "url": "https://cwe.mitre.org/data/definitions/426.html", "label_name": "vulnerable"} {"code": " it \"generates the correct messages for a secure topic\" do\n Jobs.run_immediately!\n UserActionManager.enable\n\n admin = Fabricate(:admin)\n\n cat = Fabricate(:category)\n cat.set_permissions(admins: :full)\n cat.save\n\n created_post = nil\n\n messages = MessageBus.track_publish do\n created_post = PostCreator.new(admin, basic_topic_params.merge(category: cat.id)).create\n _reply = PostCreator.new(admin, raw: \"this is my test reply 123 testing\", topic_id: created_post.topic_id).create\n end\n\n messages.filter! { |m| m.channel != \"/distributed_hash\" }\n\n channels = messages.map { |m| m.channel }.sort\n\n # 2 for topic, one to notify of new topic another for tracking state\n expect(channels).to eq(\n [\n \"/new\",\n \"/u/#{admin.username}\",\n \"/u/#{admin.username}\",\n \"/unread/#{admin.id}\",\n \"/unread/#{admin.id}\",\n \"/latest\",\n \"/latest\",\n \"/topic/#{created_post.topic_id}\",\n \"/topic/#{created_post.topic_id}\",\n \"/user\",\n \"/user\",\n \"/user\"\n ].sort\n )\n\n admin_ids = [Group[:admins].id]\n expect(messages.any? { |m| m.group_ids != admin_ids && m.user_ids != [admin.id] }).to eq(false)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " it 'correctly exports the CategoryUser table' do\n data, _csv_out = make_component_csv\n\n expect(data.find { |r| r['category_id'] == category.id }).to be_nil\n expect(data.length).to eq(4)\n data.sort! { |a, b| a['category_id'].to_i <=> b['category_id'].to_i }\n\n expect(data[0][:category_id]).to eq(subcategory.id.to_s)\n expect(data[0][:notification_level].to_s).to eq('tracking')\n expect(DateTime.parse(data[0][:dismiss_new_timestamp])).to eq(reset_at)\n\n expect(data[1][:category_id]).to eq(subsubcategory.id.to_s)\n expect(data[1][:category_names]).to eq(\"#{category.name}|#{subcategory.name}|#{subsubcategory.name}\")\n expect(data[1][:notification_level]).to eq('regular')\n expect(DateTime.parse(data[1][:dismiss_new_timestamp])).to eq(reset_at)\n\n expect(data[2][:category_id]).to eq(announcements.id.to_s)\n expect(data[2][:category_names]).to eq(announcements.name)\n expect(data[2][:notification_level]).to eq('watching_first_post')\n expect(data[2][:dismiss_new_timestamp]).to eq('')\n\n expect(data[3][:category_names]).to eq(data[3][:category_id])\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-200", "cwe_name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", "url": "https://cwe.mitre.org/data/definitions/200.html", "label_name": "vulnerable"} {"code": " it \"returns the group permissions for everyone group too\" do\n category.set_permissions(everyone: :readonly)\n category.save!\n\n json = described_class.new(category, scope: Guardian.new(admin), root: false).as_json\n\n expect(json[:group_permissions]).to eq([\n { permission_type: CategoryGroup.permission_types[:readonly], group_name: 'everyone' },\n ])\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-276", "cwe_name": "Incorrect Default Permissions", "description": "During installation, installed file permissions are set to allow anyone to modify those files.", "url": "https://cwe.mitre.org/data/definitions/276.html", "label_name": "vulnerable"} {"code": " def process_invitation\n approve_account_if_needed\n add_to_private_topics_if_invited\n add_user_to_groups\n send_welcome_message\n notify_invitee\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-863", "cwe_name": "Incorrect Authorization", "description": "The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.", "url": "https://cwe.mitre.org/data/definitions/863.html", "label_name": "vulnerable"} {"code": " it 'returns the right response' do\n get \"/session/email-login/adasdad\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to match(\n I18n.t('email_login.invalid_token')\n )\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " it 'should return the right response' do\n email_token.update!(created_at: 999.years.ago)\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to match(\n I18n.t('email_login.invalid_token')\n )\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "NVD-CWE-noinfo", "cwe_name": null, "description": null, "url": null, "label_name": "vulnerable"} {"code": " def handle_meta(message, local, &callback)\n method = Channel.parse(message['channel'])[1]\n\n unless META_METHODS.include?(method)\n response = make_response(message)\n response['error'] = Faye::Error.channel_forbidden(message['channel'])\n response['successful'] = false\n return callback.call([response])\n end\n\n __send__(method, message, local) do |responses|\n responses = [responses].flatten\n responses.each { |r| advize(r, message['connectionType']) }\n callback.call(responses)\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-287", "cwe_name": "Improper Authentication", "description": "When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.", "url": "https://cwe.mitre.org/data/definitions/287.html", "label_name": "vulnerable"} {"code": " it 'should return a key' do\n expect(jwt_validator.jwks_key(:alg, jwks_kid)).to eq('RS256')\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "vulnerable"} {"code": " def stub_dummy_jwks\n stub_request(:get, 'https://example.org/.well-known/jwks.json')\n .to_return(\n headers: { 'Content-Type' => 'application/json' },\n body: rsa_token_jwks,\n status: 200\n )\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-347", "cwe_name": "Improper Verification of Cryptographic Signature", "description": "The software does not verify, or incorrectly verifies, the cryptographic signature for data.", "url": "https://cwe.mitre.org/data/definitions/347.html", "label_name": "vulnerable"} {"code": " def parse(socket=nil)\n @socket = socket\n begin\n @peeraddr = socket.respond_to?(:peeraddr) ? socket.peeraddr : []\n @addr = socket.respond_to?(:addr) ? socket.addr : []\n rescue Errno::ENOTCONN\n raise HTTPStatus::EOFError\n end\n\n read_request_line(socket)\n if @http_version.major > 0\n read_header(socket)\n @header['cookie'].each{|cookie|\n @cookies += Cookie::parse(cookie)\n }\n @accept = HTTPUtils.parse_qvalues(self['accept'])\n @accept_charset = HTTPUtils.parse_qvalues(self['accept-charset'])\n @accept_encoding = HTTPUtils.parse_qvalues(self['accept-encoding'])\n @accept_language = HTTPUtils.parse_qvalues(self['accept-language'])\n end\n return if @request_method == \"CONNECT\"\n return if @unparsed_uri == \"*\"\n\n begin\n setup_forwarded_info\n @request_uri = parse_uri(@unparsed_uri)\n @path = HTTPUtils::unescape(@request_uri.path)\n @path = HTTPUtils::normalize_path(@path)\n @host = @request_uri.host\n @port = @request_uri.port\n @query_string = @request_uri.query\n @script_name = \"\"\n @path_info = @path.dup\n rescue\n raise HTTPStatus::BadRequest, \"bad URI `#{@unparsed_uri}'.\"\n end\n\n if /close/io =~ self[\"connection\"]\n @keep_alive = false\n elsif /keep-alive/io =~ self[\"connection\"]\n @keep_alive = true\n elsif @http_version < \"1.1\"\n @keep_alive = false\n else\n @keep_alive = true\n end\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "vulnerable"} {"code": " def initialize(file)\n @file = file.is_a?(String) ? StringIO.new(file) : file\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": " it \"should be an error instance if file was downloaded\" do\n stub_request(:get, \"www.example.com/test.jpg\").to_return(body: File.read(file_path(\"test.jpg\")))\n @instance.remote_image_url = \"http://www.example.com/test.jpg\"\n e = @instance.image_integrity_error\n\n expect(e).to be_an_instance_of(CarrierWave::IntegrityError)\n expect(e.message.lines.grep(/^You are not allowed to upload/)).to be_truthy\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-918", "cwe_name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.", "url": "https://cwe.mitre.org/data/definitions/918.html", "label_name": "vulnerable"} {"code": " def file_parse(key)\n file_path = File.join(@root_folder, key)\n url_path, is_dir = file_path.sub(Rails.root.join('public').to_s, ''), File.directory?(file_path)\n res = {\n \"name\" => File.basename(key),\n \"folder_path\" => File.dirname(key),\n \"url\" => is_dir ? '' : (is_private_uploader? ? url_path.sub(\"#{@root_folder}/\", '') : File.join(@current_site.decorate.the_url(as_path: true, locale: false, skip_relative_url_root: true), url_path)),\n \"is_folder\" => is_dir,\n \"file_size\" => is_dir ? 0 : File.size(file_path).round(2),\n \"thumb\" => '',\n 'file_type' => self.class.get_file_format(file_path),\n 'dimension' => ''\n }.with_indifferent_access\n res['key'] = File.join(res['folder_path'], res['name'])\n res[\"thumb\"] = (is_private_uploader? ? '/admin/media/download_private_file?file=' + version_path(key).slice(1..-1) : version_path(res['url'])) if res['file_type'] == 'image' && File.extname(file_path).downcase != '.gif'\n if res['file_type'] == 'image'\n res[\"thumb\"].sub! '.svg', '.jpg'\n im = MiniMagick::Image.open(file_path)\n res['dimension'] = \"#{im[:width]}x#{im[:height]}\"\n end\n res\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "NVD-CWE-Other", "cwe_name": "Other", "description": "NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.", "url": "https://nvd.nist.gov/vuln/categories", "label_name": "vulnerable"} {"code": " it \"should get the script it asks for\" do\n\n def @bus.is_admin_lookup\n proc { |_| true }\n end\n\n get \"/message-bus/_diagnostics/assets/message-bus.js\"\n last_response.status.must_equal 200\n last_response.content_type.must_equal \"application/javascript;charset=UTF-8\"\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-22", "cwe_name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", "url": "https://cwe.mitre.org/data/definitions/22.html", "label_name": "vulnerable"} {"code": " def reset_password\n @admin_user = Motor::AdminUser.find(params[:admin_user_id])\n\n authorize!(:manage, @admin_user)\n\n Devise::Mailer.default_url_options = { host: request.host, protocol: request.protocol, port: request.port }\n\n @admin_user.send_reset_password_instructions\n\n head :ok\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-116", "cwe_name": "Improper Encoding or Escaping of Output", "description": "The software prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.", "url": "https://cwe.mitre.org/data/definitions/116.html", "label_name": "vulnerable"} {"code": " def resolve_target_path(target, reader)\n return target if target_uri? target\n\n # Include file is resolved relative to dir of the current include,\n # or base_dir if within original docfile.\n path = reader.document.normalize_system_path(target, reader.dir, nil,\n target_name: 'include file')\n path if ::File.file?(path)\n end", "label": 0, "programming_language": "Ruby", "cwe_id": "CWE-78", "cwe_name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/78.html", "label_name": "vulnerable"} {"code": "func (p224FieldElement) Generate(rand *rand.Rand, size int) reflect.Value {\n\treturn reflect.ValueOf(p224FieldElement{\n\t\tgenerateLimb(rand),\n\t\tgenerateLimb(rand),\n\t\tgenerateLimb(rand),\n\t\tgenerateLimb(rand),\n\t\tgenerateLimb(rand),\n\t\tgenerateLimb(rand),\n\t\tgenerateLimb(rand),\n\t\tgenerateLimb(rand),\n\t})\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-682", "cwe_name": "Incorrect Calculation", "description": "The software performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management.", "url": "https://cwe.mitre.org/data/definitions/682.html", "label_name": "safe"} {"code": "func fixTransferEncoding(isResponse bool, requestMethod string, header Header) ([]string, error) {\n\traw, present := header[\"Transfer-Encoding\"]\n\tif !present {\n\t\treturn nil, nil\n\t}\n\tisRequest := !isResponse\n\tdelete(header, \"Transfer-Encoding\")\n\n\tencodings := strings.Split(raw[0], \",\")\n\tte := make([]string, 0, len(encodings))\n\t// TODO: Even though we only support \"identity\" and \"chunked\"\n\t// encodings, the loop below is designed with foresight. One\n\t// invariant that must be maintained is that, if present,\n\t// chunked encoding must always come first.\n\tfor _, encoding := range encodings {\n\t\tencoding = strings.ToLower(strings.TrimSpace(encoding))\n\t\t// \"identity\" encoding is not recorded\n\t\tif encoding == \"identity\" {\n\t\t\tbreak\n\t\t}\n\t\tif encoding != \"chunked\" {\n\t\t\treturn nil, &badStringError{\"unsupported transfer encoding\", encoding}\n\t\t}\n\t\tte = te[0 : len(te)+1]\n\t\tte[len(te)-1] = encoding\n\t}\n\tif len(te) > 1 {\n\t\treturn nil, &badStringError{\"too many transfer encodings\", strings.Join(te, \",\")}\n\t}\n\tif len(te) > 0 {\n\t\t// RFC 7230 3.3.2 says \"A sender MUST NOT send a\n\t\t// Content-Length header field in any message that\n\t\t// contains a Transfer-Encoding header field.\"\n\t\tif len(header[\"Content-Length\"]) > 0 {\n\t\t\tif isRequest {\n\t\t\t\treturn nil, errors.New(\"http: invalid Content-Length with Transfer-Encoding\")\n\t\t\t}\n\t\t\tdelete(header, \"Content-Length\")\n\t\t}\n\t\treturn te, nil\n\t}\n\n\treturn nil, nil\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": "func fixTransferEncoding(isResponse bool, requestMethod string, header Header) ([]string, error) {\n\traw, present := header[\"Transfer-Encoding\"]\n\tif !present {\n\t\treturn nil, nil\n\t}\n\tisRequest := !isResponse\n\tdelete(header, \"Transfer-Encoding\")\n\n\tencodings := strings.Split(raw[0], \",\")\n\tte := make([]string, 0, len(encodings))\n\t// TODO: Even though we only support \"identity\" and \"chunked\"\n\t// encodings, the loop below is designed with foresight. One\n\t// invariant that must be maintained is that, if present,\n\t// chunked encoding must always come first.\n\tfor _, encoding := range encodings {\n\t\tencoding = strings.ToLower(strings.TrimSpace(encoding))\n\t\t// \"identity\" encoding is not recorded\n\t\tif encoding == \"identity\" {\n\t\t\tbreak\n\t\t}\n\t\tif encoding != \"chunked\" {\n\t\t\treturn nil, &badStringError{\"unsupported transfer encoding\", encoding}\n\t\t}\n\t\tte = te[0 : len(te)+1]\n\t\tte[len(te)-1] = encoding\n\t}\n\tif len(te) > 1 {\n\t\treturn nil, &badStringError{\"too many transfer encodings\", strings.Join(te, \",\")}\n\t}\n\tif len(te) > 0 {\n\t\t// RFC 7230 3.3.2 says \"A sender MUST NOT send a\n\t\t// Content-Length header field in any message that\n\t\t// contains a Transfer-Encoding header field.\"\n\t\tif len(header[\"Content-Length\"]) > 0 {\n\t\t\tif isRequest {\n\t\t\t\treturn nil, errors.New(\"http: invalid Content-Length with Transfer-Encoding\")\n\t\t\t}\n\t\t\tdelete(header, \"Content-Length\")\n\t\t}\n\t\treturn te, nil\n\t}\n\n\treturn nil, nil\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-444", "cwe_name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination.", "url": "https://cwe.mitre.org/data/definitions/444.html", "label_name": "safe"} {"code": "func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {\n\t// Prevent SQL inject.\n\topt.Keyword = FilterSQLInject(opt.Keyword)\n\tif len(opt.Keyword) == 0 {\n\t\treturn repos, nil\n\t}\n\topt.Keyword = strings.ToLower(opt.Keyword)\n\n\trepos = make([]*Repository, 0, opt.Limit)\n\n\t// Append conditions.\n\tsess := x.Limit(opt.Limit)\n\tif opt.Uid > 0 {\n\t\tsess.Where(\"owner_id=?\", opt.Uid)\n\t}\n\tif !opt.Private {\n\t\tsess.And(\"is_private=false\")\n\t}\n\tsess.And(\"lower_name like ?\", \"%\"+opt.Keyword+\"%\").Find(&repos)\n\treturn repos, err\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-89", "cwe_name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", "url": "https://cwe.mitre.org/data/definitions/89.html", "label_name": "safe"} {"code": "func ShiftOwner(basepath string, path string, uid int, gid int) error {\n\tr := C.shiftowner(C.CString(basepath), C.CString(path), C.int(uid), C.int(gid))\n\tif r != 0 {\n\t\treturn fmt.Errorf(\"Failed to change ownership of: %s\", path)\n\t}\n\treturn nil\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "safe"} {"code": "func stripRoot(root, path string) string {\n\t// Make the paths clean and absolute.\n\troot, path = CleanPath(\"/\"+root), CleanPath(\"/\"+path)\n\tswitch {\n\tcase path == root:\n\t\tpath = \"/\"\n\tcase root == \"/\":\n\t\t// do nothing\n\tcase strings.HasPrefix(path, root+\"/\"):\n\t\tpath = strings.TrimPrefix(path, root+\"/\")\n\t}\n\treturn CleanPath(\"/\" + path)\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-362", "cwe_name": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')", "description": "The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.", "url": "https://cwe.mitre.org/data/definitions/362.html", "label_name": "safe"} {"code": "func (m *Mount) IsBind() bool {\n\treturn m.Flags&unix.MS_BIND != 0\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error {\n\tswitch m.Device {\n\tcase \"cgroup\":\n\t\t// No mount point(s) need to be created:\n\t\t//\n\t\t// * for v1, mount points are saved by CRIU because\n\t\t// /sys/fs/cgroup is a tmpfs mount\n\t\t//\n\t\t// * for v2, /sys/fs/cgroup is a real mount, but\n\t\t// the mountpoint appears as soon as /sys is mounted\n\t\treturn nil\n\tcase \"bind\":\n\t\t// The prepareBindMount() function checks if source\n\t\t// exists. So it cannot be used for other filesystem types.\n\t\t// TODO: pass something else than nil? Not sure if criu is\n\t\t// impacted by issue #2484\n\t\tif err := prepareBindMount(m, c.config.Rootfs, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// for all other filesystems just create the mountpoints\n\t\tdest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := checkProcMount(c.config.Rootfs, dest, \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.MkdirAll(dest, 0o755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-190", "cwe_name": "Integer Overflow or Wraparound", "description": "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", "url": "https://cwe.mitre.org/data/definitions/190.html", "label_name": "safe"} {"code": "func TestIsReqAuthenticated(t *testing.T) {\n\tpath, err := newTestConfig(globalMinioDefaultRegion)\n\tif err != nil {\n\t\tt.Fatalf(\"unable initialize config file, %s\", err)\n\t}\n\tdefer os.RemoveAll(path)\n\n\tcreds, err := auth.CreateCredentials(\"myuser\", \"mypassword\")\n\tif err != nil {\n\t\tt.Fatalf(\"unable create credential, %s\", err)\n\t}\n\n\tglobalServerConfig.SetCredential(creds)\n\n\t// List of test cases for validating http request authentication.\n\ttestCases := []struct {\n\t\treq *http.Request\n\t\ts3Error APIErrorCode\n\t}{\n\t\t// When request is unsigned, access denied is returned.\n\t\t{mustNewRequest(\"GET\", \"http://127.0.0.1:9000\", 0, nil, t), ErrAccessDenied},\n\t\t// Empty Content-Md5 header.\n\t\t{mustNewSignedEmptyMD5Request(\"PUT\", \"http://127.0.0.1:9000/\", 5, bytes.NewReader([]byte(\"hello\")), t), ErrInvalidDigest},\n\t\t// Short Content-Md5 header.\n\t\t{mustNewSignedShortMD5Request(\"PUT\", \"http://127.0.0.1:9000/\", 5, bytes.NewReader([]byte(\"hello\")), t), ErrInvalidDigest},\n\t\t// When request is properly signed, but has bad Content-MD5 header.\n\t\t{mustNewSignedBadMD5Request(\"PUT\", \"http://127.0.0.1:9000/\", 5, bytes.NewReader([]byte(\"hello\")), t), ErrBadDigest},\n\t\t// When request is properly signed, error is none.\n\t\t{mustNewSignedRequest(\"GET\", \"http://127.0.0.1:9000\", 0, nil, t), ErrNone},\n\t}\n\n\t// Validates all testcases.\n\tfor i, testCase := range testCases {\n\t\tif s3Error := isReqAuthenticated(testCase.req, globalServerConfig.GetRegion()); s3Error != testCase.s3Error {\n\t\t\tif _, err := ioutil.ReadAll(testCase.req.Body); toAPIErrorCode(err) != testCase.s3Error {\n\t\t\t\tt.Fatalf(\"Test %d: Unexpected S3 error: want %d - got %d (got after reading request %d)\", i, testCase.s3Error, s3Error, toAPIErrorCode(err))\n\t\t\t}\n\t\t}\n\t}\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-774", "cwe_name": "Allocation of File Descriptors or Handles Without Limits or Throttling", "description": "The software allocates file descriptors or handles on behalf of an actor without imposing any restrictions on how many descriptors can be allocated, in violation of the intended security policy for that actor.", "url": "https://cwe.mitre.org/data/definitions/774.html", "label_name": "safe"} {"code": "func TestDoesPolicySignatureV2Match(t *testing.T) {\n\tobj, fsDir, err := prepareFS()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(fsDir)\n\tif err = newTestConfig(globalMinioDefaultRegion, obj); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcreds := globalActiveCred\n\tpolicy := \"policy\"\n\ttestCases := []struct {\n\t\taccessKey string\n\t\tpolicy string\n\t\tsignature string\n\t\terrCode APIErrorCode\n\t}{\n\t\t{\"invalidAccessKey\", policy, calculateSignatureV2(policy, creds.SecretKey), ErrInvalidAccessKeyID},\n\t\t{creds.AccessKey, policy, calculateSignatureV2(\"random\", creds.SecretKey), ErrSignatureDoesNotMatch},\n\t\t{creds.AccessKey, policy, calculateSignatureV2(policy, creds.SecretKey), ErrNone},\n\t}\n\tfor i, test := range testCases {\n\t\tformValues := make(http.Header)\n\t\tformValues.Set(\"Awsaccesskeyid\", test.accessKey)\n\t\tformValues.Set(\"Signature\", test.signature)\n\t\tformValues.Set(\"Policy\", test.policy)\n\t\t_, errCode := doesPolicySignatureV2Match(formValues)\n\t\tif errCode != test.errCode {\n\t\t\tt.Fatalf(\"(%d) expected to get %s, instead got %s\", i+1, niceError(test.errCode), niceError(errCode))\n\t\t}\n\t}\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-285", "cwe_name": "Improper Authorization", "description": "The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.", "url": "https://cwe.mitre.org/data/definitions/285.html", "label_name": "safe"} {"code": "func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) {\n\t// Fetch the block interval that we want to trace\n\tvar from, to *types.Block\n\n\tswitch start {\n\tcase rpc.PendingBlockNumber:\n\t\tfrom = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tfrom = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tfrom = api.eth.blockchain.GetBlockByNumber(uint64(start))\n\t}\n\tswitch end {\n\tcase rpc.PendingBlockNumber:\n\t\tto = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tto = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tto = api.eth.blockchain.GetBlockByNumber(uint64(end))\n\t}\n\t// Trace the chain if we've found all our blocks\n\tif from == nil {\n\t\treturn nil, fmt.Errorf(\"starting block #%d not found\", start)\n\t}\n\tif to == nil {\n\t\treturn nil, fmt.Errorf(\"end block #%d not found\", end)\n\t}\n\tif from.Number().Cmp(to.Number()) >= 0 {\n\t\treturn nil, fmt.Errorf(\"end block (#%d) needs to come after start block (#%d)\", end, start)\n\t}\n\treturn api.traceChain(ctx, from, to, config)\n}", "label": 1, "programming_language": "Go", "cwe_id": "CWE-20", "cwe_name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly.", "url": "https://cwe.mitre.org/data/definitions/20.html", "label_name": "safe"} {"code": "func TestParseFragmentForeignContentTemplates(t *testing.T) {\n\tsrcs := []string{\n\t\t\"\",\n\t\t\"