diff --git "a/test.jsonl" "b/test.jsonl" --- "a/test.jsonl" +++ "b/test.jsonl" @@ -1,5260 +1,3984 @@ -{"code": "this.startDrawing=function(){t(!0)};this.isDrawing=function(){return y};var z=mxUtils.bind(this,function(K){if(c){var F=d.length,H=A&&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(K)}}),L=new mxCell;L.edge=!0;var C=function(){var K=b.getCurrentCellStyle(L);K=mxUtils.getValue(b.currentVertexStyle,mxConstants.STYLE_STROKECOLOR,mxUtils.getValue(K,mxConstants.STYLE_STROKECOLOR,\"#000\"));\"default\"==", "label": 0, "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,\n\t\t\t ++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": 1, "label_name": "safe"} -{"code": " public function index($id)\n {\n $this->paginate['conditions'] = array('GalaxyElement.galaxy_cluster_id' => $id);\n $clusters = $this->paginate();\n $this->set('list', $clusters);\n if ($this->request->is('ajax')) {\n $this->layout = 'ajax';\n $this->render('ajax/index');\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function params()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {\n $this->create();\n return;\n }\n\n $action = $this->actionManager->getAction($values['action_name']);\n $action_params = $action->getActionRequiredParameters();\n\n if (empty($action_params)) {\n $this->doCreation($project, $values + array('params' => array()));\n }\n\n $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());\n unset($projects_list[$project['id']]);\n\n $this->response->html($this->template->render('action_creation/params', array(\n 'values' => $values,\n 'action_params' => $action_params,\n 'columns_list' => $this->columnModel->getList($project['id']),\n 'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),\n 'projects_list' => $projects_list,\n 'colors_list' => $this->colorModel->getList(),\n 'categories_list' => $this->categoryModel->getList($project['id']),\n 'links_list' => $this->linkModel->getList(0, false),\n 'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'swimlane_list' => $this->swimlaneModel->getList($project['id']),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $this->stack[0]->appendChild($comment);\n\n /* An end tag with the tag name \"html\" */\n } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') {\n /* If the parser was originally created in order to handle the\n setting of an element's innerHTML attribute, this is a parse error;\n ignore the token. (The element will be an html element in this\n case.) (innerHTML case) */\n\n /* Otherwise, switch to the trailing end phase. */\n $this->phase = self::END_PHASE;\n\n /* Anything else */\n } else {\n /* Parse error. Set the insertion mode to \"in body\" and reprocess\n the token. */\n $this->mode = self::IN_BODY;\n return $this->inBody($token);\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public void createElementLT() {\n DocumentHelper.createElement(\"elementbcmath) return bcadd($s1, $s2, $scale);\n else return $this->scale($s1 + $s2, $scale);\n }", "label": 1, "label_name": "safe"} -{"code": " def createSessionIdAndXsrfToken(siteId: SiteId, userId: UserId): (SidOk, XsrfOk, List[Cookie]) = {\n COULD_OPTIMIZE // pass settings or a dao to here instead? so won't need to create this 2nd one.\n // (the caller always already has one)\n val dao = globals.siteDao(siteId)\n\n val ppt = dao.getParticipant(userId)\n throwForbiddenIf(ppt.exists(_.isGroup), \"TyELGIGRP\", \"Cannot login as a group\") // [imp-groups]\n\n val settings = dao.getWholeSiteSettings()\n val expireIdleAfterSecs = settings.expireIdleAfterMins * 60\n\n // Note that the xsrf token is created using the non-base64 encoded cookie value.\n val sidOk = createSessionId(siteId, userId)\n val xsrfOk = createXsrfToken()\n UX; SECURITY; SHOULD // use HttpOnly cookies \u2014 otherwise Safari will delete the cookie\n // after 7 days. See: https://webkit.org/blog/8613/intelligent-tracking-prevention-2-1/\n // the \"Client-Side Cookies Capped to 7 Days of Storage\", section, and sub section\n // \"Will This Change Log Users Out?\" \u2014 cookies that are Secure and HttpOnly aren't deleted.\n // This means the client can no longer look at the session cookie, to find out if one is\n // logged in? Could add JS variables instead. [NOCOOKIES]\n val sidCookie = urlEncodeCookie(SessionIdCookieName, sidOk.value,\n maxAgeSecs = Some(expireIdleAfterSecs))\n val xsrfCookie = urlEncodeCookie(XsrfCookieName, xsrfOk.value,\n maxAgeSecs = Some(expireIdleAfterSecs + XsrfAliveExtraSeconds))\n (sidOk, xsrfOk, sidCookie::xsrfCookie::Nil)\n }\n\n\n private val HashLength: Int = 15", "label": 0, "label_name": "vulnerable"} -{"code": " public override string ToString()\n {\n StringBuilder value = new StringBuilder();\n bool firstGroup = true;\n foreach (var group in Rules.GroupBy(r => r.Name))\n {\n if (!firstGroup)\n {\n value.Append(';');\n }\n List values = new List();\n values.Add(group.Key);\n foreach (var v in group)\n {\n values.Add(v.Value);\n }\n foreach (var i in authorized)\n {\n values.Add(i);\n }\n value.Append(String.Join(\" \", values.OfType().ToArray()));\n firstGroup = false;\n }\n return value.ToString();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static inline int verify_replay(struct xfrm_usersa_info *p,\n\t\t\t\tstruct nlattr **attrs)\n{\n\tstruct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];\n\n\tif ((p->flags & XFRM_STATE_ESN) && !rt)\n\t\treturn -EINVAL;\n\n\tif (!rt)\n\t\treturn 0;\n\n\tif (p->id.proto != IPPROTO_ESP)\n\t\treturn -EINVAL;\n\n\tif (p->replay_window != 0)\n\t\treturn -EINVAL;\n\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "_pickle_PicklerMemoProxy_copy_impl(PicklerMemoProxyObject *self)\n/*[clinic end generated code: output=bb83a919d29225ef input=b73043485ac30b36]*/\n{\n Py_ssize_t i;\n PyMemoTable *memo;\n PyObject *new_memo = PyDict_New();\n if (new_memo == NULL)\n return NULL;\n\n memo = self->pickler->memo;\n for (i = 0; i < memo->mt_allocated; ++i) {\n PyMemoEntry entry = memo->mt_table[i];\n if (entry.me_key != NULL) {\n int status;\n PyObject *key, *value;\n\n key = PyLong_FromVoidPtr(entry.me_key);\n value = Py_BuildValue(\"nO\", entry.me_value, entry.me_key);\n\n if (key == NULL || value == NULL) {\n Py_XDECREF(key);\n Py_XDECREF(value);\n goto error;\n }\n status = PyDict_SetItem(new_memo, key, value);\n Py_DECREF(key);\n Py_DECREF(value);\n if (status < 0)\n goto error;\n }\n }\n return new_memo;\n\n error:\n Py_XDECREF(new_memo);\n return NULL;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should not compile when 1 argument is passed\" do\n skip(\"Fails on 2.6.x, see bug #15912\") if Puppet.version =~ /^2\\.6\\./\n Puppet[:code] = \"$my_hash={'one' => 1}\\n$x = deep_merge($my_hash)\"\n expect {\n scope.compiler.compile\n }.to raise_error(Puppet::ParseError, /wrong number of arguments/)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def _assert_not_matches(\n self, condition: Dict[str, Any], content: Dict[str, Any], msg=None", "label": 1, "label_name": "safe"} -{"code": "\tpublic function &storeicms_ipf_ObjectD() {\n\t\treturn $this->storeicms_ipf_Object(true);\n\t}", "label": 1, "label_name": "safe"} -{"code": " it \"should not compile when no arguments are passed\" do\n Puppet[:code] = \"validate_ipv4_address()\"\n expect {\n scope.compiler.compile\n }.to raise_error(Puppet::ParseError, /wrong number of arguments/)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function testContextExceptionKeyCanBeExceptionOrOtherValues()\n {\n $this->getLogger()->warning('Random message', array('exception' => 'oops'));\n $this->getLogger()->critical('Uncaught Exception!', array('exception' => new \\LogicException('Fail')));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function assertTraceNotContains($trace)\n {\n $traces = $this->cache->getTraces();\n $traces = current($traces);\n\n $this->assertNotRegExp('/'.$trace.'/', implode(', ', $traces));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testMungeReplaceResource()\n {\n $this->setMunge('/r?embeds=%r&url=%s');\n $embeds = false;\n $this->context->register('EmbeddedURI', $embeds);\n $this->assertFiltering('http://google.com', '/r?embeds=&url=http%3A%2F%2Fgoogle.com');\n }", "label": 1, "label_name": "safe"} -{"code": " static function isSearchable() {\r\n return true;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $comment = $this->getComment();\n\n $this->response->html($this->template->render('comment/remove', array(\n 'comment' => $comment,\n 'task' => $task,\n 'title' => t('Remove a comment')\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $swimlane = $this->getSwimlane($project);\n\n $this->response->html($this->helper->layout->project('swimlane/remove', array(\n 'project' => $project,\n 'swimlane' => $swimlane,\n )));\n }", "label": 1, "label_name": "safe"} -{"code": " public function setUsername($username)\n {\n $this->username = $username;\n\n return $this;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public String getLiteralExecutable()\n {\n return executable;\n }", "label": 1, "label_name": "safe"} -{"code": "void trustedSetSEK_backup(int *errStatus, char *errString,\n uint8_t *encrypted_sek, uint32_t *enc_len, const char *sek_hex) {\n CALL_ONCE\n LOG_INFO(__FUNCTION__);\n INIT_ERROR_STATE\n\n CHECK_STATE(encrypted_sek);\n CHECK_STATE(sek_hex);\n\n uint64_t len;\n hex2carray(sek_hex, &len, (uint8_t *) AES_key);\n derive_DH_Key();\n\n sealHexSEK(errStatus, errString, encrypted_sek, enc_len, (char *)sek_hex);\n\n if (*errStatus != 0) {\n LOG_ERROR(\"sealHexSEK failed\");\n goto clean;\n }\n\n SET_SUCCESS\n clean:\n ;\n LOG_INFO(__FUNCTION__ );\n LOG_INFO(\"SGX call completed\");\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_cleanCSS_scopeWithMultipleNaughtySelectors()\n {\n $this->config->set('Filter.ExtractStyleBlocks.Scope', '#foo');\n $this->assertCleanCSS(\" ++ ++ p {\\ntext-indent:1em\\n}\", \"#foo p {\\ntext-indent:1em\\n}\");\n }", "label": 1, "label_name": "safe"} -{"code": "RList *r_bin_ne_get_segments(r_bin_ne_obj_t *bin) {\n\tint i;\n\tif (!bin) {\n\t\treturn NULL;\n\t}\n\tRList *segments = r_list_newf (free);\n\tfor (i = 0; i < bin->ne_header->SegCount; i++) {\n\t\tRBinSection *bs = R_NEW0 (RBinSection);\n\t\tNE_image_segment_entry *se = &bin->segment_entries[i];\n\t\tif (!bs) {\n\t\t\treturn segments;\n\t\t}\n\t\tbs->size = se->length;\n\t\tbs->vsize = se->minAllocSz ? se->minAllocSz : 64000;\n\t\tbs->bits = R_SYS_BITS_16;\n\t\tbs->is_data = se->flags & IS_DATA;\n\t\tbs->perm = __translate_perms (se->flags);\n\t\tbs->paddr = (ut64)se->offset * bin->alignment;\n\t\tbs->name = r_str_newf (\"%s.%\" PFMT64d, se->flags & IS_MOVEABLE ? \"MOVEABLE\" : \"FIXED\", bs->paddr);\n\t\tbs->is_segment = true;\n\t\tr_list_append (segments, bs);\n\t}\n\tbin->segments = segments;\n\treturn segments;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=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": 0, "label_name": "vulnerable"} -{"code": "coolkey_add_object(coolkey_private_data_t *priv, unsigned long object_id, const u8 *object_data, size_t object_length, int add_v1_record)\n{\n\tsc_cardctl_coolkey_object_t new_object;\n\tint r;\n\n\tmemset(&new_object, 0, sizeof(new_object));\n\tnew_object.path = coolkey_template_path;\n\tnew_object.path.len = 4;\n\tulong2bebytes(new_object.path.value, object_id);\n\tnew_object.id = object_id;\n\tnew_object.length = object_length;\n\n\t/* The object ID needs to be unique */\n\tif (coolkey_find_object_by_id(&priv->objects_list, object_id) != NULL) {\n\t\treturn SC_ERROR_INTERNAL;\n\t}\n\n\tif (object_data) {\n\t\tnew_object.data = malloc(object_length + add_v1_record);\n\t\tif (new_object.data == NULL) {\n\t\t\treturn SC_ERROR_OUT_OF_MEMORY;\n\t\t}\n\t\tif (add_v1_record) {\n\t\t\tnew_object.data[0] = COOLKEY_V1_OBJECT;\n\t\t\tnew_object.length++;\n\t\t}\n\t\tmemcpy(&new_object.data[add_v1_record], object_data, object_length);\n\t}\n\n\tr = coolkey_add_object_to_list(&priv->objects_list, &new_object);\n\tif (r != SC_SUCCESS) {\n\t\t/* if we didn't successfully put the object on the list,\n\t\t * the data space didn't get adopted. free it before we return */\n\t\tfree(new_object.data);\n\t\tnew_object.data = NULL;\n\t}\n\treturn r;\n}", "label": 1, "label_name": "safe"} -{"code": "sysServices_handler(snmp_varbind_t *varbind, uint32_t *oid)\n{\n snmp_api_set_time_ticks(varbind, oid, clock_seconds() * 100);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def anyWeirdJsObjField(obj: JsObject, maxLength: i32,\n allowHeaderNameValues: Bo = false): Opt[St] = {\n unimplIf(allowHeaderNameValues, \"TyE50MFEDJ4601\")\n for ((fieldName, fieldValue) <- obj.fields) {\n if (fieldName.isEmpty)\n return Some(\"Empty field name\")\n\n if (allowHeaderNameValues) {\n if (!fieldName.isOkHeaderName)\n return Some(s\"Weird header name: '$fieldName' [TyE0HDRNAME]\")\n }\n else {\n if (!fieldName.isOkVariableName)\n return Some(s\"Weird field name: '$fieldName' [TyE0VARNAME]\")\n }\n\n if (fieldName.length > maxLength)\n return Some(s\"Too long field name: '$fieldName' [TyE2LNGFLDNM]\")\n\n fieldValue match {\n case _: JsNumber =>\n // Fine\n case s: JsString =>\n if (s.value.isEmpty)\n return Some(s\"Empty value for field $fieldName\")\n\n if (allowHeaderNameValues) {\n // Don't allow newlines in value?\n unimpl(\"TyE50MFEDJ4602\")\n }\n else if (!s.value.isOkVariableName) {\n return Some(s\"Bad value for field $fieldName: '$fieldValue'\")\n }\n\n if (s.value.length > maxLength)\n return Some(s\"Too long field value, $fieldName: '$fieldValue'\")\n\n case _ =>\n return Some(s\"Value of field $fieldName is not a nummer or string; it is a ${\n classNameOf(fieldValue)} [TyEFIELDVALTYP]\")\n }\n }\n None\n }\n\n /** Default value doesn't work with anyJsonObj.flatMap(anyWeirdJsObjField)\n */\n def anyWeirdJsObjField(obj: JsObject): Option[String] =", "label": 1, "label_name": "safe"} -{"code": " public static function decodeDeflate($data)\n {\n if (!function_exists('gzuncompress')) {\n throw new HTTP_Request2_LogicException(\n 'Unable to decode body: gzip extension not available',\n HTTP_Request2_Exception::MISCONFIGURATION\n );\n }\n // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,\n // while many applications send raw deflate stream from RFC 1951.\n // We should check for presence of zlib header and use gzuncompress() or\n // gzinflate() as needed. See bug #15305\n $header = unpack('n', substr($data, 0, 2));\n return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);\n }", "label": 0, "label_name": "vulnerable"} -{"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(3 * 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": 0, "label_name": "vulnerable"} -{"code": "1,b.length-this.index-1);b.length==this.limit&&b.shift();this.index=b.push(c)-1;this.currentImage=c;!1!==d&&this.fireChange();return!0},restoreImage:function(a){var c=this.editor,d;a.bookmarks&&(c.focus(),d=c.getSelection());this.locked=1;this.editor.loadSnapshot(a.contents);a.bookmarks?d.selectBookmarks(a.bookmarks):CKEDITOR.env.ie&&(d=this.editor.document.getBody().$.createTextRange(),d.collapse(!0),d.select());this.locked=0;this.index=a.index;this.currentImage=this.snapshots[this.index];this.update();\nthis.fireChange();c.fire(\"change\")},getNextImage:function(a){var c=this.snapshots,d=this.currentImage,b;if(d)if(a)for(b=this.index-1;0<=b;b--){if(a=c[b],!d.equalsContent(a))return a.index=b,a}else for(b=this.index+1;bmarkTestSkipped('CURLOPT_POSTREDIR required for strict redirects, available in PHP 5.3.2+');\n } else {\n parent::testRedirectsStrict();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testKeepAbsoluteCSSWidthAndHeightOnImg()\n {\n $this->assertResult(\n '\"\"'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " it \"returns false\" do\n socket.connect.should be_false\n end", "label": 0, "label_name": "vulnerable"} -{"code": "def test_plugins_cli_error_messages_invalid_example(example):\n result = httpie(*example.split(), no_debug=True)\n assert result.exit_status == ExitStatus.ERROR\n assert 'usage: ' in result.stderr\n assert f'http {example}' not in result.stderr\n assert f'https {example}' not in result.stderr", "label": 1, "label_name": "safe"} -{"code": " it \"creates an article with a password\" do\n post :create, params: { \"article\" => base_article(password: \"foobar\") }\n new_article = Article.last\n expect(new_article.password).to eq(\"foobar\")\n end", "label": 1, "label_name": "safe"} -{"code": "\tthis.dialog = function(content, options) {\n\t\tvar dialog = $('
').append(content).appendTo(node).elfinderdialog(options),\n\t\t\tdnode = dialog.closest('.ui-dialog'),\n\t\t\tresize = function() {\n\t\t\t\t! dialog.data('draged') && dialog.is(':visible') && dialog.elfinderdialog('posInit');\n\t\t\t};\n\t\tif (dnode.length) {\n\t\t\tself.bind('resize', resize);\n\t\t\tdnode.on('remove', function() {\n\t\t\t\tself.unbind('resize', resize);\n\t\t\t});\n\t\t}\n\t\treturn dialog;\n\t};", "label": 1, "label_name": "safe"} -{"code": "export function escapeCommentText(value: string): string {\n return value.replace(\n COMMENT_DISALLOWED, (text) => text.replace(COMMENT_DELIMITER, COMMENT_DELIMITER_ESCAPED));\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "int main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n Mounter srv;\n\n return app.exec();\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct($exceptions = false) {\n $this->exceptions = ($exceptions == true);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "encodeURIComponent(K):\"\")+\"&extras=\"+encodeURIComponent(JSON.stringify(y))+(0 hostgroups(:common).id}, set_session_user\n assert_template 'new'\n end", "label": 1, "label_name": "safe"} -{"code": " public function testIsExpiredReturnsTrueIfCompiledFileDoesntExist()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('exists')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(false);\n $this->assertTrue($compiler->isExpired('foo'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " 61: (self, payload) => {\n if (!self._authsQueue.length) {\n self._debug\n && self._debug('Inbound: Received payload type 61 without auth');\n return;\n }\n /*\n byte SSH_MSG_USERAUTH_INFO_RESPONSE\n int num-responses\n string response[1] (ISO-10646 UTF-8)\n ...\n string response[num-responses] (ISO-10646 UTF-8)\n */\n if (self._authsQueue[0] !== 'keyboard-interactive') {\n return doFatalError(\n self,\n 'Inbound: Received unexpected payload type 61'\n );\n }\n bufferParser.init(payload, 1);\n const numResponses = bufferParser.readUInt32BE();\n let responses;\n if (numResponses !== undefined) {\n responses = new Array(numResponses);\n let i;\n for (i = 0; i < numResponses; ++i) {\n const response = bufferParser.readString(true);\n if (response === undefined)\n break;\n responses[i] = response;\n }\n if (i !== numResponses)\n responses = undefined;\n }\n bufferParser.clear();\n\n if (responses === undefined) {\n return doFatalError(\n self,\n 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet'\n );\n }\n\n self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE');\n\n const handler = self._handlers.USERAUTH_INFO_RESPONSE;\n handler && handler(self, responses);\n },", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "_PyMem_RawRealloc(void *ctx, void *ptr, size_t size)\n{\n if (size == 0)\n size = 1;\n return realloc(ptr, size);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " stitchSchemas({ subschemas: [autoSchema] }),\n });\n\n parseGraphQLServer.applyGraphQL(expressApp);\n await new Promise(resolve =>\n httpServer.listen({ port: 13377 }, resolve)\n );\n const httpLink = createUploadLink({\n uri: 'http://localhost:13377/graphql',\n fetch,\n headers,\n });\n apolloClient = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n fetchPolicy: 'no-cache',\n },\n },\n });\n });\n\n afterAll(async () => {\n await httpServer.close();\n });\n\n it('can resolve a query', async () => {\n const result = await apolloClient.query({\n query: gql`\n query Health {\n health\n }\n `,\n });\n expect(result.data.health).toEqual(true);\n });\n });", "label": 1, "label_name": "safe"} -{"code": " it \"initializes with the string's bytes\" do\n expect(object_id.to_s).to eq(string)\n end", "label": 1, "label_name": "safe"} -{"code": " it { should contain_supervisord__group('foo').with_program }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should exist\" do\n expect(Puppet::Parser::Functions.function(\"capitalize\")).to eq(\"function_capitalize\")\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\tfunction WarningsReturned($ack)\n\t{\n if(strpos(strtoupper($ack),'WARNING') !== false)\n {\n return true;\n }\n else\n {\n false;\n }\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "\"size\",this.size)));x=mxUtils.getValue(this.style,mxConstants.STYLE_ARCSIZE,mxConstants.LINE_ARCSIZE)/2;this.addPoints(c,[new mxPoint(0,v),new mxPoint(0,l),new mxPoint(p,0),new mxPoint(p,v)],this.isRounded,x,!0);c.end()};mxCellRenderer.registerShape(\"manualInput\",Qa);mxUtils.extend(Ta,mxRectangleShape);Ta.prototype.dx=20;Ta.prototype.dy=20;Ta.prototype.isHtmlAllowed=function(){return!1};Ta.prototype.paintForeground=function(c,l,x,p,v){mxRectangleShape.prototype.paintForeground.apply(this,arguments);", "label": 1, "label_name": "safe"} -{"code": " public function downloadfile() {\n if (empty($this->params['fileid'])) {\n flash('error', gt('There was an error while trying to download your file. No File Specified.'));\n expHistory::back();\n }\n \n $fd = new filedownload($this->params['fileid']); \n if (empty($this->params['filenum'])) $this->params['filenum'] = 0;\n\n if (empty($fd->expFile['downloadable'][$this->params['filenum']]->id)) {\n flash('error', gt('There was an error while trying to download your file. The file you were looking for could not be found.'));\n expHistory::back();\n } \n \n $fd->downloads++;\n $fd->save();\n \n // this will set the id to the id of the actual file..makes the download go right.\n $this->params['id'] = $fd->expFile['downloadable'][$this->params['filenum']]->id;\n parent::downloadfile(); \n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tprivate static async Task ResponseLootByRealAppIDs(EAccess access, string botNames, string realAppIDsText, bool exclude, ulong steamID = 0) {\n\t\tif (!Enum.IsDefined(access)) {\n\t\t\tthrow new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(botNames)) {\n\t\t\tthrow new ArgumentNullException(nameof(botNames));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(realAppIDsText)) {\n\t\t\tthrow new ArgumentNullException(nameof(realAppIDsText));\n\t\t}\n\n\t\tHashSet? bots = Bot.GetBots(botNames);\n\n\t\tif ((bots == null) || (bots.Count == 0)) {\n\t\t\treturn access >= EAccess.Owner ? FormatStaticResponse(string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)) : null;\n\t\t}\n\n\t\tIList results = await Utilities.InParallel(bots.Select(bot => bot.Commands.ResponseLootByRealAppIDs(ProxyAccess(bot, access, steamID), realAppIDsText, exclude))).ConfigureAwait(false);\n\n\t\tList responses = new(results.Where(static result => !string.IsNullOrEmpty(result))!);\n\n\t\treturn responses.Count > 0 ? string.Join(Environment.NewLine, responses) : null;\n\t}", "label": 1, "label_name": "safe"} -{"code": "init_pyfribidi (void)\n{\n PyObject *module = Py_InitModule (\"_pyfribidi\", PyfribidiMethods);\n\tPyModule_AddIntConstant (module, \"RTL\", (long) FRIBIDI_TYPE_RTL);\n\tPyModule_AddIntConstant (module, \"LTR\", (long) FRIBIDI_TYPE_LTR);\n\tPyModule_AddIntConstant (module, \"ON\", (long) FRIBIDI_TYPE_ON);\n}", "label": 1, "label_name": "safe"} -{"code": "function(){function O(ua,ya,Na){var Fa=U.menus.get(ua),Ra=R.addMenu(mxResources.get(ua),mxUtils.bind(this,function(){Fa.funct.apply(this,arguments)}),P);Ra.className=\"1\"==urlParams.sketch?\"geToolbarButton\":\"geMenuItem\";Ra.style.display=\"inline-block\";Ra.style.boxSizing=\"border-box\";Ra.style.top=\"6px\";Ra.style.marginRight=\"6px\";Ra.style.height=\"30px\";Ra.style.paddingTop=\"6px\";Ra.style.paddingBottom=\"6px\";Ra.style.cursor=\"pointer\";Ra.setAttribute(\"title\",mxResources.get(ua));U.menus.menuCreated(Fa,\nRa,\"geMenuItem\");null!=Na?(Ra.style.backgroundImage=\"url(\"+Na+\")\",Ra.style.backgroundPosition=\"center center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.backgroundSize=\"24px 24px\",Ra.style.width=\"34px\",Ra.innerHTML=\"\"):ya||(Ra.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\",Ra.style.backgroundPosition=\"right 6px center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.paddingRight=\"22px\");return Ra}function X(ua,ya,Na,Fa,Ra,db){var Va=document.createElement(\"a\");Va.className=", "label": 0, "label_name": "vulnerable"} -{"code": "pdf_t *pdf_new(const char *name)\n{\n const char *n;\n pdf_t *pdf;\n \n pdf = safe_calloc(sizeof(pdf_t));\n\n if (name)\n {\n /* Just get the file name (not path) */\n if ((n = strrchr(name, '/')))\n ++n;\n else\n n = name;\n\n pdf->name = safe_calloc(strlen(n) + 1);\n strcpy(pdf->name, n);\n }\n else /* !name */\n {\n pdf->name = safe_calloc(strlen(\"Unknown\") + 1);\n strcpy(pdf->name, \"Unknown\");\n }\n\n return pdf;\n}", "label": 1, "label_name": "safe"} -{"code": "\t \t\tself::$collectedInfo[$params['name']] = array('definition' => $params, 'value' => $_FILES[$params['name']]);\r\n\t \t}\r\n\r\n \t} else {\r\n \t\tif (isset(self::$collectedInfo[$params['name']]['value'])){\r\n \t\t\t$valueContent = self::$collectedInfo[$params['name']]['value'];\r\n \t\t\t$downloadLink = \"id.'/'.self::$collectedObject->hash.'/'.$params['name'].\"\\\">Download (\".htmlspecialchars($valueContent['name']).\")\";\r\n \t\t}\r\n \t}\r\n \t\r\n \treturn \"{$downloadLink}\";\r\n }\r", "label": 1, "label_name": "safe"} -{"code": "_isBidi (const uint32_t *label, size_t llen)\n{\n while (llen-- > 0) {\n int bc = uc_bidi_category (*label++);\n\n if (bc == UC_BIDI_R || bc == UC_BIDI_AL || bc == UC_BIDI_AN)\n return 1;\n }\n\n return 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it 'applies the manifest twice with no stderr' do\n expect(apply_manifest(pp, :catch_failures => true).stderr).to eq(\"\")\n expect(apply_manifest(pp, :catch_changes => true).stderr).to eq(\"\")\n end", "label": 0, "label_name": "vulnerable"} -{"code": "e()};OneDriveClient.prototype.getItemRef=function(e){var f=e.split(\"/\");return 1 GetRedemptions()\n {\n var coupons = new CouponRedemptionList();\n var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Get,\n UrlPrefix + Uri.EscapeUriString(Uuid) + \"/redemptions/\",\n coupons.ReadXmlList);\n\n return statusCode == HttpStatusCode.NotFound ? null : coupons;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "var T=document.createElement(\"tbody\"),P=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(e=mxUtils.indexOf(b.pages,b.currentPage));for(q=f.length-1;0<=q;q--){var O=function(R){var Y=new Date(R.modifiedDate),da=null;if(0<=Y.getTime()){var ha=function(ea){v.stop();D.innerHTML=\"\";var aa=mxUtils.parseXml(ea),va=b.editor.extractGraphModel(aa.documentElement,!0);if(null!=va){var la=function(Ba){null!=Ba&&(Ba=Aa(Editor.parseDiagramNode(Ba)));return Ba},Aa=function(Ba){var ua=Ba.getAttribute(\"background\");", "label": 1, "label_name": "safe"} -{"code": "\tremoveClass: function( classNames ) {\n\t\tjQuery.className.remove( this, classNames );\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": " it \"logs in and processes commands\" do\n session.login *Support::MongoHQ.auth_credentials\n session.command(ping: 1).should eq(\"ok\" => 1)\n end", "label": 1, "label_name": "safe"} -{"code": "function(e){var f=e.split(\"/\");return 1child:0;while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}", "label": 1, "label_name": "safe"} -{"code": "bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {\n assertx(m_len != -1);\n if (whence == SEEK_CUR) {\n if (offset > 0 && offset < bufferedLen()) {\n setReadPosition(getReadPosition() + offset);\n setPosition(getPosition() + offset);\n return true;\n }\n offset += getPosition();\n whence = SEEK_SET;\n }\n\n // invalidate the current buffer\n setWritePosition(0);\n setReadPosition(0);\n if (whence == SEEK_SET) {\n m_cursor = offset;\n } else {\n assertx(whence == SEEK_END);\n m_cursor = m_len + offset;\n }\n setPosition(m_cursor);\n return true;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def test_29_catch_terminal_ctrl_k(self):\n \"\"\" F29 | test ctrl-v ctrl-k then command, forbidden/security \"\"\"\n self.child = pexpect.spawn('%s/bin/lshell '\n '--config %s/etc/lshell.conf '\n % (TOPDIR, TOPDIR))\n self.child.expect('%s:~\\$' % self.user)\n\n expected = u'*** forbidden control char: echo\\x0b() bash && echo\\r'\n self.child.send('echo')\n self.child.sendcontrol('v')\n self.child.sendcontrol('k')\n self.child.sendline('() bash && echo')\n self.child.expect('%s:~\\$' % self.user)\n\n result = self.child.before.decode('utf8').split('\\n')[1]\n\n self.assertIn(expected, result)", "label": 1, "label_name": "safe"} -{"code": " public static function sodiumEncrypt($content, $key = null) {\n if ($key === null) {\n $key = self::getGlpiSecKey();\n }\n\n $nonce = random_bytes(SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES); // NONCE = Number to be used ONCE, for each message\n $encrypted = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(\n $content,\n $nonce,\n $nonce,\n $key\n );\n return base64_encode($nonce . $encrypted);\n }", "label": 1, "label_name": "safe"} -{"code": " protected function evalArray($contents)\n {\n return eval('return array(' . $contents . ');');\n }", "label": 1, "label_name": "safe"} -{"code": "p[C]}catch(I){null!=window.console&&console.log(\"Error in vars URL parameter: \"+I)}};Graph.prototype.getExportVariables=function(){return null!=this.globalVars?mxUtils.clone(this.globalVars):{}};var y=Graph.prototype.getGlobalVariable;Graph.prototype.getGlobalVariable=function(p){var C=y.apply(this,arguments);null==C&&null!=this.globalVars&&(C=this.globalVars[p]);return C};Graph.prototype.getDefaultStylesheet=function(){if(null==this.defaultStylesheet){var p=this.themes[\"default-style2\"];this.defaultStylesheet=", "label": 0, "label_name": "vulnerable"} -{"code": "function(){A()}),1E3)});mxEvent.addListener(q,\"click\",mxUtils.bind(this,function(L){var M=mxEvent.getSource(L);M!=v&&M!=x?(null!=g&&g(),A(),mxEvent.consume(L)):z()}));window.setTimeout(mxUtils.bind(this,function(){mxUtils.setPrefixedStyle(q.style,\"transform\",\"translate(-50%,0%)\")}),500);window.setTimeout(z,3E4);m=!0}return m};EditorUi.prototype.setCurrentFile=function(c){null!=c&&(c.opened=new Date);this.currentFile=c};EditorUi.prototype.getCurrentFile=function(){return this.currentFile};EditorUi.prototype.isExportToCanvas=", "label": 0, "label_name": "vulnerable"} -{"code": "void luaD_shrinkstack (lua_State *L) {\n int inuse = stackinuse(L);\n int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;\n if (goodsize > LUAI_MAXSTACK)\n goodsize = LUAI_MAXSTACK; /* respect stack limit */\n /* if thread is currently not handling a stack overflow and its\n good size is smaller than current size, shrink its stack */\n if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) &&\n goodsize < L->stacksize)\n luaD_reallocstack(L, goodsize, 0); /* ok if that fails */\n else /* don't change stack */\n condmovestack(L,{},{}); /* (change only for debugging) */\n luaE_shrinkCI(L); /* shrink CI list */\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it 'squeezes arrays' do\n pp = <<-EOS\n # Real words!\n $a = [\"wallless\", \"laparohysterosalpingooophorectomy\", \"brrr\", \"goddessship\"]\n $o = squeeze($a)\n notice(inline_template('squeeze is <%= @o.inspect %>'))\n EOS\n\n apply_manifest(pp, :catch_failures => true) do |r|\n expect(r.stdout).to match(/squeeze is \\[\"wales\", \"laparohysterosalpingophorectomy\", \"br\", \"godeship\"\\]/)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_addFilter_deprecated()\n {\n $this->expectError('HTMLPurifier->addFilter() is deprecated, use configuration directives in the Filter namespace or Filter.Custom');\n generate_mock_once('HTMLPurifier_Filter');\n $this->purifier->addFilter($mock = new HTMLPurifier_FilterMock());\n $mock->expectOnce('preFilter');\n $mock->expectOnce('postFilter');\n $this->purifier->purify('foo');\n }", "label": 1, "label_name": "safe"} -{"code": " public static buildMintOpReturn(config: configBuildMintOpReturn, type = 0x01) {\n return SlpTokenType1.buildMintOpReturn(\n config.tokenIdHex,\n config.batonVout,\n config.mintQuantity,\n type,\n );\n }", "label": 1, "label_name": "safe"} -{"code": " function fopen($filename, $mode)\n {\n if (\\yiiunit\\framework\\base\\SecurityTest::$fopen !== null) {\n return \\yiiunit\\framework\\base\\SecurityTest::$fopen;\n }\n\n return \\fopen($filename, $mode);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testDebug()\n {\n $handler = new ExceptionHandler(false);\n\n ob_start();\n $handler->sendPhpResponse(new \\RuntimeException('Foo'));\n $response = ob_get_clean();\n\n $this->assertContains('

Whoops, looks like something went wrong.

', $response);\n $this->assertNotContains('

', $response);\n\n $handler = new ExceptionHandler(true);\n\n ob_start();\n $handler->sendPhpResponse(new \\RuntimeException('Foo'));\n $response = ob_get_clean();\n\n $this->assertContains('

Whoops, looks like something went wrong.

', $response);\n $this->assertContains('

', $response);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testDoNotParagraphSingleSurroundingSpaceInBlockNode()\n {\n $this->assertResult(\n'
\nPar1\n
'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "def screenshotcommentcounts(context, screenshot):\n \"\"\"\n Returns a JSON array of current comments for a screenshot.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n text The text of the comment\n localdraft True if this is the current user's draft comment\n x The X location of the comment's region\n y The Y location of the comment's region\n w The width of the comment's region\n h The height of the comment's region\n =========== ==================================================\n \"\"\"\n comments = {}\n user = context.get('user', None)\n\n for comment in screenshot.comments.all():\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n position = '%dx%d+%d+%d' % (comment.w, comment.h, \\\n comment.x, comment.y)\n\n comments.setdefault(position, []).append({\n 'id': comment.id,\n 'text': comment.text,\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n 'url': comment.get_review_url(),\n 'localdraft' : review.user == user and \\\n not review.public,\n 'x' : comment.x,\n 'y' : comment.y,\n 'w' : comment.w,\n 'h' : comment.h,\n })\n\n return simplejson.dumps(comments)", "label": 0, "label_name": "vulnerable"} -{"code": "\t\"ternary?:\": function(test, alternate, consequent, context) {\n\t\treturn function(scope, locals, assign, inputs) {\n\t\t\tvar arg = test(scope, locals, assign, inputs)\n\t\t\t\t? alternate(scope, locals, assign, inputs)\n\t\t\t\t: consequent(scope, locals, assign, inputs);\n\t\t\treturn context ? { value: arg } : arg;\n\t\t};\n\t},", "label": 1, "label_name": "safe"} -{"code": " function import() {\r\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname);\r\n $modules = new expPaginator(array(\r\n 'records' => $pullable_modules,\r\n 'controller' => $this->loc->mod,\r\n 'action' => $this->params['action'],\r\n 'order' => isset($this->params['order']) ? $this->params['order'] : 'section',\r\n 'dir' => isset($this->params['dir']) ? $this->params['dir'] : '',\r\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\r\n 'columns' => array(\r\n gt('Title') => 'title',\r\n gt('Page') => 'section'\r\n ),\r\n ));\r\n\r\n assign_to_template(array(\r\n 'modules' => $modules,\r\n ));\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "\"\",ea=0;eainHead($token);\n\n /* Anything else */\n } else {\n /* Act as if a start tag token with the tag name \"body\" and no\n attributes had been seen, and then reprocess the current token. */\n $this->afterHead(array(\n 'name' => 'body',\n 'type' => HTML5::STARTTAG,\n 'attr' => array()\n ));\n\n return $this->inBody($token);\n }\n }", "label": 1, "label_name": "safe"} -{"code": "parseError: function parseError (str, hash) {\n if (hash.recoverable) {\n this.trace(str);\n } else {\n var error = new Error(str);\n error.hash = hash;\n throw error;\n }\n},", "label": 1, "label_name": "safe"} -{"code": "PyObject_Realloc(void *ptr, size_t new_size)\n{\n /* see PyMem_RawMalloc() */\n if (new_size > (size_t)PY_SSIZE_T_MAX)\n return NULL;\n return _PyObject.realloc(_PyObject.ctx, ptr, new_size);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_extractBody_uppercaseBodyTags()\n {\n $this->assertExtractBody('Bold', 'Bold');\n }", "label": 1, "label_name": "safe"} -{"code": " def update\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n SqlHelper.validate_token([params[:groups], params[:teams]])\n\n @equipment = Equipment.find(params[:id])\n\n if params[:groups].blank?\n params[:equipment][:groups] = nil\n else\n params[:equipment][:groups] = '|' + params[:groups].join('|') + '|'\n end\n\n if params[:teams].blank?\n params[:equipment][:teams] = nil\n else\n params[:equipment][:teams] = '|' + params[:teams].join('|') + '|'\n end\n\n if @equipment.update_attributes(params.require(:equipment).permit(Equipment::PERMIT_BASE))\n flash[:notice] = t('msg.update_success')\n list\n render(:action => 'list')\n else\n render(:controller => 'equipment', :action => 'edit', :id => params[:id])\n end\n end", "label": 1, "label_name": "safe"} -{"code": " public List search(final String filter, final String[] filterArgs, final int maxResultCount) {\n return search(filter, filterArgs, resultWrapper -> (Entry) resultWrapper.getResult(), maxResultCount);\n }", "label": 1, "label_name": "safe"} -{"code": " def loadOneOrTwoSessions(part1Maybe2Or3: Opt[St], part4HttpOnly: Opt[St],\n maybeActiveOnly: Bo): ImmSeq[TySessionInDbMaybeBad]\n def loadActiveSessions(patId: PatId): ImmSeq[TySessionInDbMaybeBad]\n def insertValidSession(session: TySession): U\n def upsertSession(session: TySessionInDbMaybeBad): U\n\n def tryLoginAsMember(loginAttempt: MemberLoginAttempt, requireVerifiedEmail: Boolean)\n : Hopefully[MemberLoginGrant]\n def loginAsGuest(loginAttempt: GuestLoginAttempt): GuestLoginResult\n def configIdtySimple(ctime: ju.Date, emailAddr: String, emailNotfPrefs: EmailNotfPrefs): Unit\n\n def loadUserInclDetails(userId: UserId): Option[UserInclDetails] =\n loadMemberInclDetailsById(userId) map {", "label": 1, "label_name": "safe"} -{"code": "func TestNonceSize(t *testing.T) {\n\taead, err := NewAES256SHA512(make([]byte, 64))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\texpected := 16\n\tactual := aead.NonceSize()\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %v but was %v\", expected, actual)\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": " public function delete() {\n global $db, $history;\n\n /* The global constants can be overriden by passing appropriate params */\n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the comment you would like to delete'));\n $lastUrl = expHistory::getLast('editable');\n }\n\n // delete the note\n $simplenote = new expSimpleNote($this->params['id']);\n $rows = $simplenote->delete();\n\n // delete the assocication too\n $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']);\n\n // send the user back where they came from.\n $lastUrl = expHistory::getLast('editable');\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label": 1, "label_name": "safe"} -{"code": "(self.webpackChunkkimai2=self.webpackChunkkimai2||[]).push([[149],{474:function(i,n,s){s(3648)},3648:function(i,n,s){\"use strict\";s.r(n)}},function(i){\"use strict\";var n;n=474,i(i.s=n)}]);", "label": 1, "label_name": "safe"} -{"code": "PUBLIC cchar *httpGetParam(HttpConn *conn, cchar *var, cchar *defaultValue)\n{\n cchar *value;\n\n value = mprLookupJson(httpGetParams(conn), var);\n return (value) ? value : defaultValue;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic final static function CreateSetupToken()\n\t{\n\t\tif (!is_dir(APPROOT.'data'))\n\t\t{\n\t\t\tmkdir(APPROOT.'data');\n\t\t}\n\t\tif (!is_dir(APPROOT.'data/setup'))\n\t\t{\n\t\t\tmkdir(APPROOT.'data/setup');\n\t\t}\n\t\t$sUID = hash('sha256', rand());\n\t\tfile_put_contents(APPROOT.'data/setup/authent', $sUID);\n\t\t$_SESSION['setup_token'] = $sUID;\n\t\treturn $sUID;\n\t}", "label": 1, "label_name": "safe"} -{"code": " secureErrorAttribute(secureError, sourceError, attribute) {\r\n if (!Object.keys(sourceError).includes(attribute)) {\r\n return;\r\n }\r\n secureError[attribute] = this.secureAttributeValue(sourceError[attribute]);\r\n }\r", "label": 1, "label_name": "safe"} -{"code": "function mci_check_login( $p_username, $p_password ) {\n\tif( mci_is_mantis_offline() ) {\n\t\treturn false;\n\t}\n\n\t# if no user name supplied, then attempt to login as anonymous user.\n\tif( is_blank( $p_username ) ) {\n\t\t$t_anon_allowed = config_get( 'allow_anonymous_login' );\n\t\tif( OFF == $t_anon_allowed ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$p_username = config_get( 'anonymous_account' );\n\n\t\t# do not use password validation.\n\t\t$p_password = null;\n\t} else {\n\t\tif( is_blank( $p_password ) ) {\n\t\t\t# require password for authenticated access\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif( false === auth_attempt_script_login( $p_username, $p_password ) ) {\n\t\treturn false;\n\t}\n\n\treturn auth_get_current_user_id();\n}", "label": 1, "label_name": "safe"} -{"code": "def create(request, topic_id):\n topic = get_object_or_404(\n Topic.objects.for_access(request.user),\n pk=topic_id)\n form = NotificationCreationForm(\n user=request.user,\n topic=topic,\n data=request.POST)\n\n if form.is_valid():\n form.save()\n else:\n messages.error(request, utils.render_form_errors(form))\n\n return safe_redirect(request, 'next', topic.get_absolute_url(), method='POST')", "label": 1, "label_name": "safe"} -{"code": " function _getBaseDN()\n {\n $this->log('Auth_Container_LDAP::_getBaseDN() called.', AUTH_LOG_DEBUG);\n $err = $this->_prepare();\n if ($err !== true) {\n return PEAR::raiseError($err->getMessage(), $err->getCode());\n }\n\n if ($this->options['basedn'] == \"\" && $this->_isValidLink()) {\n $this->log(\"basedn not set, searching via namingContexts.\", AUTH_LOG_DEBUG);\n\n $result_id = @ldap_read($this->conn_id, \"\", \"(objectclass=*)\", array(\"namingContexts\"));\n\n if (@ldap_count_entries($this->conn_id, $result_id) == 1) {\n\n $this->log(\"got result for namingContexts\", AUTH_LOG_DEBUG);\n\n $entry_id = @ldap_first_entry($this->conn_id, $result_id);\n $attrs = @ldap_get_attributes($this->conn_id, $entry_id);\n $basedn = $attrs['namingContexts'][0];\n\n if ($basedn != \"\") {\n $this->log(\"result for namingContexts was $basedn\", AUTH_LOG_DEBUG);\n $this->options['basedn'] = $basedn;\n }\n }\n @ldap_free_result($result_id);\n }\n\n // if base ist still not set, raise error\n if ($this->options['basedn'] == \"\") {\n return PEAR::raiseError(\"Auth_Container_LDAP: LDAP search base not specified!\", 41);\n }\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " protected function getExternalTaskLink(array $task)\n {\n $link = $this->taskExternalLinkModel->getById($this->request->getIntegerParam('link_id'));\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n if ($link['task_id'] != $task['id']) {\n throw new AccessForbiddenException();\n }\n\n return $link;\n }", "label": 1, "label_name": "safe"} -{"code": "function(c,e){if(Graph.isPageLink(e)){var g=c[e.substring(e.indexOf(\",\")+1)];e=null!=g?\"data:page/id,\"+g:null}else if(\"data:action/json,\"==e.substring(0,17))try{var k=JSON.parse(e.substring(17));if(null!=k.actions){for(var m=0;massertEqualYamlStructure(file_get_contents(self::$fixturesPath.'/yaml/services1.yml'), $dumper->dump(), '->dump() dumps an empty container as an empty YAML file');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public async Task Edit(string contentItemId)\n {\n var contentItem = await _contentManager.GetAsync(contentItemId);\n\n if (contentItem == null)\n {\n return NotFound();\n }\n\n if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, CommonPermissions.EditContent, contentItem))\n {\n return Forbid();\n }\n\n var shape = await _contentDisplay.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false);\n return View(shape);\n }", "label": 1, "label_name": "safe"} -{"code": " public function getAlias($id)\n {\n $id = strtolower($id);\n\n if (!isset($this->aliasDefinitions[$id])) {\n throw new InvalidArgumentException(sprintf('The service alias \"%s\" does not exist.', $id));\n }\n\n return $this->aliasDefinitions[$id];\n }", "label": 0, "label_name": "vulnerable"} -{"code": "Note.renderNote = function(note) {\n if (!note) {\n return;\n }\n // title\n $(\"#noteTitle\").val(note.Title);\n\n // \u5f53\u524d\u6b63\u5728\u7f16\u8f91\u7684\n // tags\n Tag.input.setTags(note.Tags);\n};", "label": 0, "label_name": "vulnerable"} -{"code": "var T=document.createElement(\"tbody\"),N=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(g=mxUtils.indexOf(b.pages,b.currentPage));for(q=e.length-1;0<=q;q--){var Q=function(R){var Y=new Date(R.modifiedDate),ba=null;if(0<=Y.getTime()){var ea=function(fa){x.stop();v.innerHTML=\"\";var aa=mxUtils.parseXml(fa),va=b.editor.extractGraphModel(aa.documentElement,!0);if(null!=va){var ja=function(Ha){null!=Ha&&(Ha=Ba(Editor.parseDiagramNode(Ha)));return Ha},Ba=function(Ha){var ra=Ha.getAttribute(\"background\");\nif(null==ra||\"\"==ra||ra==mxConstants.NONE)ra=d.defaultPageBackgroundColor;n.style.backgroundColor=ra;(new mxCodec(Ha.ownerDocument)).decode(Ha,d.getModel());d.maxFitScale=1;d.fit(8);d.center();return Ha};M.style.display=\"none\";M.innerHTML=\"\";t=aa;z=fa;k=parseSelectFunction=null;l=0;if(\"mxfile\"==va.nodeName){aa=va.getElementsByTagName(\"diagram\");k=[];for(fa=0;famessages[] = $event;\n\n\t}", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " function listUsers()\n {\n $this->log('Auth::listUsers() called.', AUTH_LOG_DEBUG);\n $this->_loadStorage();\n return $this->storage->listUsers();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function deleteAllCustomDNSEntries()\n{\n if (isset($customDNSFile))\n {\n $handle = fopen($customDNSFile, \"r\");\n if ($handle)\n {\n try\n {\n while (($line = fgets($handle)) !== false) {\n $line = str_replace(\"\\r\",\"\", $line);\n $line = str_replace(\"\\n\",\"\", $line);\n $explodedLine = explode (\" \", $line);\n\n if (count($explodedLine) != 2)\n continue;\n\n $ip = $explodedLine[0];\n $domain = $explodedLine[1];\n\n pihole_execute(\"-a removecustomdns \".$ip.\" \".$domain);\n }\n }\n catch (\\Exception $ex)\n {\n return errorJsonResponse($ex->getMessage());\n }\n\n fclose($handle);\n }\n }\n\n return successJsonResponse();\n}", "label": 1, "label_name": "safe"} -{"code": "MONGO_EXPORT void __mongo_set_error( mongo *conn, mongo_error_t err, const char *str,\n int errcode ) {\n int errstr_size, str_size;\n\n conn->err = err;\n conn->errcode = errcode;\n\n if( str ) {\n str_size = strlen( str ) + 1;\n errstr_size = str_size > MONGO_ERR_LEN ? MONGO_ERR_LEN : str_size;\n memcpy( conn->errstr, str, errstr_size );\n conn->errstr[errstr_size-1] = '\\0';\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should delete all undef items from Hash and only these\" do\n result = scope.function_delete_undef_values([{'a'=>'A','b'=>:undef,'c'=>'C','d'=>'undef'}])\n expect(result).to(eq({'a'=>'A','c'=>'C','d'=>'undef'}))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask/remove', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function onSFTP() {\n if (clientSFTP && serverSFTP)\n self.onReady(clientSFTP, serverSFTP);\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct($n = '0', $u = false) {\n $this->n = (string) $n;\n $this->unit = $u !== false ? (string) $u : false;\n }", "label": 1, "label_name": "safe"} -{"code": " public function testSpuriousEndTag()\n {\n $this->assertResult('', '');\n }", "label": 1, "label_name": "safe"} -{"code": " def tearDown(self):\n if os.path.isfile(self.filename):\n os.unlink(self.filename)", "label": 0, "label_name": "vulnerable"} -{"code": " public function filter(&$uri, $config, $context)\n {\n return !$context->get('EmbeddedURI', true);\n }", "label": 1, "label_name": "safe"} -{"code": " function m(file) {\n const p = path.join(certificateFolder, file);\n if (!fs.existsSync(p)) {\n console.error(\" cannot find \", p);\n }\n return p;\n }", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": "\tpublic function post_prop () {\n\t\t$file = urldecode (join ('/', func_get_args ()));\n\t\tif (! FileManager::verify_file ($file)) {\n\t\t\treturn $this->error (__ ('Invalid file name'));\n\t\t}\n\t\t\n\t\t// handle multiple properties at once\n\t\tif (isset ($_POST['props'])) {\n\t\t\tif (! is_array ($_POST['props'])) {\n\t\t\t\treturn $this->error (__ ('Invalid properties'));\n\t\t\t}\n\t\t\t\n\t\t\tforeach ($_POST['props'] as $k => $v) {\n\t\t\t\tif (FileManager::prop ($file, $k, $v) === false) {\n\t\t\t\t\treturn $this->error (__ ('Error saving properties.'));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn array (\n\t\t\t\t'file' => $file,\n\t\t\t\t'props' => $_POST['props'],\n\t\t\t\t'msg' => __ ('Properties saved.')\n\t\t\t);\n\t\t}\n\t\t\n\t\t// handle a single property\n\t\tif (! isset ($_POST['prop'])) {\n\t\t\treturn $this->error (__ ('Missing property name'));\n\t\t}\n\t\tif (isset ($_POST['value'])) {\n\t\t\t// update and fetch\n\t\t\t$res = FileManager::prop ($file, $_POST['prop'], $_POST['value']);\n\t\t} else {\n\t\t\t// fetch\n\t\t\t$res = FileManager::prop ($file, $_POST['prop']);\n\t\t}\n\t\treturn array (\n\t\t\t'file' => $file,\n\t\t\t'prop' => $_POST['prop'],\n\t\t\t'value' => $res,\n\t\t\t'msg' => __ ('Properties saved.')\n\t\t);\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " stripEventHandlersInHtml: function (html) {\n function stripHTML(){\n html = html.slice(0, strip) + html.slice(j);\n j = strip;\n strip = false;\n }\n function isValidTagChar(str) {\n return str.match(/[a-z?\\\\\\/!]/i);\n }\n var strip = false;\n var lastQuote = false;\n for (var i = 0; i\"){\n if (strip) {\n stripHTML();\n }\n i = j;\n break;\n }\n if (lastQuote === html[j]){\n lastQuote = false;\n continue;\n }\n if (!lastQuote && html[j-1] === \"=\" && (html[j] === \"'\" || html[j] === '\"')){\n lastQuote = html[j];\n }\n if (!lastQuote && html[j-2] === \" \" && html[j-1] === \"o\" && html[j] === \"n\"){\n strip = j-2;\n }\n if (strip && html[j] === \" \" && !lastQuote){\n stripHTML();\n }\n }\n }\n }\n return html;\n },", "label": 1, "label_name": "safe"} -{"code": "void Huff_Compress(msg_t *mbuf, int offset) {\n\tint\t\t\ti, ch, size;\n\tbyte\t\tseq[65536];\n\tbyte*\t\tbuffer;\n\thuff_t\t\thuff;\n\n\tsize = mbuf->cursize - offset;\n\tbuffer = mbuf->data+ + offset;\n\n\tif (size<=0) {\n\t\treturn;\n\t}\n\n\tCom_Memset(&huff, 0, sizeof(huff_t));\n\t// Add the NYT (not yet transmitted) node into the tree/list */\n\thuff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]);\n\thuff.tree->symbol = NYT;\n\thuff.tree->weight = 0;\n\thuff.lhead->next = huff.lhead->prev = NULL;\n\thuff.tree->parent = huff.tree->left = huff.tree->right = NULL;\n\n\tseq[0] = (size>>8);\n\tseq[1] = size&0xff;\n\n\tbloc = 16;\n\n\tfor (i=0; icursize = (bloc>>3) + offset;\n\tCom_Memcpy(mbuf->data+offset, seq, (bloc>>3));\n}", "label": 1, "label_name": "safe"} -{"code": " public void validateFail2(ViolationCollector col) {\n col.addViolation(\"p2\", FAILED);\n }", "label": 1, "label_name": "safe"} -{"code": " it 'handles non-indicies arguments' do\n pp = <<-EOS\n $one = ['a','b','c','d','e']\n $two = []\n $output = values_at($one,$two)\n notice(inline_template('<%= @output.inspect %>'))\n EOS\n\n expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/at least one positive index/)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public async Task UpdateListBySeries(UpdateReadingListBySeriesDto dto)\n {\n var user = await UserHasReadingListAccess(dto.ReadingListId);\n if (user == null)\n {\n return BadRequest(\"You do not have permissions on this reading list or the list doesn't exist\");\n }\n\n var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);\n if (readingList == null) return BadRequest(\"Reading List does not exist\");\n var chapterIdsForSeries =\n await _unitOfWork.SeriesRepository.GetChapterIdsForSeriesAsync(new [] {dto.SeriesId});\n\n // If there are adds, tell tracking this has been modified\n if (await AddChaptersToReadingList(dto.SeriesId, chapterIdsForSeries, readingList))\n {\n _unitOfWork.ReadingListRepository.Update(readingList);\n }\n\n try\n {\n if (_unitOfWork.HasChanges())\n {\n await _unitOfWork.CommitAsync();\n return Ok(\"Updated\");\n }\n }\n catch\n {\n await _unitOfWork.RollbackAsync();\n }\n\n return Ok(\"Nothing to do\");\n }", "label": 1, "label_name": "safe"} -{"code": " if(saml2PSecurityTokenHandler != null)\n {\n throw new InvalidOperationException(\"Can't change entity id when a token handler has been instantiated.\");\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct($points)\n {\n $this->points = $this->formatPoints($points);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def test_basic_for_domain():\n # Test Basic Authentication\n http = httplib2.Http()\n password = tests.gen_password()\n handler = tests.http_reflect_with_auth(allow_scheme=\"basic\", allow_credentials=((\"joe\", password),))\n with tests.server_request(handler, request_count=4) as uri:\n response, content = http.request(uri, \"GET\")\n assert response.status == 401\n http.add_credentials(\"joe\", password, \"example.org\")\n response, content = http.request(uri, \"GET\")\n assert response.status == 401\n domain = urllib.parse.urlparse(uri)[1]\n http.add_credentials(\"joe\", password, domain)\n response, content = http.request(uri, \"GET\")\n assert response.status == 200", "label": 1, "label_name": "safe"} -{"code": " def test_28_checksecure_quoted_command(self):\n \"\"\" U28 | quoted command should be parsed \"\"\"\n INPUT = \"echo'/1.sh'\"\n return self.assertEqual(sec.check_secure(INPUT, self.userconf)[0], 1)", "label": 1, "label_name": "safe"} -{"code": " $evs = $this->event->find('all', \"id=\" . $edate->event_id . $featuresql);\n foreach ($evs as $key=>$event) {\n if ($condense) {\n $eventid = $event->id;\n $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\n if (!empty($multiday_event)) {\n unset($evs[$key]);\n continue;\n }\n }\n $evs[$key]->eventstart += $edate->date;\n $evs[$key]->eventend += $edate->date;\n $evs[$key]->date_id = $edate->id;\n if (!empty($event->expCat)) {\n $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\n// if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\n $evs[$key]->color = $catcolor;\n }\n }\n if (count($events) < 500) { // magic number to not crash loop?\n $events = array_merge($events, $evs);\n } else {\n// $evs[$key]->title = gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!');\n// $events = array_merge($events, $evs);\n flash('notice',gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!'));\n break; // keep from breaking system by too much data\n }\n }", "label": 1, "label_name": "safe"} -{"code": " $body = str_replace(array(\"\\n\"), \"
\", $body);\r\n } else {\r\n // It's going elsewhere (doesn't like quoted-printable)\r\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\r\n }\r\n $title = $items[$i]->title;\r\n\r\n $msg .= \"BEGIN:VEVENT\\n\";\r\n $msg .= $dtstart . $dtend;\r\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\r\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\r\n if ($title) {\r\n $msg .= \"SUMMARY:$title\\n\";\r\n }\r\n if ($body) {\r\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\r\n }\r\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\r\n if (!empty($this->config['usecategories'])) {\r\n if (!empty($items[$i]->expCat[0]->title)) {\r\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\r\n } else {\r\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\r\n }\r\n }\r\n $msg .= \"END:VEVENT\\n\";\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public void appendText(String text) {\n if (text == null) {\n return;\n }\n String previous = this.binding.textinput.getText().toString();\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": 0, "label_name": "vulnerable"} -{"code": " public function testSetSaveHandler54()\n {\n $this->iniSet('session.save_handler', 'files');\n $storage = $this->getStorage();\n $storage->setSaveHandler();\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(null);\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new SessionHandlerProxy(new NativeSessionHandler()));\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new NativeSessionHandler());\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler()));\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new NullSessionHandler());\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should convert boolean true to [ true ] \" do\n result = scope.function_any2array([true])\n expect(result).to(eq([true]))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public static IRubyObject read_memory(ThreadContext context, IRubyObject klazz, IRubyObject content) {\n String data = content.convertToString().asJavaString();\n return getSchema(context, (RubyClass) klazz, new StreamSource(new StringReader(data)));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def create\n allvalidchains do |t, chain, table, protocol|\n if chain =~ InternalChains\n # can't create internal chains\n warning \"Attempting to create internal chain #{@resource[:name]}\"\n end\n if properties[:ensure] == protocol\n debug \"Skipping Inserting chain #{chain} on table #{table} (#{protocol}) already exists\"\n else\n debug \"Inserting chain #{chain} on table #{table} (#{protocol}) using #{t}\"\n t.call ['-t',table,'-N',chain]\n unless @resource[:policy].nil?\n t.call ['-t',table,'-P',chain,@resource[:policy].to_s.upcase]\n end\n end\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " void setPayload(final String s) {\n this.payload = PayloadUtil.deserialize(s);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tnormalize : function(data) {\n\t\tvar filter = function(file) { \n\t\t\n\t\t\tif (file && file.hash && file.name && file.mime) {\n\t\t\t\tif (file.mime == 'application/x-empty') {\n\t\t\t\t\tfile.mime = 'text/plain';\n\t\t\t\t}\n\t\t\t\treturn file;\n\t\t\t}\n\t\t\treturn null;\n\t\t\treturn file && file.hash && file.name && file.mime ? file : null; \n\t\t};\n\t\t\n\n\t\tif (data.files) {\n\t\t\tdata.files = $.map(data.files, filter);\n\t\t} \n\t\tif (data.tree) {\n\t\t\tdata.tree = $.map(data.tree, filter);\n\t\t}\n\t\tif (data.added) {\n\t\t\tdata.added = $.map(data.added, filter);\n\t\t}\n\t\tif (data.changed) {\n\t\t\tdata.changed = $.map(data.changed, filter);\n\t\t}\n\t\tif (data.api) {\n\t\t\tdata.init = true;\n\t\t}\n\t\treturn data;\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": " \"should remove the property\": function (res) {\n assert.isUndefined(res.a);\n },", "label": 1, "label_name": "safe"} -{"code": " public function __construct(\n $streamOrFile,\n $size,\n $errorStatus,\n $clientFilename = null,\n $clientMediaType = null\n ) {\n $this->setError($errorStatus);\n $this->setSize($size);\n $this->setClientFilename($clientFilename);\n $this->setClientMediaType($clientMediaType);\n\n if ($this->isOk()) {\n $this->setStreamOrFile($streamOrFile);\n }\n }", "label": 1, "label_name": "safe"} -{"code": "function(O){O=da.apply(this,arguments);var X=this.editorUi,ea=X.editor.graph;if(ea.isEnabled()&&\"1\"==urlParams.sketch){var ka=this.createOption(mxResources.get(\"sketch\"),function(){return Editor.sketchMode},function(ja,U){X.setSketchMode(!Editor.sketchMode);null!=U&&mxEvent.isShiftDown(U)||ea.updateCellStyles({sketch:ja?\"1\":null},ea.getVerticesAndEdges())},{install:function(ja){this.listener=function(){ja(Editor.sketchMode)};X.addListener(\"sketchModeChanged\",this.listener)},destroy:function(){X.removeListener(this.listener)}});", "label": 0, "label_name": "vulnerable"} -{"code": " public function testSetGetClass()\n {\n $def = new Definition('stdClass');\n $this->assertSame($def, $def->setClass('foo'), '->setClass() implements a fluent interface');\n $this->assertEquals('foo', $def->getClass(), '->getClass() returns the class name');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def testInvalidBlockShape(self):\n tf_in = constant_op.constant(\n -3.5e+35, shape=[10, 20, 20], dtype=dtypes.float32)\n block_shape = constant_op.constant(-10, shape=[2], dtype=dtypes.int64)\n paddings = constant_op.constant(0, shape=[2, 2], dtype=dtypes.int32)\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n \"block_shape must be positive\"):\n array_ops.space_to_batch_nd(tf_in, block_shape, paddings)", "label": 1, "label_name": "safe"} -{"code": "\tprivate function _addpagecounter( $option ) {\n\t\tif ( class_exists( \"\\\\HitCounters\\\\Hooks\" ) ) {\n\t\t\t$this->addTable( 'hit_counter', 'hit_counter' );\n\t\t\t$this->addSelect(\n\t\t\t\t[\n\t\t\t\t\t\"page_counter\"\t=> \"hit_counter.page_counter\"\n\t\t\t\t]\n\t\t\t);\n\n\t\t\tif ( !isset( $this->join['hit_counter'] ) ) {\n\t\t\t\t$this->addJoin(\n\t\t\t\t\t'hit_counter',\n\t\t\t\t\t[\n\t\t\t\t\t\t\"LEFT JOIN\",\n\t\t\t\t\t\t\"hit_counter.page_id = \" . $this->tableNames['page'] . '.page_id'\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}", "label": 1, "label_name": "safe"} -{"code": "\trun_server_script: function() {\n\t\t// DEPRECATE\n\t\tvar me = this;\n\t\tif(this.frm && this.frm.docname) {\n\t\t\tfrappe.call({\n\t\t\t\tmethod: \"runserverobj\",\n\t\t\t\targs: {'docs': this.frm.doc, 'method': this.df.options },\n\t\t\t\tbtn: this.$input,\n\t\t\t\tcallback: function(r) {\n\t\t\t\t\tif(!r.exc) {\n\t\t\t\t\t\tme.frm.refresh_fields();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": "static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)\n{\n\tjas_ulonglong tmp;\n\tif (jas_iccgetuint(in, 2, &tmp))\n\t\treturn -1;\n\t*val = tmp;\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": " $keys = array_keys($var);\n if (array_keys($keys) !== $keys) {\n $this->error('Indices for list are not uniform');\n }\n }\n return $var;\n case (self::C_MIXED):\n return $var;\n default:\n $this->errorInconsistent(get_class($this), $type);\n }\n $this->errorGeneric($var, $type);\n }", "label": 1, "label_name": "safe"} -{"code": "def get_release_file(root, request):\n session = DBSession()\n\n f = ReleaseFile.by_id(session, int(request.matchdict['file_id']))\n url = f.url\n if url.startswith('http://pypi.python.org'):\n url = 'https' + url[4:]\n\n rv = {'id': f.id,\n 'url': url,\n 'filename': f.filename,\n }\n f.downloads += 1\n f.release.downloads += 1\n f.release.package.downloads += 1\n session.add(f.release.package)\n session.add(f.release)\n session.add(f)\n return rv", "label": 1, "label_name": "safe"} -{"code": "ServerSecurityFeature::ServerSecurityFeature(application_features::ApplicationServer& server)\n : ApplicationFeature(server, \"ServerSecurity\"),\n _enableFoxxApi(true),\n _enableFoxxStore(true),\n _hardenedRestApi(false),\n _foxxAllowInstallFromRemote(false) {\n setOptional(false);\n startsAfter();\n}", "label": 1, "label_name": "safe"} -{"code": " protected function createResponse()\n {\n $response = new Response();\n $response->setStatusCode(200);\n $response->headers->set('Content-Type', 'application/json');\n $response->headers->setCookie(new Cookie('foo', 'bar', 1, '/foo', 'localhost', true, true));\n $response->headers->setCookie(new Cookie('bar', 'foo', new \\DateTime('@946684800')));\n $response->headers->setCookie(new Cookie('bazz', 'foo', '2000-12-12'));\n\n return $response;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "func (*UpdateAccountRequest) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{36}\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static int snd_compr_allocate_buffer(struct snd_compr_stream *stream,\n\t\tstruct snd_compr_params *params)\n{\n\tunsigned int buffer_size;\n\tvoid *buffer;\n\n\tif (params->buffer.fragment_size == 0 ||\n\t params->buffer.fragments > SIZE_MAX / params->buffer.fragment_size)\n\t\treturn -EINVAL;\n\n\tbuffer_size = params->buffer.fragment_size * params->buffer.fragments;\n\tif (stream->ops->copy) {\n\t\tbuffer = NULL;\n\t\t/* if copy is defined the driver will be required to copy\n\t\t * the data from core\n\t\t */\n\t} else {\n\t\tbuffer = kmalloc(buffer_size, GFP_KERNEL);\n\t\tif (!buffer)\n\t\t\treturn -ENOMEM;\n\t}\n\tstream->runtime->fragment_size = params->buffer.fragment_size;\n\tstream->runtime->fragments = params->buffer.fragments;\n\tstream->runtime->buffer = buffer;\n\tstream->runtime->buffer_size = buffer_size;\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": "static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len)\n{\n int offset = 0;\n const uint8_t *ptr = NULL;\n\n if (asn1_next_obj(asn1_sig, &offset, ASN1_SEQUENCE) < 0 || \n asn1_skip_obj(asn1_sig, &offset, ASN1_SEQUENCE))\n goto end_get_sig;\n\n if (asn1_sig[offset++] != ASN1_OCTET_STRING)\n goto end_get_sig;\n *len = get_asn1_length(asn1_sig, &offset);\n ptr = &asn1_sig[offset]; /* all ok */\n\nend_get_sig:\n return ptr;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def get_auth_teams\n Log.add_info(request, params.inspect)\n\n folder_id = params[:id]\n SqlHelper.validate_token([folder_id])\n\n begin\n @folder = Folder.find(folder_id)\n rescue\n @folder = nil\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\n session[:folder_id] = folder_id\n\n render(:partial => 'ajax_auth_teams', :layout => false)\n end", "label": 1, "label_name": "safe"} -{"code": " public function testSingleSpanWithAttributes()\n {\n $this->assertResult(\n 'foo',\n 'foo'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " public function testGetDropdownValue($params, $expected, $session_params = []) {\n $this->login();\n\n $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n\n $params['_idor_token'] = \\Session::getNewIDORToken($params['itemtype'] ?? '');\n\n $result = \\Dropdown::getDropdownValue($params, false);\n\n //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }\n\n $this->array($result)->isIdenticalTo($expected);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tawait promises_.rm(temporaryPath, {recursive: true, force: true});\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": " def test_conf_set_no_read(self):\n orig_parser = memcache.ConfigParser\n memcache.ConfigParser = ExcConfigParser\n exc = None\n try:\n app = memcache.MemcacheMiddleware(\n FakeApp(), {'memcache_servers': '1.2.3.4:5',\n 'memcache_serialization_support': '2'})\n except Exception, err:\n exc = err\n finally:\n memcache.ConfigParser = orig_parser\n self.assertEquals(exc, None)", "label": 1, "label_name": "safe"} -{"code": "def render_archived_books(page, sort_param):\n order = sort_param[0] or []\n archived_books = (\n ub.session.query(ub.ArchivedBook)\n .filter(ub.ArchivedBook.user_id == int(current_user.id))\n .filter(ub.ArchivedBook.is_archived == True)\n .all()\n )\n archived_book_ids = [archived_book.book_id for archived_book in archived_books]\n\n archived_filter = db.Books.id.in_(archived_book_ids)\n\n entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, db.Books,\n 0,\n archived_filter,\n order,\n True,\n False, 0)\n\n name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')'\n pagename = \"archived\"\n return render_title_template('index.html', random=random, entries=entries, pagination=pagination,\n title=name, page=pagename, order=sort_param[1])", "label": 0, "label_name": "vulnerable"} -{"code": "void sctp_generate_proto_unreach_event(unsigned long data)\n{\n\tstruct sctp_transport *transport = (struct sctp_transport *) data;\n\tstruct sctp_association *asoc = transport->asoc;\n\tstruct net *net = sock_net(asoc->base.sk);\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\\n\", __func__);\n\n\t\t/* Try again later. */\n\t\tif (!mod_timer(&transport->proto_unreach_timer,\n\t\t\t\tjiffies + (HZ/20)))\n\t\t\tsctp_association_hold(asoc);\n\t\tgoto out_unlock;\n\t}\n\n\t/* Is this structure just waiting around for us to actually\n\t * get destroyed?\n\t */\n\tif (asoc->base.dead)\n\t\tgoto out_unlock;\n\n\tsctp_do_sm(net, SCTP_EVENT_T_OTHER,\n\t\t SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH),\n\t\t asoc->state, asoc->ep, asoc, transport, GFP_ATOMIC);\n\nout_unlock:\n\tbh_unlock_sock(asoc->base.sk);\n\tsctp_association_put(asoc);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function delete() {\n\t global $db;\n\n /* The global constants can be overriden by passing appropriate params */\n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('Missing id for the comment you would like to delete'));\n\t expHistory::back();\n\t }\n\n\t // delete the comment\n $comment = new expComment($this->params['id']);\n $comment->delete();\n\n // delete the association too\n $db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']);\n\n // send the user back where they came from.\n expHistory::back();\n\t}", "label": 1, "label_name": "safe"} -{"code": " public function test_convertToASCIIDumbLossless()\n {\n // Uppercase thorn letter\n $this->assertIdentical(\n HTMLPurifier_Encoder::convertToASCIIDumbLossless(\"\\xC3\\x9Eorn\"),\n \"Þorn\"\n );\n\n $this->assertIdentical(\n HTMLPurifier_Encoder::convertToASCIIDumbLossless(\"an\"),\n \"an\"\n );\n\n // test up to four bytes\n $this->assertIdentical(\n HTMLPurifier_Encoder::convertToASCIIDumbLossless(\"\\xF3\\xA0\\x80\\xA0\"),\n \"󠀠\"\n );\n\n }", "label": 1, "label_name": "safe"} -{"code": "snmp_api_set_time_ticks(snmp_varbind_t *varbind, uint32_t *oid, uint32_t integer)\n{\n\n snmp_api_replace_oid(varbind, oid);\n varbind->value_type = SNMP_DATA_TYPE_TIME_TICKS;\n varbind->value.integer = integer;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function(){b.spinner.stop();if(null==b.linkPicker){var n=b.drive.createLinkPicker();b.linkPicker=n.setCallback(function(y){LinkDialog.filePicked(y)}).build()}b.linkPicker.setVisible(!0)}))});\"undefined\"!=typeof Dropbox&&\"undefined\"!=typeof Dropbox.choose&&c(IMAGE_PATH+\"/dropbox-logo.svg\",mxResources.get(\"dropbox\"),function(){Dropbox.choose({linkType:\"direct\",cancel:function(){},success:function(n){k.value=n[0].link;k.focus()}})});null!=b.oneDrive&&c(IMAGE_PATH+\"/onedrive-logo.svg\",mxResources.get(\"oneDrive\"),", "label": 0, "label_name": "vulnerable"} -{"code": " public function mergeIn($def) {\n\n // later keys takes precedence\n foreach($def->attr as $k => $v) {\n if ($k === 0) {\n // merge in the includes\n // sorry, no way to override an include\n foreach ($v as $v2) {\n $this->attr[0][] = $v2;\n }\n continue;\n }\n if ($v === false) {\n if (isset($this->attr[$k])) unset($this->attr[$k]);\n continue;\n }\n $this->attr[$k] = $v;\n }\n $this->_mergeAssocArray($this->excludes, $def->excludes);\n $this->attr_transform_pre = array_merge($this->attr_transform_pre, $def->attr_transform_pre);\n $this->attr_transform_post = array_merge($this->attr_transform_post, $def->attr_transform_post);\n\n if(!empty($def->content_model)) {\n $this->content_model =\n str_replace(\"#SUPER\", $this->content_model, $def->content_model);\n $this->child = false;\n }\n if(!empty($def->content_model_type)) {\n $this->content_model_type = $def->content_model_type;\n $this->child = false;\n }\n if(!is_null($def->child)) $this->child = $def->child;\n if(!is_null($def->formatting)) $this->formatting = $def->formatting;\n if($def->descendants_are_inline) $this->descendants_are_inline = $def->descendants_are_inline;\n\n }", "label": 1, "label_name": "safe"} -{"code": "\t\tfunction updateProfile($data) {\n\t\t\tglobal $bigtree;\n\n\t\t\tforeach ($data as $key => $val) {\n\t\t\t\tif (substr($key,0,1) != \"_\" && !is_array($val)) {\n\t\t\t\t\t$$key = sqlescape($val);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$id = sqlescape($this->ID);\n\n\t\t\tif ($data[\"password\"]) {\n\t\t\t\t$phpass = new PasswordHash($bigtree[\"config\"][\"password_depth\"], TRUE);\n\t\t\t\t$password = sqlescape($phpass->HashPassword($data[\"password\"]));\n\t\t\t\tsqlquery(\"UPDATE bigtree_users SET `password` = '$password', `name` = '$name', `company` = '$company', `daily_digest` = '$daily_digest' WHERE id = '$id'\");\n\t\t\t} else {\n\t\t\t\tsqlquery(\"UPDATE bigtree_users SET `name` = '$name', `company` = '$company', `daily_digest` = '$daily_digest' WHERE id = '$id'\");\n\t\t\t}\n\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": " function _log($url, $msg) {\n if ($this->_debug) {\n $data = sprintf(\"[%s] [%s] %s\\n\", date('r'), $url, $msg);\n $data = strtr($data, '<>', '..');\n\n $filename = w3_debug_log('varnish');\n\n return @file_put_contents($filename, $data, FILE_APPEND);\n }\n\n return true;\n }", "label": 1, "label_name": "safe"} -{"code": " $period_days_append_sql= substr($period_days_append_sql,0,-4).'))';\n }\n \n $exist_RET= DBGet(DBQuery(\"SELECT s.ID FROM schedule s WHERE student_id=\". $student_id.\" AND s.syear='\".UserSyear().\"' {$mp_append_sql}{$period_days_append_sql} UNION SELECT s.ID FROM temp_schedule s WHERE student_id=\". $student_id.\"{$mp_append_sql}{$period_days_append_sql}\"));\n if($exist_RET)\n return 'There is a Period Conflict ('.$course_RET[1]['CP_TITLE'].')';\n else\n {\n return true;\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " $link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));", "label": 1, "label_name": "safe"} -{"code": " it { is_expected.to contain_class(\"apache::params\") }", "label": 0, "label_name": "vulnerable"} -{"code": " $object->size = convert_size($cur->getSize());\n $object->mtime = date('D, j M, Y', $cur->getMTime());\n list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());\n \n // Find the file type\n $object->type = $this->_getFileType($cur);\n\n // make the link depending on if it's a file or a dir\n if ($cur->isDir()) {\n $object->link = 'path . $object->name) . '\">' . $object->name . '';\n } else {\n $object->link = 'path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '\">' . $object->name . '';\n }\n\n $files[$object->name] = $object;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static function sanitizeGetParams () {\n //sanitize get params\n $whitelist = array(\n 'fg', 'bgc', 'font', 'bs', 'bc', 'iframeHeight'\n );\n $_GET = array_intersect_key($_GET, array_flip($whitelist));\n //restrict param values, alphanumeric, # for color vals, comma for tag list, . for decimals\n $_GET = preg_replace('/[^a-zA-Z0-9#,.]/', '', $_GET);\n return $_GET;\n }", "label": 1, "label_name": "safe"} -{"code": " def makeTrustRoot(self):\n # If this option is specified, use a specific root CA cert. This is useful for testing when it's not\n # practical to get the client cert signed by a real root CA but should never be used on a production server.\n caCertFilename = self.sydent.cfg.get('http', 'replication.https.cacert')\n if len(caCertFilename) > 0:\n try:\n fp = open(caCertFilename)\n caCert = twisted.internet.ssl.Certificate.loadPEM(fp.read())\n fp.close()\n except Exception:\n logger.warn(\"Failed to open CA cert file %s\", caCertFilename)\n raise\n logger.warn(\"Using custom CA cert file: %s\", caCertFilename)\n return twisted.internet._sslverify.OpenSSLCertificateAuthorities([caCert.original])\n else:\n return twisted.internet.ssl.OpenSSLDefaultPaths()", "label": 1, "label_name": "safe"} -{"code": " public function generateMessageFileName()\n {\n $time = microtime(true);\n\n return date('Ymd-His-', $time) . sprintf('%04d', (int) (($time - (int) $time) * 10000)) . '-' . sprintf('%04d', random_int(0, 10000)) . '.eml';\n }", "label": 1, "label_name": "safe"} -{"code": "rdpsnd_process_training(STREAM in)\n{\n\tuint16 tick;\n\tuint16 packsize;\n\tSTREAM out;\n\tstruct stream packet = *in;\n\n\tif (!s_check_rem(in, 4))\n\t{\n\t\trdp_protocol_error(\"rdpsnd_process_training(), consume of training data from stream would overrun\", &packet);\n\t}\n\n\tin_uint16_le(in, tick);\n\tin_uint16_le(in, packsize);\n\n\tlogger(Sound, Debug, \"rdpsnd_process_training(), tick=0x%04x\", (unsigned) tick);\n\n\tout = rdpsnd_init_packet(SNDC_TRAINING, 4);\n\tout_uint16_le(out, tick);\n\tout_uint16_le(out, packsize);\n\ts_mark_end(out);\n\trdpsnd_send(out);\n}", "label": 1, "label_name": "safe"} -{"code": "function(b,c){b=typeof c;\"function\"==b?c=mxStyleRegistry.getName(c):\"object\"==b&&(c=null);return c};a.decode=function(b,c,d){d=d||new this.template.constructor;var e=c.getAttribute(\"id\");null!=e&&(b.objects[e]=d);for(c=c.firstChild;null!=c;){if(!this.processInclude(b,c,d)&&\"add\"==c.nodeName&&(e=c.getAttribute(\"as\"),null!=e)){var f=c.getAttribute(\"extend\"),g=null!=f?mxUtils.clone(d.styles[f]):null;null==g&&(null!=f&&mxLog.warn(\"mxStylesheetCodec.decode: stylesheet \"+f+\" not found to extend\"),g={});\nfor(f=c.firstChild;null!=f;){if(f.nodeType==mxConstants.NODETYPE_ELEMENT){var k=f.getAttribute(\"as\");if(\"add\"==f.nodeName){var l=mxUtils.getTextContent(f);null!=l&&0(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, "label_name": "vulnerable"} -{"code": " private func increaseSecurityLevelIfNeeded(for cause: SecurityChangeCause) {\n guard\n securityLevel != .secure &&\n allUsersTrusted &&\n allParticipantsHaveClients &&\n conversationType.isOne(of: .group, .oneOnOne, .invalid)\n else {\n return\n }\n\n securityLevel = .secure\n appendNewIsSecureSystemMessage(cause: cause)\n notifyOnUI(name: ZMConversation.isVerifiedNotificationName)\n }", "label": 1, "label_name": "safe"} -{"code": " public String toString() {\n return Hex.encode(prefix);\n }", "label": 1, "label_name": "safe"} -{"code": "\"geCommentActionLnk\";mxUtils.write(ba,N);Y.appendChild(ba);mxEvent.addListener(ba,\"click\",function(ea){Q(ea,K);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;\n\t}\n\tif (val) {\n\t\t*val = v;\n\t}\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": "void handle_debug_usb_rx(const void *msg, size_t len)\n{\n if (msg_tiny_flag) {\n msg_read_tiny(msg, len);\n } else {\n usb_rx_helper(msg, len, DEBUG_MSG);\n }\n}", "label": 1, "label_name": "safe"} -{"code": " protected TablesGeneratorBase(DatabaseSchema schema)\r\n {\r\n Schema = schema;\r\n IncludeSchema = true;\r\n EscapeNames = true;\r\n }\r", "label": 1, "label_name": "safe"} -{"code": "(k?\"\":Graph.xmlDeclaration+\"\\n\"+Graph.svgFileComment+\"\\n\"+Graph.svgDoctype+\"\\n\")+mxUtils.getXml(K);null!=m&&m(K);return K});e.mathEnabled&&this.editor.addMathCss(q);if(null!=m)this.embedFonts(q,mxUtils.bind(this,function(K){x?this.editor.convertImages(K,mxUtils.bind(this,function(B){y(B)})):y(K)}));else return y(q)};EditorUi.prototype.embedFonts=function(c,e){this.editor.loadFonts(mxUtils.bind(this,function(){try{null!=this.editor.resolvedFontCss&&this.editor.addFontCss(c,this.editor.resolvedFontCss),\nthis.editor.embedExtFonts(mxUtils.bind(this,function(g){try{null!=g&&this.editor.addFontCss(c,g),e(c)}catch(k){e(c)}}))}catch(g){e(c)}}))};EditorUi.prototype.exportImage=function(c,e,g,k,m,q,v,x,A,z,L,M,n){A=null!=A?A:\"png\";if(this.spinner.spin(document.body,mxResources.get(\"exporting\"))){var y=this.editor.graph.isSelectionEmpty();g=null!=g?g:y;null==this.thumbImageCache&&(this.thumbImageCache={});try{this.editor.exportToCanvas(mxUtils.bind(this,function(K){this.spinner.stop();try{this.saveCanvas(K,", "label": 0, "label_name": "vulnerable"} -{"code": " it 'does not log in the user if they were not activated' do\n put \"/invites/show/#{invite.invite_key}.json\", params: { password: SecureRandom.hex }\n\n expect(session[:current_user_id]).to eq(nil)\n expect(response.parsed_body[\"message\"]).to eq(I18n.t('invite.confirm_email'))\n end", "label": 1, "label_name": "safe"} -{"code": " Tooltip.prototype.hide = function (callback) {\n var that = this\n var $tip = $(this.$tip)\n var e = $.Event('hide.bs.' + this.type)\n\n 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 }\n\n this.$element.trigger(e)\n\n if (e.isDefaultPrevented()) return\n\n $tip.removeClass('in')\n\n $.support.transition && $tip.hasClass('fade') ?\n $tip\n .one('bsTransitionEnd', complete)\n .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :\n complete()\n\n this.hoverState = null\n\n return this\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public void translate(GeyserSession session, ServerAdvancementTabPacket packet) {\n AdvancementsCache advancementsCache = session.getAdvancementsCache();\n advancementsCache.setCurrentAdvancementCategoryId(packet.getTabId());\n advancementsCache.buildAndShowListForm();\n }", "label": 1, "label_name": "safe"} -{"code": " render() {},", "label": 0, "label_name": "vulnerable"} -{"code": " public function testExtension()\n {\n $container = new ContainerBuilder();\n $container->setResourceTracking(false);\n\n $container->registerExtension($extension = new \\ProjectExtension());\n $this->assertTrue($container->getExtension('project') === $extension, '->registerExtension() registers an extension');\n\n $this->setExpectedException('LogicException');\n $container->getExtension('no_registered');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_logout_user_is_logged_in() {\n $_REQUEST['nonce'] = yourls_create_nonce('admin_login');\n $valid = yourls_is_valid_user();\n $this->assertTrue($valid);\n $this->assertSame(self::$user, 'yourls');\n }", "label": 1, "label_name": "safe"} -{"code": " function edit_externalalias() {\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\n if ($section->parent == -1) {\n notfoundController::handle_not_found();\n exit;\n } // doesn't work for standalone pages\n if (empty($section->id)) {\n $section->public = 1;\n if (!isset($section->parent)) {\n // This is another precaution. The parent attribute\n // should ALWAYS be set by the caller.\n //FJD - if that's the case, then we should die.\n notfoundController::handle_not_authorized();\n exit;\n //$section->parent = 0;\n }\n }\n assign_to_template(array(\n 'section' => $section,\n 'glyphs' => self::get_glyphs(),\n ));\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct(ClonerInterface $cloner, DataDumperInterface $dumper)\n {\n $this->cloner = $cloner;\n $this->dumper = $dumper;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tprotected function getRootStatExtra() {\n\t\t$stat = array();\n\t\tif ($this->rootName) {\n\t\t\t$stat['name'] = $this->rootName;\n\t\t}\n\t\t$stat['options'] = $this->options(null);\n\t\treturn $stat;\n\t}", "label": 1, "label_name": "safe"} -{"code": " public function countErrors()\n {\n return count($this->logs['critical']);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tprotected function _add_log_attachment( $action, $attachment_id ) {\n\t\t$post = get_post( $attachment_id );\n\n\t\taal_insert_log( array(\n\t\t\t'action' => $action,\n\t\t\t'object_type' => 'Attachment',\n\t\t\t'object_subtype' => $post->post_type,\n\t\t\t'object_id' => $attachment_id,\n\t\t\t'object_name' => get_the_title( $post->ID ),\n\t\t) );\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def destroy\n FileUtils.rm_rf(@resource.value(:path))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct(ProfilerStorageInterface $storage, LoggerInterface $logger = null)\n {\n $this->storage = $storage;\n $this->logger = $logger;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tprotected SymbolContext getContextLegacy() {\n\t\tthrow new UnsupportedOperationException();\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testUnstartedSessionIsNotSave()\n {\n $this->sessionHasNotBeenStarted();\n $this->sessionMustNotBeSaved();\n\n $this->filterResponse(new Request());\n }", "label": 0, "label_name": "vulnerable"} -{"code": "l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {\n CallInfo *ci = L->ci;\n const char *msg;\n va_list argp;\n luaC_checkGC(L); /* error message uses memory */\n va_start(argp, fmt);\n msg = luaO_pushvfstring(L, fmt, argp); /* format message */\n va_end(argp);\n if (isLua(ci)) /* if Lua function, add source:line information */\n luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));\n luaG_errormsg(L);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static int ceph_x_decrypt(struct ceph_crypto_key *secret,\n\t\t\t void **p, void *end, void *obuf, size_t olen)\n{\n\tstruct ceph_x_encrypt_header head;\n\tsize_t head_len = sizeof(head);\n\tint len, ret;\n\n\tlen = ceph_decode_32(p);\n\tif (*p + len > end)\n\t\treturn -EINVAL;\n\n\tdout(\"ceph_x_decrypt len %d\\n\", len);\n\tret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,\n\t\t\t *p, len);\n\tif (ret)\n\t\treturn ret;\n\tif (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)\n\t\treturn -EPERM;\n\t*p += len;\n\treturn olen;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def _has_sneaky_javascript(self, style):\n \"\"\"\n Depending on the browser, stuff like ``e x p r e s s i o n(...)``\n can get interpreted, or ``expre/* stuff */ssion(...)``. This\n checks for attempt to do stuff like this.\n\n Typically the response will be to kill the entire style; if you\n have just a bit of Javascript in the style another rule will catch\n that and remove only the Javascript from the style; this catches\n more sneaky attempts.\n \"\"\"\n style = self._substitute_comments('', style)\n style = style.replace('\\\\', '')\n style = _substitute_whitespace('', style)\n style = style.lower()\n if 'javascript:' in style:\n return True\n if 'expression(' in style:\n return True\n if '@import' in style:\n return True\n if ''\n return True\n return False", "label": 1, "label_name": "safe"} -{"code": "f.setCellStyles(mxConstants.STYLE_ROTATION,Number(I.value),[e[t]])}}finally{f.getModel().endUpdate()}});O.className=\"geBtn gePrimaryBtn\";mxEvent.addListener(m,\"keypress\",function(t){13==t.keyCode&&O.click()});n=document.createElement(\"div\");n.style.marginTop=\"20px\";n.style.textAlign=\"right\";b.editor.cancelFirst?(n.appendChild(c),n.appendChild(O)):(n.appendChild(O),n.appendChild(c));m.appendChild(n);this.container=m},LibraryDialog=function(b,e,f,c,m,n){function v(E){for(E=document.elementFromPoint(E.clientX,", "label": 1, "label_name": "safe"} -{"code": "ast_dealloc(AST_object *self)\n{\n /* bpo-31095: UnTrack is needed before calling any callbacks */\n PyObject_GC_UnTrack(self);\n Py_CLEAR(self->dict);\n Py_TYPE(self)->tp_free(self);\n}", "label": 1, "label_name": "safe"} -{"code": "setTimeout(function(){Ia.style.display=\"none\"},4E3)}function z(){null!=X&&(X.style.fontWeight=\"normal\",X.style.textDecoration=\"none\",p=X,X=null)}function L(fa,ca,ba,ja,ia,ma,qa){if(-18)&&e)a=e+\":\"+a;return new CKEDITOR.dom.nodeList(this.$.getElementsByTagName(a))},getHead:function(){var a=this.$.getElementsByTagName(\"head\")[0];return a=", "label": 1, "label_name": "safe"} -{"code": " def test_list_email_content_error(self, task_history_request):\n \"\"\" Test handling of error retrieving email \"\"\"\n invalid_task = FakeContentTask(0, 0, 0, 'test')\n invalid_task.make_invalid_input()\n task_history_request.return_value = [invalid_task]\n url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.post(url, {})\n self.assertEqual(response.status_code, 200)\n\n self.assertTrue(task_history_request.called)\n returned_email_info = json.loads(response.content)['emails']\n self.assertEqual(len(returned_email_info), 1)\n returned_info = returned_email_info[0]\n for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']:\n self.assertEqual(returned_info[info], None)", "label": 1, "label_name": "safe"} -{"code": " onHandshakeComplete: (negotiated) => {\n this.emit('handshake', negotiated);\n if (!ready) {\n ready = true;\n proto.service('ssh-userauth');\n }\n },", "label": 1, "label_name": "safe"} -{"code": " QUInt16() {}", "label": 0, "label_name": "vulnerable"} -{"code": "OAuthServer.prototype.validateAccessToken = function (username, accessToken) {\n if (!this.users[username] || this.users[username].accessToken !== accessToken || this.users[username].expiresIn < Date.now()) {\n return false;\n } else {\n return true;\n }\n};", "label": 1, "label_name": "safe"} -{"code": " function getCryptType()\n {\n return($this->options['cryptType']);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function assertDecode($string, $expect = true)\n {\n if ($expect === true) $expect = $string;\n $this->assertIdentical($this->PercentEncoder->{$this->func}($string), $expect);\n }", "label": 1, "label_name": "safe"} -{"code": "exports.set = function(obj, path, value) {\n\tvar cachekey = 'S+' + path;\n\n\tif (F.temporary.other[cachekey])\n\t\treturn F.temporary.other[cachekey](obj, value);\n\n\tvar arr = parsepath(path);\n\tvar builder = [];\n\n\tfor (var i = 0; i < arr.length - 1; i++) {\n\t\tvar type = arr[i + 1] ? (REGISARR.test(arr[i + 1]) ? '[]' : '{}') : '{}';\n\t\tvar p = 'w' + (arr[i][0] === '[' ? '' : '.') + arr[i];\n\t\tbuilder.push('if(typeof(' + p + ')!==\\'object\\'||' + p + '==null)' + p + '=' + type + ';');\n\t}\n\n\tvar v = arr[arr.length - 1];\n\tvar ispush = v.lastIndexOf('[]') !== -1;\n\tvar a = builder.join(';') + ';var v=typeof(a)===\\'function\\'?a(U.get(b)):a;w' + (v[0] === '[' ? '' : '.') + (ispush ? v.replace(REGREPLACEARR, '.push(v)') : (v + '=v')) + ';return v';\n\n\tif ((/__proto__|constructor|prototype/).test(a))\n\t\tthrow new Error('Prototype pollution');\n\n\tvar fn = new Function('w', 'a', 'b', a);\n\tF.temporary.other[cachekey] = fn;\n\tfn(obj, value, path);\n};", "label": 0, "label_name": "vulnerable"} -{"code": "function db_case($array)\n{\n global $DatabaseType;\n\n $counter = 0;\n if ($DatabaseType == 'mysqli') {\n $array_count = count($array);\n $string = \" CASE WHEN $array[0] =\";\n $counter++;\n $arr_count = count($array);\n for ($i = 1; $i < $arr_count; $i++) {\n $value = $array[$i];\n\n if ($value == \"''\" && substr($string, -1) == '=') {\n $value = ' IS NULL';\n $string = substr($string, 0, -1);\n }\n\n $string .= \"$value\";\n if ($counter == ($array_count - 2) && $array_count % 2 == 0)\n $string .= \" ELSE \";\n elseif ($counter == ($array_count - 1))\n $string .= \" END \";\n elseif ($counter % 2 == 0)\n $string .= \" WHEN $array[0]=\";\n elseif ($counter % 2 == 1)\n $string .= \" THEN \";\n\n $counter++;\n }\n }\n return $string;\n}", "label": 0, "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, "label_name": "vulnerable"} -{"code": " protected function renderImageByImagick($code)\n {\n $backColor = $this->transparent ? new \\ImagickPixel('transparent') : new \\ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));\n $foreColor = new \\ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));\n\n $image = new \\Imagick();\n $image->newImage($this->width, $this->height, $backColor);\n\n $draw = new \\ImagickDraw();\n $draw->setFont($this->fontFile);\n $draw->setFontSize(30);\n $fontMetrics = $image->queryFontMetrics($draw, $code);\n\n $length = strlen($code);\n $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);\n $h = (int) $fontMetrics['textHeight'] - 8;\n $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);\n $x = 10;\n $y = round($this->height * 27 / 40);\n for ($i = 0; $i < $length; ++$i) {\n $draw = new \\ImagickDraw();\n $draw->setFont($this->fontFile);\n $draw->setFontSize((int) (random_int(26, 32) * $scale * 0.8));\n $draw->setFillColor($foreColor);\n $image->annotateImage($draw, $x, $y, random_int(-10, 10), $code[$i]);\n $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);\n $x += (int) $fontMetrics['textWidth'] + $this->offset;\n }\n\n $image->setImageFormat('png');\n return $image->getImageBlob();\n }", "label": 1, "label_name": "safe"} -{"code": "TEST_F(AsStringGraphTest, String) {\n Status s = Init(DT_STRING);\n ASSERT_EQ(error::INVALID_ARGUMENT, s.code());\n ASSERT_TRUE(absl::StrContains(\n s.error_message(),\n \"Value for attr 'T' of string is not in the list of allowed values\"));\n}", "label": 1, "label_name": "safe"} -{"code": " public function transform($attr, $config, $context)\n {\n if (!isset($attr['type'])) {\n $attr['type'] = 'application/x-shockwave-flash';\n }\n return $attr;\n }", "label": 1, "label_name": "safe"} -{"code": "typeof fa.getAttribute&&null!=fa.getAttribute(\"title\")&&sa.push({img:fa.getAttribute(\"img\"),libs:fa.getAttribute(\"libs\"),clibs:fa.getAttribute(\"clibs\"),title:fa.getAttribute(\"title\")}),fa=fa.nextSibling;F(sa)}});var ra=function(fa,ca,ba){la.style.display=\"\";Ea.stop();W=!1;if(V)V=!1;else if(ca)aa.innerHTML=ca;else{ba=ba||{};ca=0;for(var ja in ba)ca+=ba[ja].length;0==fa.length&&0==ca?aa.innerHTML=mxUtils.htmlEntities(mxResources.get(\"noDiagrams\")):B(fa,!1,O,0==ca?null:ba)}};J(P);var xa=null;mxEvent.addListener(Oa,", "label": 1, "label_name": "safe"} -{"code": "var get = module.exports.get = function get(object, path) {\n if (typeof path === \"string\") {\n path = path.split(\".\");\n }\n\n if (!(path instanceof Array) || path.length === 0) {\n return;\n }\n\n path = path.slice();\n\n var key = path.shift();\n\n if (typeof object !== \"object\" || object === null) {\n return;\n }\n\n if (path.length === 0) {\n return object[key];\n }\n\n if (path.length) {\n return get(object[key], path);\n }\n};", "label": 0, "label_name": "vulnerable"} -{"code": " def extract_tar_gz io, destination_dir, pattern = \"*\" # :nodoc:\n open_tar_gz io do |tar|\n tar.each do |entry|\n next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH\n\n destination = install_location entry.full_name, destination_dir\n\n FileUtils.rm_rf destination\n\n mkdir_options = {}\n mkdir_options[:mode] = entry.header.mode if entry.directory?\n mkdir =\n if entry.directory? then\n destination\n else\n File.dirname destination\n end\n\n FileUtils.mkdir_p mkdir, mkdir_options\n\n File.open destination, 'wb' do |out|\n out.write entry.read\n FileUtils.chmod entry.header.mode, destination\n end if entry.file?\n\n File.symlink(entry.header.linkname, destination) if entry.symlink?\n\n verbose destination\n end\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " $this->inCaption(array(\n 'name' => 'caption',\n 'type' => HTML5::ENDTAG\n ));\n\n return $this->inTable($token);\n\n /* An end tag whose tag name is one of: \"body\", \"col\", \"colgroup\",\n \"html\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\" */\n } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],", "label": 1, "label_name": "safe"} -{"code": "\tpublic void fireUndeployEvent(HotDeployEvent hotDeployEvent) {\n\t\tfor (HotDeployListener hotDeployListener : _hotDeployListeners) {\n\t\t\ttry {\n\t\t\t\thotDeployListener.invokeUndeploy(hotDeployEvent);\n\t\t\t}\n\t\t\tcatch (HotDeployException hde) {\n\t\t\t\t_log.error(hde, hde);\n\t\t\t}\n\t\t}\n\n\t\t_deployedServletContextNames.remove(\n\t\t\thotDeployEvent.getServletContextName());\n\n\t\tClassLoader classLoader = hotDeployEvent.getContextClassLoader();\n\n\t\tTemplateManagerUtil.destroy(classLoader);\n\n\t\tPACLPolicyManager.unregister(classLoader);\n\t}", "label": 1, "label_name": "safe"} -{"code": "static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo,\n size_t offset)\n{\n\tsize_t position;\n\tWINPR_UNUSED(context);\n\tposition = Stream_GetPosition(s);\n\tStream_SetPosition(s, offset);\n\tStream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */\n\n\tif (orderInfo->controlFlags & ORDER_TYPE_CHANGE)\n\t\tStream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */\n\n\tupdate_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags,\n\t PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]);\n\tupdate_write_bounds(s, orderInfo);\n\tStream_SetPosition(s, position);\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName(expString::escape($this->params['coupon_code']));\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }", "label": 1, "label_name": "safe"} -{"code": " it \"yields all indexes on the collection\" do\n indexes.to_a.should eq \\\n session[:\"system.indexes\"].find(ns: \"moped_test.users\").to_a\n end", "label": 0, "label_name": "vulnerable"} -{"code": "Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& publicShares, int t, int n) {\n spdlog::info(\"Entering {}\", __FUNCTION__);\n INIT_RESULT(result)\n\n try {\n if (!check_n_t(t, n)) {\n throw SGXException(INVALID_DKG_PARAMS, \"Invalid DKG parameters: n or t \");\n }\n\n if (!publicShares.isArray()) {\n throw SGXException(INVALID_DKG_PARAMS, \"Invalid public shares format\");\n }\n\n if (publicShares.size() != (uint64_t) n) {\n throw SGXException(INVALID_DKG_PARAMS, \"Invalid length of public shares\");\n }\n\n for (int i = 0; i < n; ++i) {\n if (!publicShares[i].isString()) {\n throw SGXException(INVALID_DKG_PARAMS, \"Invalid public shares parts format\");\n }\n\n if (publicShares[i].asString().length() != (uint64_t) 256 * t) {\n throw SGXException(INVALID_DKG_PARAMS, \"Invalid length of public shares parts\");\n }\n }\n\n vector public_shares(n);\n for (int i = 0; i < n; ++i) {\n public_shares[i] = publicShares[i].asString();\n }\n\n vector public_keys = calculateAllBlsPublicKeys(public_shares);\n\n if (public_keys.size() != (uint64_t)n) {\n throw SGXException(UNKNOWN_ERROR, \"\");\n }\n\n for (int i = 0; i < n; ++i) {\n result[\"publicKeys\"][i] = public_keys[i];\n }\n } HANDLE_SGX_EXCEPTION(result)\n\n RETURN_SUCCESS(result);\n}", "label": 1, "label_name": "safe"} -{"code": "function validateNodeName($name, &$errmsg) {\n\tif(preg_match('/^[-A-Za-z0-9_\\. ]+$/', $name))\n\t\treturn 1;\n\t$errmsg = _(\"Node names can only contain letters, numbers, spaces,
dashes(-), dots(.), and underscores(_).\");\n\treturn 0;\n}", "label": 1, "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]=", "label": 1, "label_name": "safe"} -{"code": "EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createSvgDataUri\");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedCssFonts\");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedExtFonts\");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,y,A,z,L,M,n,x,K,B){EditorUi.logEvent(\"SHOULD NOT BE CALLED: exportToCanvas\");\nreturn this.editor.exportToCanvas(c,e,g,k,m,q,v,y,A,z,L,M,n,x,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createImageUrlConverter\");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImages\");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImageToDataUri\");", "label": 1, "label_name": "safe"} -{"code": "Jsi_RC Jsi_RegExpMatch(Jsi_Interp *interp, Jsi_Value *pattern, const char *v, int *rc, Jsi_DString *dStr)\n{\n Jsi_Regex *re;\n int regexec_flags = 0;\n if (rc)\n *rc = 0;\n if (pattern == NULL || pattern->vt != JSI_VT_OBJECT || pattern->d.obj->ot != JSI_OT_REGEXP) \n return Jsi_LogError(\"expected pattern\");\n re = pattern->d.obj->d.robj;\n regex_t *reg = &re->reg;\n \n regmatch_t pos = {};\n if (dStr)\n Jsi_DSInit(dStr);\n \n int r = regexec(reg, v, 1, &pos, regexec_flags);\n\n if (r >= REG_BADPAT) {\n char buf[JSI_MAX_NUMBER_STRING];\n\n regerror(r, reg, buf, sizeof(buf));\n return Jsi_LogError(\"error while matching pattern: %s\", buf);\n }\n if (r != REG_NOMATCH) {\n if (rc) *rc = 1;\n if (dStr && pos.rm_so >= 0 && pos.rm_eo >= 0 && pos.rm_eo >= pos.rm_so)\n Jsi_DSAppendLen(dStr, v + pos.rm_so, pos.rm_eo - pos.rm_so);\n }\n \n return JSI_OK;\n}", "label": 1, "label_name": "safe"} -{"code": "\"top center\";da.style.backgroundRepeat=\"no-repeat\";da.setAttribute(\"title\",\"Minimize\");var fa=!1,ma=mxUtils.bind(this,function(){S.innerText=\"\";if(!fa){var aa=function(la,oa,ra){la=B(\"\",la.funct,null,oa,la,ra);la.style.width=\"40px\";la.style.opacity=\"0.7\";return ca(la,null,\"pointer\")},ca=function(la,oa,ra){null!=oa&&la.setAttribute(\"title\",oa);la.style.cursor=null!=ra?ra:\"default\";la.style.margin=\"2px 0px\";S.appendChild(la);mxUtils.br(S);return la};ca(F.sidebar.createVertexTemplate(\"text;strokeColor=none;fillColor=none;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\",", "label": 1, "label_name": "safe"} -{"code": "crm_send_remote_msg(void *session, xmlNode * msg, gboolean encrypted)\n{\n if (encrypted) {\n#ifdef HAVE_GNUTLS_GNUTLS_H\n cib_send_tls(session, msg);\n#else\n CRM_ASSERT(encrypted == FALSE);\n#endif\n } else {\n cib_send_plaintext(GPOINTER_TO_INT(session), msg);\n }\n}", "label": 0, "label_name": "vulnerable"} -{"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 $log.log('[trudesk:profile:updateUser] - ' + e.error.message)\n helpers.UI.showSnackbar('Error ' + e.error.message, true)\n })\n }", "label": 1, "label_name": "safe"} -{"code": " def limited?\n @limited\n end", "label": 1, "label_name": "safe"} -{"code": " } elseif($params[$pseud] != $params[$key]){\n // Throw error about multiple params (and if they are different) #15204\n throw new CHttpException(403, sprintf(gT(\"Invalid parameter %s (%s already set)\"),$pseud,$key));\n }", "label": 1, "label_name": "safe"} -{"code": " function send_feedback() {\r\n $success = false;\r\n if (isset($this->params['id'])) {\r\n $ed = new eventdate($this->params['id']);\r\n// $email_addrs = array();\r\n if ($ed->event->feedback_email != '') {\r\n $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);\r\n $msgtemplate->assign('params', $this->params);\r\n $msgtemplate->assign('event', $ed);\r\n $email_addrs = explode(',', $ed->event->feedback_email);\r\n //This is an easy way to remove duplicates\r\n $email_addrs = array_flip(array_flip($email_addrs));\r\n $email_addrs = array_map('trim', $email_addrs);\r\n $mail = new expMail();\r\n $success += $mail->quickSend(array(\r\n \"text_message\" => $msgtemplate->render(),\r\n 'to' => $email_addrs,\r\n 'from' => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),\r\n 'subject' => $this->params['subject'],\r\n ));\r\n }\r\n }\r\n\r\n if ($success) {\r\n flashAndFlow('message', gt('Your feedback was successfully sent.'));\r\n } else {\r\n flashAndFlow('error', gt('We could not send your feedback. Please contact your administrator.'));\r\n }\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " it 'should accept empty hashes' do\n scope.function_mysql_deepmerge([{},{},{}]).should == {}\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic static ResourceEvaluation evaluate(File file, String filename) {\n\t\tResourceEvaluation eval = new ResourceEvaluation();\n\t\ttry {\n\t\t\tImsManifestFileFilter visitor = new ImsManifestFileFilter();\n\t\t\tPath fPath = PathUtils.visit(file, filename, visitor);\n\t\t\tif(visitor.hasManifest()) {\n\t\t\t\tPath realManifestPath = visitor.getManifestPath();\n\t\t\t\tPath manifestPath = fPath.resolve(realManifestPath);\n\t\t\t\t\n\t\t\t\tRootSearcher rootSearcher = new RootSearcher();\n\t\t\t\tFiles.walkFileTree(fPath, EnumSet.noneOf(FileVisitOption.class), 16, rootSearcher);\n\t\t\t\tif(rootSearcher.foundRoot()) {\n\t\t\t\t\tmanifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);\n\t\t\t\t} else {\n\t\t\t\t\tmanifestPath = fPath.resolve(IMS_MANIFEST);\n\t\t\t\t}\n\n\t\t\t\tDocument doc = IMSLoader.loadIMSDocument(manifestPath);\n\t\t\t\tif(validateImsManifest(doc)) {\n\t\t\t\t\tif(visitor.hasEditorTreeModel()) {\n\t\t\t\t\t\tXMLScanner scanner = new XMLScanner();\n\t\t\t\t\t\tscanner.scan(visitor.getEditorTreeModelPath());\n\t\t\t\t\t\teval.setValid(!scanner.hasEditorTreeModelMarkup());\t\n\t\t\t\t\t} else {\n\t\t\t\t\t\teval.setValid(true);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\teval.setValid(false);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\teval.setValid(false);\n\t\t\t}\n\t\t\tPathUtils.closeSubsequentFS(fPath);\n\t\t} catch (IOException | IllegalArgumentException e) {\n\t\t\tlog.error(\"\", e);\n\t\t\teval.setValid(false);\n\t\t}\n\t\treturn eval;\n\t}", "label": 1, "label_name": "safe"} -{"code": " ReservedChar(int rawChar, String percentEncodedChar, byte marker) {\n this.rawChar = rawChar;\n this.percentEncodedChar = percentEncodedChar;\n this.marker = marker;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_convertFromUTF8_utf8()\n {\n // UTF-8 means that we don't touch it\n $this->assertIdentical(\n HTMLPurifier_Encoder::convertFromUTF8(\"\\xC3\\xB6\", $this->config, $this->context),\n \"\\xC3\\xB6\"\n );\n }", "label": 1, "label_name": "safe"} -{"code": "exports.map = function(arr, fn, scope){\n var result = [];\n for (var i = 0, l = arr.length; i < l; i++)\n result.push(fn.call(scope, arr[i], i));\n return result;\n};", "label": 0, "label_name": "vulnerable"} -{"code": " it \"drops a collection\" do\n session.command(count: :people)[\"n\"].should eq 0\n session[:people].insert(name: \"John\")\n session.command(count: :people)[\"n\"].should eq 1\n session[:people].drop\n session.command(count: :people)[\"n\"].should eq 0\n end", "label": 0, "label_name": "vulnerable"} -{"code": "error_t httpClientSetUri(HttpClientContext *context, const char_t *uri)\n{\n size_t m;\n size_t n;\n char_t *p;\n char_t *q;\n\n //Check parameters\n if(context == NULL || uri == NULL)\n return ERROR_INVALID_PARAMETER;\n\n //The resource name must not be empty\n if(uri[0] == '\\0')\n return ERROR_INVALID_PARAMETER;\n\n //Check HTTP request state\n if(context->requestState != HTTP_REQ_STATE_FORMAT_HEADER)\n return ERROR_WRONG_STATE;\n\n //Make sure the buffer contains a valid HTTP request\n if(context->bufferLen > HTTP_CLIENT_BUFFER_SIZE)\n return ERROR_INVALID_SYNTAX;\n\n //Properly terminate the string with a NULL character\n context->buffer[context->bufferLen] = '\\0';\n\n //The Request-Line begins with a method token\n p = strchr(context->buffer, ' ');\n //Any parsing error?\n if(p == NULL)\n return ERROR_INVALID_SYNTAX;\n\n //The method token is followed by the Request-URI\n p++;\n\n //Point to the end of the Request-URI\n q = strpbrk(p, \" ?\");\n //Any parsing error?\n if(q == NULL)\n return ERROR_INVALID_SYNTAX;\n\n //Compute the length of the current URI\n m = q - p;\n //Compute the length of the new URI\n n = osStrlen(uri);\n\n //Make sure the buffer is large enough to hold the new resource name\n if((context->bufferLen + n - m) > HTTP_CLIENT_BUFFER_SIZE)\n return ERROR_BUFFER_OVERFLOW;\n\n //Make room for the new resource name\n osMemmove(p + n, q, context->buffer + context->bufferLen + 1 - q);\n //Copy the new resource name\n osStrncpy(p, uri, n);\n\n //Adjust the length of the request header\n context->bufferLen = context->bufferLen + n - m;\n\n //Successful processing\n return NO_ERROR;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "void options_apply() { /* apply default/validated configuration */\n unsigned num=0;\n SERVICE_OPTIONS *section;\n\n CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_SECTIONS]);\n\n memcpy(&global_options, &new_global_options, sizeof(GLOBAL_OPTIONS));\n memset(&new_global_options, 0, sizeof(GLOBAL_OPTIONS));\n\n /* service_options are used for inetd mode and to enumerate services */\n for(section=new_service_options.next; section; section=section->next)\n section->section_number=num++;\n memcpy(&service_options, &new_service_options, sizeof(SERVICE_OPTIONS));\n memset(&new_service_options, 0, sizeof(SERVICE_OPTIONS));\n number_of_sections=num;\n\n CRYPTO_THREAD_unlock(stunnel_locks[LOCK_SECTIONS]);\n}", "label": 1, "label_name": "safe"} -{"code": " def dataReceived(self, data: bytes) -> None:\n self.stream.write(data)\n self.length += len(data)\n if self.max_size is not None and self.length >= self.max_size:\n self.deferred.errback(\n SynapseError(\n 502,\n \"Requested file is too large > %r bytes\" % (self.max_size,),\n Codes.TOO_LARGE,\n )\n )\n self.deferred = defer.Deferred()\n self.transport.loseConnection()", "label": 0, "label_name": "vulnerable"} -{"code": "c.nodeName&&(v=c.hasAttribute(\"max-scale\")?parseFloat(c.getAttribute(\"max-scale\")):1);c=c.nextSibling}}finally{q.endUpdate()}null!=v&&this.chromelessResize&&this.chromelessResize(!0,v)}return g};EditorUi.prototype.getCopyFilename=function(c,e){var g=null!=c&&null!=c.getTitle()?c.getTitle():this.defaultFilename;c=\"\";var k=g.lastIndexOf(\".\");0<=k&&(c=g.substring(k),g=g.substring(0,k));if(e){e=g;var m=new Date;g=m.getFullYear();k=m.getMonth()+1;var q=m.getDate(),v=m.getHours(),y=m.getMinutes();m=m.getSeconds();\ng=e+(\" \"+(g+\"-\"+k+\"-\"+q+\"-\"+v+\"-\"+y+\"-\"+m))}return g=mxResources.get(\"copyOf\",[g])+c};EditorUi.prototype.fileLoaded=function(c,e){var g=this.getCurrentFile();this.fileEditable=this.fileLoadedError=null;this.setCurrentFile(null);var k=!1;this.hideDialog();null!=g&&(EditorUi.debug(\"File.closed\",[g]),g.removeListener(this.descriptorChangedListener),g.close());this.editor.graph.model.clear();this.editor.undoManager.clear();var m=mxUtils.bind(this,function(){this.setGraphEnabled(!1);this.setCurrentFile(null);", "label": 1, "label_name": "safe"} -{"code": "(function(){var b=new mxObjectCodec(new ChangeGridColor,[\"ui\"]);b.beforeDecode=function(e,f,c){c.ui=e.ui;return f};mxCodecRegistry.register(b)})();(function(){EditorUi.VERSION=\"19.0.1\";EditorUi.compactUi=\"atlas\"!=uiTheme;Editor.isDarkMode()&&(mxGraphView.prototype.gridColor=mxGraphView.prototype.defaultDarkGridColor);EditorUi.enableLogging=\"1\"!=urlParams.stealth&&\"1\"!=urlParams.lockdown&&(/.*\\.draw\\.io$/.test(window.location.hostname)||/.*\\.diagrams\\.net$/.test(window.location.hostname))&&\"support.draw.io\"!=window.location.hostname;EditorUi.drawHost=window.DRAWIO_BASE_URL;EditorUi.lightboxHost=window.DRAWIO_LIGHTBOX_URL;EditorUi.lastErrorMessage=", "label": 0, "label_name": "vulnerable"} -{"code": " public function index(Request $request)\n {\n /** @var User $user */\n $user = auth()->user();\n $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page');\n $pageSize = (int) app('preferences')->get('listPageSize', 50)->data;\n $collection = $this->repository->getAll();\n $total = $collection->count();\n $collection = $collection->slice(($page - 1) * $pageSize, $pageSize);\n $currencies = new LengthAwarePaginator($collection, $total, $pageSize, $page);\n $currencies->setPath(route('currencies.index'));\n\n $defaultCurrency = $this->repository->getCurrencyByPreference(app('preferences')->get('currencyPreference', config('firefly.default_currency', 'EUR')));\n $isOwner = true;\n if (!$this->userRepository->hasRole($user, 'owner')) {\n $request->session()->flash('info', (string) trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')]));\n $isOwner = false;\n }\n\n return prefixView('currencies.index', compact('currencies', 'defaultCurrency', 'isOwner'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def attemptRequestWithMaliciousURI(self, uri):\n \"\"\"\n Attempt a request with the provided method.\n\n @param uri: see L{URIInjectionTestsMixin}\n \"\"\"\n agent = client.Agent(self.createReactor())\n method = b\"GET\"\n agent.request(method, uri, client.Headers(), None)", "label": 1, "label_name": "safe"} -{"code": " def test_get_student_progress_url_nostudent(self):\n \"\"\" Test that the endpoint 400's when requesting an unknown email. \"\"\"\n url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.post(url)\n self.assertEqual(response.status_code, 400)", "label": 1, "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, "label_name": "safe"} -{"code": " def maySeePostUseCache(pageId: PageId, postNr: PostNr, user: Opt[Pat])\n : (MaySeeOrWhyNot, St) = {\n maySeePostImpl(pageId, postNr, user, anyPost = None, anyTx = None)\n }\n\n\n def maySeePostUseCache(post: Post, pageMeta: PageMeta, ppt: Option[Participant],", "label": 1, "label_name": "safe"} -{"code": "static char *getDirective(char *line, char **valuep)\n{\n char *key, *value;\n ssize len;\n \n assert(line);\n assert(valuep);\n\n *valuep = 0;\n key = stok(line, \" \\t\", &value);\n key = strim(key, \" \\t\\r\\n>\", MPR_TRIM_END);\n if (value) {\n value = strim(value, \" \\t\\r\\n>\", MPR_TRIM_END);\n /*\n Trim quotes if wrapping the entire value and no spaces. Preserve embedded quotes and leading/trailing \"\" etc.\n */\n len = slen(value);\n if (*value == '\\\"' && value[len - 1] == '\"' && len > 2 && value[1] != '\\\"' && !strpbrk(value, \" \\t\")) {\n /*\n Cannot strip quotes if multiple args are quoted, only if one single arg is quoted\n */\n if (schr(&value[1], '\"') == &value[len - 1]) {\n value = snclone(&value[1], len - 2);\n }\n }\n *valuep = value;\n }\n return key;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label": 0, "label_name": "vulnerable"} -{"code": "0>ea&&(ea=N.strokeWidth/2);u.setStrokeAlpha(u.state.fillAlpha);u.setStrokeColor(N.fill||\"\");u.setStrokeWidth(ea);u.setDashed(!1);this._drawToContext(K,T,N);u.setDashed(ba);u.setStrokeWidth(R);u.setStrokeColor(Q);u.setStrokeAlpha(Y)};D._drawToContext=function(K,T,N){K.begin();for(var Q=0;Q GetCopyNameAsync(this IFile file, string suffix,\n CancellationToken cancellationToken = default)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n string name = Path.GetFileNameWithoutExtension(file.Name);\n string extension = file.Extension;\n\n if (string.IsNullOrEmpty(suffix))\n {\n suffix = \" - copy\";\n }\n\n string newName = $\"{name}{suffix}{extension}\";\n if (!File.Exists(Path.Combine(file.DirectoryName, newName)))\n return newName;\n else\n {\n var search = $\"{name}*{extension}\";\n var sameNames = (await file.Parent.GetFilesAsync(search, false, _ => true, cancellationToken: cancellationToken))\n .Select(f => f.Name).ToArray();\n\n var count = 1;\n while (count != int.MaxValue)\n {\n newName = $\"{name}{suffix}({count++}){extension}\";\n if (!sameNames.Contains(newName))\n return newName;\n }\n\n throw new StackOverflowException();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def update(request, pk):\n comment = Comment.objects.for_update_or_404(pk, request.user)\n form = CommentForm(data=post_data(request), instance=comment)\n if is_post(request) and form.is_valid():\n pre_comment_update(comment=Comment.objects.get(pk=comment.pk))\n comment = form.save()\n post_comment_update(comment=comment)\n return redirect(request.POST.get('next', comment.get_absolute_url()))\n return render(\n request=request,\n template_name='spirit/comment/update.html',\n context={'form': form})", "label": 0, "label_name": "vulnerable"} -{"code": "\"25px\";btn.className=\"geColorBtn\";return btn}function Y(Aa,ta,ka,oa,sa,ya,wa){if(0checkCSRFParam();\n $project = $this->getProject();\n $swimlane = $this->getSwimlane($project);\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane['id'])) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label": 1, "label_name": "safe"} -{"code": " obj.select = function(o, e) {\r\n if (o.tagName == 'NAV') {\r\n var m = el.querySelectorAll('nav');\r\n for (var i = 0; i < m.length; i++) {\r\n m[i].style.display = 'none';\r\n }\r\n o.style.display = '';\r\n o.classList.add('selected');\r\n } else {\r\n var m = el.querySelectorAll('nav a');\r\n for (var i = 0; i < m.length; i++) {\r\n m[i].classList.remove('selected');\r\n }\r\n o.classList.add('selected');\r\n\r\n // Better navigation\r\n if (options && options.collapse == true) {\r\n if (o.classList.contains('show')) {\r\n m = el.querySelectorAll('nav');\r\n for (var i = 0; i < m.length; i++) {\r\n m[i].style.display = '';\r\n }\r\n o.style.display = 'none';\r\n } else {\r\n m = el.querySelectorAll('nav');\r\n for (var i = 0; i < m.length; i++) {\r\n m[i].style.display = 'none';\r\n }\r\n\r\n m = el.querySelector('.show');\r\n if (m) {\r\n m.style.display = 'block';\r\n }\r\n\r\n m = jSuites.findElement(o.parentNode, 'selected');\r\n if (m) {\r\n m.style.display = '';\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (options && typeof(options.onclick) == 'function') {\r\n options.onclick(obj, e);\r\n }\r\n\r\n // Close menu if is oped\r\n if (jSuites.getWindowWidth() < 800) {\r\n obj.hide();\r\n }\r\n }\r", "label": 1, "label_name": "safe"} -{"code": "\tbody: function(section) {\n\t\treturn this.state[section].body.join(\"\");\n\t},", "label": 1, "label_name": "safe"} -{"code": "!0));q.push(B)}this.updatePageLinks(c,q)}}if(null!=L&&\"mxGraphModel\"===L.nodeName){x=A.importGraphModel(L,e,g,k);if(null!=x)for(y=0;yfind('first', 'is_current=1');\n\t \n\t // check to see if the we have a new current version and unset the old current version.\n\t if (!empty($this->params['is_current'])) {\n//\t $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');\n help_version::clearHelpVersion();\n\t }\n\t expSession::un_set('help-version');\n\n\t // save the version\n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $version = new help_version();\n\t // if we don't have a current version yet so we will force this one to be it\n\t if (empty($current_version->id)) $this->params['is_current'] = 1;\n\t $version->update($this->params);\n\t \n\t // if this is a new version we need to copy over docs\n\t if (empty($id)) {\n\t self::copydocs($current_version->id, $version->id);\t \n\t }\n // let's update the search index to reflect the current help version\n searchController::spider();\n\n\t flash('message', gt('Saved help version').' '.$version->version);\n\t expHistory::back();\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "var S=document.createElement(\"tbody\"),Q=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(e=mxUtils.indexOf(b.pages,b.currentPage));for(p=f.length-1;0<=p;p--){var P=function(T){var X=new Date(T.modifiedDate),ba=null;if(0<=X.getTime()){var ja=function(ka){v.stop();E.innerText=\"\";var da=mxUtils.parseXml(ka),fa=b.editor.extractGraphModel(da.documentElement,!0);if(null!=fa){var ma=function(Ba){null!=Ba&&(Ba=ya(Editor.parseDiagramNode(Ba)));return Ba},ya=function(Ba){var Ha=Ba.getAttribute(\"background\");", "label": 1, "label_name": "safe"} -{"code": "null);mxEvent.consume(ca)})))}if(null!=L)for(M=0;M_special_dec2str[$code])) {\n return $entity;\n }\n return HTMLPurifier_Encoder::unichr($code);\n } else {\n if (isset($this->_special_ent2dec[$matches[3]])) {\n return $entity;\n }\n if (!$this->_entity_lookup) {\n $this->_entity_lookup = HTMLPurifier_EntityLookup::instance();\n }\n if (isset($this->_entity_lookup->table[$matches[3]])) {\n return $this->_entity_lookup->table[$matches[3]];\n } else {\n return $entity;\n }\n }\n }", "label": 1, "label_name": "safe"} -{"code": " it \"creates an index\" do\n indexes.create(key, background: true)\n indexes[key][\"background\"].should eq true\n end", "label": 0, "label_name": "vulnerable"} -{"code": "func (svc *Service) GetHost(ctx context.Context, id uint) (*fleet.HostDetail, error) {\n\talreadyAuthd := svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken)\n\tif !alreadyAuthd {\n\t\t// First ensure the user has access to list hosts, then check the specific\n\t\t// host once team_id is loaded.\n\t\tif err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\thost, err := svc.ds.Host(ctx, id, false)\n\tif err != nil {\n\t\treturn nil, ctxerr.Wrap(ctx, err, \"get host\")\n\t}\n\n\tif !alreadyAuthd {\n\t\t// Authorize again with team loaded now that we have team_id\n\t\tif err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn svc.getHostDetails(ctx, host)\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_secure_image_paths_dont_serve_non_images()\n {\n config()->set('filesystems.images', 'local_secure');\n $this->asEditor();\n\n $testFilePath = storage_path('/uploads/images/testing.txt');\n file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');\n\n $resp = $this->get('/uploads/images/testing.txt');\n $resp->assertStatus(404);\n }", "label": 1, "label_name": "safe"} -{"code": " public function testAttributesTransformedGlobalPre()\n {\n $def = $this->config->getHTMLDefinition(true);\n generate_mock_once('HTMLPurifier_AttrTransform');\n $transform = new HTMLPurifier_AttrTransformMock();\n $input = array('original' => 'value');\n $output = array('class' => 'value'); // must be valid\n $transform->returns('transform', $output, array($input, new AnythingExpectation(), new AnythingExpectation()));\n $def->info_attr_transform_pre[] = $transform;\n\n $token = new HTMLPurifier_Token_Start('span', $input, 1);\n $this->invoke($token);\n\n $result = $this->collector->getRaw();\n $expect = array(\n array(1, E_NOTICE, 'Attributes on transformed from original to class', array()),\n );\n $this->assertIdentical($result, $expect);\n }", "label": 1, "label_name": "safe"} -{"code": " protected function imageExtensions()\n {\n return [\n 'jpg',\n 'jpeg',\n 'bmp',\n 'png',\n 'webp',\n 'gif',\n 'svg'\n ];\n }", "label": 0, "label_name": "vulnerable"} -{"code": " void Init(void)\n {\n for(int i = 0;i < 15;i++) {\n X[i].Init();\n M[i].Init();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def feed_get_cover(book_id):\n return get_book_cover(book_id)", "label": 1, "label_name": "safe"} -{"code": " public static function loadFieldType(Db $zdb, $id)\n {\n try {\n $select = $zdb->select(self::TABLE);\n $select->where('field_id = ' . $id);\n\n $results = $zdb->execute($select);\n $result = $results->current();\n if ($result) {\n $field_type = $result->field_type;\n $field_type = self::getFieldType($zdb, $field_type);\n $field_type->loadFromRs($result);\n return $field_type;\n }\n } catch (Throwable $e) {\n Analog::log(\n __METHOD__ . ' | Unable to retrieve field `' . $id .\n '` information | ' . $e->getMessage(),\n Analog::ERROR\n );\n return false;\n }\n return false;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "SPL_METHOD(FilesystemIterator, current)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) {\n\t\tspl_filesystem_object_get_file_name(intern TSRMLS_CC);\n\t\tRETURN_STRINGL(intern->file_name, intern->file_name_len, 1);\n\t} else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) {\n\t\tspl_filesystem_object_get_file_name(intern TSRMLS_CC);\n\t\tspl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC);\n\t} else {\n\t\tRETURN_ZVAL(getThis(), 1, 0);\n\t\t/*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": " public function testShiftJIS()\n {\n if (!HTMLPurifier_Encoder::iconvAvailable()) return;\n $this->config->set('Core.Encoding', 'Shift_JIS');\n // This actually looks like a Yen, but we're going to treat it differently\n $this->assertIdentical(\n HTMLPurifier_Encoder::convertFromUTF8('\\\\~', $this->config, $this->context),\n '\\\\~'\n );\n $this->assertIdentical(\n HTMLPurifier_Encoder::convertToUTF8('\\\\~', $this->config, $this->context),\n '\\\\~'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "isis_print_id(const uint8_t *cp, int id_len)\n{\n int i;\n static char id[sizeof(\"xxxx.xxxx.xxxx.yy-zz\")];\n char *pos = id;\n\n for (i = 1; i <= SYSTEM_ID_LEN; i++) {\n snprintf(pos, sizeof(id) - (pos - id), \"%02x\", *cp++);\n\tpos += strlen(pos);\n\tif (i == 2 || i == 4)\n\t *pos++ = '.';\n\t}\n if (id_len >= NODE_ID_LEN) {\n snprintf(pos, sizeof(id) - (pos - id), \".%02x\", *cp++);\n\tpos += strlen(pos);\n }\n if (id_len == LSP_ID_LEN)\n snprintf(pos, sizeof(id) - (pos - id), \"-%02x\", *cp);\n return (id);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $category = $this->getCategory($project);\n\n $this->response->html($this->helper->layout->project('category/remove', array(\n 'project' => $project,\n 'category' => $category,\n )));\n }", "label": 1, "label_name": "safe"} -{"code": " public function angle($angle)\n {\n $this->angle = $angle;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def test_challenge(self):\n rc, root, folder, object = self._makeTree()\n response = FauxCookieResponse()\n testPath = '/some/path'\n testURL = 'http://test' + testPath\n request = FauxRequest(RESPONSE=response, URL=testURL,\n ACTUAL_URL=testURL)\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(testPath)))\n self.assertNotIn(testURL, loc)\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": 1, "label_name": "safe"} -{"code": " private function invertedSection($nodes, $id, $filters, $level)\n {\n $method = $this->getFindMethod($id);\n $id = var_export($id, true);\n $filters = $this->getFilters($filters, $level);\n\n return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $filters, $this->walk($nodes, $level));\n }", "label": 0, "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, "label_name": "vulnerable"} -{"code": "this.sidebar&&null!=urlParams[\"search-shapes\"]&&null!=this.sidebar.searchShapes&&(this.sidebar.searchShapes(urlParams[\"search-shapes\"]),this.sidebar.showEntries(\"search\"));var F=this;mxWindow.prototype.fit=function(){if(Editor.inlineFullscreen||null==F.embedViewport)mxUtils.fit(this.div);else{var da=parseInt(this.div.offsetLeft),ca=parseInt(this.div.offsetWidth),la=F.embedViewport.x+F.embedViewport.width,ia=parseInt(this.div.offsetTop),ma=parseInt(this.div.offsetHeight),qa=F.embedViewport.y+F.embedViewport.height;\nthis.div.style.left=Math.max(F.embedViewport.x,Math.min(da,la-ca))+\"px\";this.div.style.top=Math.max(F.embedViewport.y,Math.min(ia,qa-ma))+\"px\";this.div.style.height=Math.min(F.embedViewport.height,parseInt(this.div.style.height))+\"px\";this.div.style.width=Math.min(F.embedViewport.width,parseInt(this.div.style.width))+\"px\"}};this.keyHandler.bindAction(75,!0,\"toggleShapes\",!0);EditorUi.windowed&&(\"1\"==urlParams.sketch||1E3<=c)&&\"1\"!=urlParams.embedInline&&(b(this,!0),\"1\"==urlParams.sketch?(this.initFormatWindow(),", "label": 0, "label_name": "vulnerable"} -{"code": " public void translate(ServerEntityTeleportPacket 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.teleport(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), packet.isOnGround());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getFixesForLevel($level)\n {\n if ($level == $this->levels[0]) {\n return array();\n }\n $activated_levels = array();\n for ($i = 1, $c = count($this->levels); $i < $c; $i++) {\n $activated_levels[] = $this->levels[$i];\n if ($this->levels[$i] == $level) {\n break;\n }\n }\n if ($i == $c) {\n trigger_error(\n 'Tidy level ' . htmlspecialchars($level) . ' not recognized',\n E_USER_WARNING\n );\n return array();\n }\n $ret = array();\n foreach ($activated_levels as $level) {\n foreach ($this->fixesForLevel[$level] as $fix) {\n $ret[$fix] = true;\n }\n }\n return $ret;\n }", "label": 1, "label_name": "safe"} -{"code": " public function remove($config) {\n return false;\n }", "label": 1, "label_name": "safe"} -{"code": " public function upload() {\n \n // upload the file, but don't save the record yet...\n if ($this->params['resize'] != 'false') {\n $maxwidth = $this->params['max_width'];\n } else {\n $maxwidth = null;\n }\n $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);\n // since most likely this function will only get hit via flash in YUI Uploader\n // and since Flash can't pass cookies, we lose the knowledge of our $user\n // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,\n // and then assign $user->id to $file->poster so we have an audit trail for the upload\n\n if (is_object($file)) {\n $resized = !empty($file->resized) ? true : false;\n $user = new user($this->params['usrid']);\n $file->poster = $user->id;\n $file->posted = $file->last_accessed = time();\n $file->save();\n if (!empty($this->params['cat'])) {\n $expcat = new expCat($this->params['cat']);\n $params['expCat'][0] = $expcat->id;\n $file->update($params);\n }\n\n // a echo so YUI Uploader is notified of the function's completion\n if ($resized) {\n echo gt('File resized and then saved');\n } else {\n echo gt('File saved');\n }\n } else {\n echo gt('File was NOT uploaded!');\n// flash('error',gt('File was not uploaded!'));\n }\n } ", "label": 0, "label_name": "vulnerable"} -{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . expString::escape($this->params['model']) . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label": 1, "label_name": "safe"} -{"code": " public function withScheme($scheme)\n {\n $scheme = $this->filterScheme($scheme);\n\n if ($this->scheme === $scheme) {\n return $this;\n }\n\n $new = clone $this;\n $new->scheme = $scheme;\n $new->port = $new->filterPort($new->port);\n return $new;\n }", "label": 1, "label_name": "safe"} -{"code": " function searchCategory() {\r\n return gt('Event');\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "function updatePropertyOn(obj, path, value) {\n if (typeof path === 'string') {\n path = path.split('.');\n }\n\n var next = path[0];\n\n if (obj.hasOwnProperty(next)) {\n if (path.length === 1) {\n obj[next] = value;\n } else {\n updatePropertyOn(obj[next], path.slice(1), value);\n }\n }\n}", "label": 1, "label_name": "safe"} -{"code": "PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_pli(\n\t\t\t\t\tpjmedia_rtcp_session *session, \n\t\t\t\t\tvoid *buf,\n\t\t\t\t\tpj_size_t *length)\n{\n pjmedia_rtcp_fb_common *hdr;\n unsigned len;\n\n PJ_ASSERT_RETURN(session && buf && length, PJ_EINVAL);\n\n len = 12;\n if (len > *length)\n\treturn PJ_ETOOSMALL;\n\n /* Build RTCP-FB PLI header */\n hdr = (pjmedia_rtcp_fb_common*)buf;\n pj_memcpy(hdr, &session->rtcp_fb_com, sizeof(*hdr));\n hdr->rtcp_common.pt = RTCP_PSFB;\n hdr->rtcp_common.count = 1; /* FMT = 1 */\n hdr->rtcp_common.length = pj_htons((pj_uint16_t)(len/4 - 1));\n\n /* Finally */\n *length = len;\n\n return PJ_SUCCESS;\n}", "label": 1, "label_name": "safe"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $action = $this->getAction($project);\n\n if (! empty($action) && $this->actionModel->remove($action['id'])) {\n $this->flash->success(t('Action removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this action.'));\n }\n\n $this->response->redirect($this->helper->url->to('ActionController', 'index', array('project_id' => $project['id'])));\n }", "label": 1, "label_name": "safe"} -{"code": " protected function getInternalTaskLink(array $task)\n {\n $link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n if ($link['task_id'] != $task['id']) {\n throw new AccessForbiddenException();\n }\n\n return $link;\n }", "label": 1, "label_name": "safe"} -{"code": " def on_moved\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n location_id = params[:id]\n SqlHelper.validate_token([location_id])\n\n if location_id.blank?\n location = Location.get_for(@login_user)\n if location.nil?\n location = Location.new\n location.user_id = @login_user.id\n end\n else\n begin\n location = Location.find(location_id)\n rescue\n location = nil\n end\n end\n\n unless location.nil?\n group_id = params[:group_id]\n group_id = nil if group_id.empty?\n SqlHelper.validate_token([group_id])\n attrs = ActionController::Parameters.new({group_id: group_id, x: params[:x], y: params[:y]})\n location.update_attributes(attrs.permit(Location::PERMIT_BASE))\n end\n\n render(:text => (location.nil?)?'':location.id.to_s)\n end", "label": 1, "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, "label_name": "safe"} -{"code": " private function addServiceAlias($alias, Alias $id, \\DOMElement $parent)\n {\n $service = $this->document->createElement('service');\n $service->setAttribute('id', $alias);\n $service->setAttribute('alias', $id);\n if (!$id->isPublic()) {\n $service->setAttribute('public', 'false');\n }\n $parent->appendChild($service);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def another_upload_file(request):\n path = tempfile.mkdtemp()\n file_name = os.path.join(path, \"another_%s.txt\" % request.node.name)\n with open(file_name, \"w\") as f:\n f.write(request.node.name)\n return file_name", "label": 0, "label_name": "vulnerable"} -{"code": "bool ValidateInput(const Tensor& updates) {\n const auto updates_flat = updates.flat();\n const T zero(0);\n for (int i = 0; i < updates.NumElements(); i++) {\n if (updates_flat(i) == zero) return false;\n }\n return true;\n}", "label": 1, "label_name": "safe"} -{"code": " public function search(){\n // Warning: Please modify the following code to remove attributes that\n // should not be searched.\n\n $criteria = new CDbCriteria;\n $username = Yii::app()->user->name;\n $criteria->addCondition(\"uploadedBy='$username' OR private=0 OR private=null\");\n $criteria->addCondition(\"associationType != 'theme'\");\n return $this->searchBase($criteria);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct($message = null, $code = null, $nativeCode = null)\n {\n parent::__construct($message, $code);\n $this->_nativeCode = $nativeCode;\n }", "label": 0, "label_name": "vulnerable"} -{"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 ' + $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": 0, "label_name": "vulnerable"} -{"code": "mxShape.prototype.clear=function(){if(null!=this.node.ownerSVGElement)for(;null!=this.node.lastChild;)this.node.removeChild(this.node.lastChild);else this.node.style.cssText=\"position:absolute;\"+(null!=this.cursor?\"cursor:\"+this.cursor+\";\":\"\"),this.node.innerHTML=\"\"};", "label": 0, "label_name": "vulnerable"} -{"code": "Map1toN(SDL_PixelFormat * src, Uint8 Rmod, Uint8 Gmod, Uint8 Bmod, Uint8 Amod,\n SDL_PixelFormat * dst)\n{\n Uint8 *map;\n int i;\n int bpp;\n SDL_Palette *pal = src->palette;\n\n bpp = ((dst->BytesPerPixel == 3) ? 4 : dst->BytesPerPixel);\n map = (Uint8 *) SDL_malloc(pal->ncolors * bpp);\n if (map == NULL) {\n SDL_OutOfMemory();\n return (NULL);\n }\n\n /* We memory copy to the pixel map so the endianness is preserved */\n for (i = 0; i < pal->ncolors; ++i) {\n Uint8 R = (Uint8) ((pal->colors[i].r * Rmod) / 255);\n Uint8 G = (Uint8) ((pal->colors[i].g * Gmod) / 255);\n Uint8 B = (Uint8) ((pal->colors[i].b * Bmod) / 255);\n Uint8 A = (Uint8) ((pal->colors[i].a * Amod) / 255);\n ASSEMBLE_RGBA(&map[i * bpp], dst->BytesPerPixel, dst, (Uint32)R, (Uint32)G, (Uint32)B, (Uint32)A);\n }\n return (map);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testDoesNotCacheRequestsWithACookieHeader()\n {\n $this->setNextResponse(200);\n $this->request('GET', '/', array(), array('foo' => 'bar'));\n\n $this->assertHttpKernelIsCalled();\n $this->assertResponseOk();\n $this->assertEquals('private', $this->response->headers->get('Cache-Control'));\n $this->assertTraceContains('miss');\n $this->assertTraceNotContains('store');\n $this->assertFalse($this->response->headers->has('Age'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "Channel.prototype.signal = function(signalName) {\n if (this.server)\n throw new Error('Client-only method called in server mode');\n\n if (this.type === 'session'\n && this.writable\n && this.outgoing.state === 'open')\n return this._client._sshstream.signal(this.outgoing.id, signalName);\n\n return true;\n};", "label": 0, "label_name": "vulnerable"} -{"code": "var M=mxText.prototype.redraw;mxText.prototype.redraw=function(){M.apply(this,arguments);null!=this.node&&\"DIV\"==this.node.nodeName&&Graph.processFontAttributes(this.node)};Graph.prototype.createTagsDialog=function(p,C,I){function T(){for(var la=R.getSelectionCells(),Aa=[],Fa=0;Fa')\n with self.assertRaises(NotFound):\n t()\n\n t.write('

')\n with self.assertRaises(NotFound):\n t()\n\n t.write('

')\n with self.assertRaises(NotFound):\n t()", "label": 1, "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, "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, "label_name": "safe"} -{"code": " it 'should not preserve the content of removed `math` elements' do\n Sanitize.fragment('hello! ')\n .must_equal ''\n end", "label": 1, "label_name": "safe"} -{"code": " public function __construct() {\n $this->keyfile = GLPI_CONFIG_DIR . '/glpi.key';\n }", "label": 1, "label_name": "safe"} -{"code": " text: Ext.util.Format.htmlEncode(String.format(i18n._('User: {0}'), Tine.Tinebase.registry.get('currentAccount').accountDisplayName)),", "label": 1, "label_name": "safe"} -{"code": "static int parse_token(char **name, char **value, char **cp)\n{\n\tchar *end;\n\n\tif (!name || !value || !cp)\n\t\treturn -BLKID_ERR_PARAM;\n\n\tif (!(*value = strchr(*cp, '=')))\n\t\treturn 0;\n\n\t**value = '\\0';\n\t*name = strip_line(*cp);\n\t*value = skip_over_blank(*value + 1);\n\n\tif (**value == '\"') {\n\t\tend = strchr(*value + 1, '\"');\n\t\tif (!end) {\n\t\t\tDBG(READ, ul_debug(\"unbalanced quotes at: %s\", *value));\n\t\t\t*cp = *value;\n\t\t\treturn -BLKID_ERR_CACHE;\n\t\t}\n\t\t(*value)++;\n\t\t*end = '\\0';\n\t\tend++;\n\t} else {\n\t\tend = skip_over_word(*value);\n\t\tif (*end) {\n\t\t\t*end = '\\0';\n\t\t\tend++;\n\t\t}\n\t}\n\t*cp = end;\n\n\treturn 1;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " ...new Set(utxos.filter((txOut) => {\n if (txOut.slpTransactionDetails &&\n txOut.slpUtxoJudgement !== SlpUtxoJudgement.UNKNOWN &&\n txOut.slpUtxoJudgement !== SlpUtxoJudgement.UNSUPPORTED_TYPE &&\n txOut.slpUtxoJudgement !== SlpUtxoJudgement.NOT_SLP) {\n return true;\n }\n return false;\n }).map((txOut) => txOut.txid)),", "label": 1, "label_name": "safe"} -{"code": " public function getName()\n {\n return 'testkernel';\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getCacheDir()\n {\n return $this->rootDir.'/cache/'.$this->environment;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def update_auth_token_in_cookie(token)\n return unless cookie_auth_token_complete?\n current_token = cookie_split_auth_token\n updated_token = [token, *current_token[1..-1]]\n cookies[:auth_token] = updated_token.join(\"&\")\n end", "label": 1, "label_name": "safe"} -{"code": " def show_owners name\n response = rubygems_api_request :get, \"api/v1/gems/#{name}/owners.yaml\" do |request|\n request.add_field \"Authorization\", api_key\n end\n\n with_response response do |resp|\n owners = Gem::SafeYAML.load resp.body\n\n say \"Owners for gem: #{name}\"\n owners.each do |owner|\n say \"- #{owner['email'] || owner['handle'] || owner['id']}\"\n end\n end\n end", "label": 1, "label_name": "safe"} -{"code": "\tprotected function parse()\n\t{\n\t\tparent::parse();\n\n\t\t// grab the error-type from the parameters\n\t\t$errorType = $this->getParameter('type');\n\n\t\t// set correct headers\n\t\tswitch($errorType)\n\t\t{\n\t\t\tcase 'module-not-allowed':\n\t\t\tcase 'action-not-allowed':\n\t\t\t\tSpoonHTTP::setHeadersByCode(403);\n\t\t\t\tbreak;\n\n\t\t\tcase 'not-found':\n\t\t\t\tSpoonHTTP::setHeadersByCode(404);\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// querystring provided?\n\t\tif($this->getParameter('querystring') !== null)\n\t\t{\n\t\t\t// split into file and parameters\n\t\t\t$chunks = explode('?', $this->getParameter('querystring'));\n\n\t\t\t// get extension\n\t\t\t$extension = SpoonFile::getExtension($chunks[0]);\n\n\t\t\t// if the file has an extension it is a non-existing-file\n\t\t\tif($extension != '' && $extension != $chunks[0])\n\t\t\t{\n\t\t\t\t// set correct headers\n\t\t\t\tSpoonHTTP::setHeadersByCode(404);\n\n\t\t\t\t// give a nice error, so we can detect which file is missing\n\t\t\t\techo 'Requested file (' . implode('?', $chunks) . ') not found.';\n\n\t\t\t\t// stop script execution\n\t\t\t\texit;\n\t\t\t}\n\t\t}\n\n\t\t// assign the correct message into the template\n\t\t$this->tpl->assign('message', BL::err(SpoonFilter::toCamelCase($errorType, '-')));\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def initialize(nodes = 3)\n @nodes = nodes.times.map { Node.new(self) }\n @manager = ConnectionManager.new(@nodes)\n @mongo = TCPSocket.new \"127.0.0.1\", 27017\n end", "label": 1, "label_name": "safe"} -{"code": " $tmpProviders = $container->getExpressionLanguageProviders();\n }));\n\n $provider = $this->getMock('Symfony\\\\Component\\\\ExpressionLanguage\\\\ExpressionFunctionProviderInterface');\n $container = new ContainerBuilder(new ParameterBag());\n $container->registerExtension($extension);\n $container->prependExtensionConfig('foo', array('bar' => true));\n $container->addExpressionLanguageProvider($provider);\n\n $pass = new MergeExtensionConfigurationPass();\n $pass->process($container);\n\n $this->assertEquals(array($provider), $tmpProviders);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($all_users as &$u) {\n if ($u['username'] == $username && $this->verifyPassword($password, $u['password'])) {\n $user = $this->mapToUserObject($u);\n $this->store($user);\n $this->session->set(self::SESSION_HASH, $u['password']);\n\n return true;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_ForbiddenElements_invalidElement()\n {\n $this->config->set('HTML.ForbiddenElements', 'obviously_incorrect');\n // no error!\n $this->assertPurification('i');\n }", "label": 1, "label_name": "safe"} -{"code": "cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb_vol *vol)\n{\n\tstruct cifsSesInfo *ses;\n\n\twrite_lock(&cifs_tcp_ses_lock);\n\tlist_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {\n\t\tswitch (server->secType) {\n\t\tcase Kerberos:\n\t\t\tif (vol->linux_uid != ses->linux_uid)\n\t\t\t\tcontinue;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/* anything else takes username/password */\n\t\t\tif (strncmp(ses->userName, vol->username,\n\t\t\t\t MAX_USERNAME_SIZE))\n\t\t\t\tcontinue;\n\t\t\tif (strlen(vol->username) != 0 &&\n\t\t\t strncmp(ses->password, vol->password,\n\t\t\t\t MAX_PASSWORD_SIZE))\n\t\t\t\tcontinue;\n\t\t}\n\t\t++ses->ses_count;\n\t\twrite_unlock(&cifs_tcp_ses_lock);\n\t\treturn ses;\n\t}\n\twrite_unlock(&cifs_tcp_ses_lock);\n\treturn NULL;\n}", "label": 1, "label_name": "safe"} -{"code": " public function backup($type='json')\r\n {\r\n global $DB;\r\n global $website;\r\n\r\n $out = array();\r\n\r\n $DB->query('SELECT * FROM nv_webdictionary WHERE website = '.protect($website->id), 'object');\r\n\r\n if($type='json')\r\n $out = json_encode($DB->result());\r\n\r\n return $out;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " def sql_one_row(self, sentence, column):\n if type(sentence) is str:\n \tself.cursor.execute(sentence)\n \telse:\n \tself.cursor.execute(sentence[0], sentence[1])\t\n return self.cursor.fetchone()[column]", "label": 1, "label_name": "safe"} -{"code": " public function setFragmentPath($path)\n {\n $this->fragmentPath = $path;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "!(a%400)};d.isSameDay=function(a,c){return a.toDateString()===c.toDateString()};d.locale=function(a,c){c?u(a,{res:v,formatter:w,parser:x},c):\"function\"===typeof a?m=a(d):a&&(q&&!q.date&&console.warn(\"This method of changing the locale is deprecated. See documentation for details.\"),m=a);return m};d.extend=function(a){var c=a.extender||{},b;for(b in c)d[b]||(d[b]=c[b]);(a.formatter||a.parser||a.res)&&u(m,t[m],a)};d.plugin=function(a,c){\"function\"===typeof a?d.extend(r[a(d)]):(r[a]=r[a]||c,!c&&r[a]&&", "label": 1, "label_name": "safe"} -{"code": "\t\tATTR: function(match){\n\t\t\tvar name = match[1].replace(/\\\\/g, \"\");\n\t\t\t\n\t\t\tif ( Expr.attrMap[name] ) {\n\t\t\t\tmatch[1] = Expr.attrMap[name];\n\t\t\t}\n\n\t\t\tif ( match[2] === \"~=\" ) {\n\t\t\t\tmatch[4] = \" \" + match[4] + \" \";\n\t\t\t}\n\n\t\t\treturn match;\n\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n if ($tag['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n if ($this->tagModel->remove($tag_id)) {\n $this->flash->success(t('Tag removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this tag.'));\n }\n\n $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public String encodePassword(final String rawPassword) {\n return encodePassword(rawPassword, null);\n }", "label": 1, "label_name": "safe"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"removes all matching documents\" do\n session.should_receive(:with, :consistency => :strong).\n and_yield(session)\n\n session.should_receive(:execute).with do |delete|\n delete.flags.should eq []\n delete.selector.should eq query.operation.selector\n end\n\n query.remove_all\n end", "label": 0, "label_name": "vulnerable"} -{"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, "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=\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, "label_name": "safe"} -{"code": " public function registerContainerConfiguration(LoaderInterface $loader)\n {\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function setIp($ip)\n {\n $this->ip = $ip;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testConstructWithoutArgument() {\n $hash = new Hash;\n $this->assertTrue($hash instanceof \\RandomLib\\Mixer);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static void scsi_free_request(SCSIRequest *req)\n{\n SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);\n\n qemu_vfree(r->iov.iov_base);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test()\n {\n $this->def = new HTMLPurifier_AttrDef_HTML_Bool('foo');\n $this->assertDef('foo');\n $this->assertDef('', 'foo');\n $this->assertDef('bar', 'foo');\n }", "label": 1, "label_name": "safe"} -{"code": " it \"does not log the operations\" do\n socket.should_receive(:log_operations).never\n socket.instrument([]) {}\n end", "label": 0, "label_name": "vulnerable"} -{"code": "func (m *MockTokenRevocationStorage) RevokeRefreshToken(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RevokeRefreshToken\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "label": 1, "label_name": "safe"} -{"code": " $files = array_merge($files, $sub_files);\n }\n return $files;\n }", "label": 1, "label_name": "safe"} -{"code": " it 'should be able to disable compression' do\n verify_contents(subject, 'mysqlbackup.sh', [\n ' --all-databases > ${DIR}/${PREFIX}`date +%Y%m%d-%H%M%S`.sql',\n ])\n end", "label": 0, "label_name": "vulnerable"} -{"code": "g.join(\"\"))}()+''}]}],\nbuttons:[CKEDITOR.dialog.cancelButton]}});", "label": 1, "label_name": "safe"} -{"code": " def test_render_with_explicit_unescaped_template\n assert_raise(ActionView::MissingTemplate) { get :render_with_explicit_unescaped_template }\n get :render_with_explicit_escaped_template\n assert_equal \"Hello w*rld!\", @response.body\n end", "label": 1, "label_name": "safe"} -{"code": "\tparent: function(elem){return elem.parentNode;},", "label": 0, "label_name": "vulnerable"} -{"code": "def is_gae_instance():\n server_software = os.environ.get('SERVER_SOFTWARE', '')\n if (server_software.startswith('Google App Engine/') or\n server_software.startswith('Development/') or\n server_software.startswith('testutil/')):\n return True\n return False", "label": 0, "label_name": "vulnerable"} -{"code": " public function getContents($recursive = false)\n {\n return $this->filesystem->listContents($this->path, $recursive);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def test_login_missing_code_post(self):\n response = self.client.post('/accounts/login/code/')\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context['form'].errors, {\n 'user': ['This field is required.'],\n 'code': ['This field is required.'],\n '__all__': ['Unable to log in with provided login code.']\n })", "label": 1, "label_name": "safe"} -{"code": " const wrapper = (err, stream) => {\n cb(err, stream);\n };", "label": 1, "label_name": "safe"} -{"code": " foreach ($val as $vkey => $value) {\n if ($vkey != 'LAST_UPDATED') {\n if ($vkey != 'UPDATED_BY') {\n if ($vkey == 'ID')\n echo '' . htmlentities($value) . '';\n else if ($vkey == 'SYEAR')\n echo '' . htmlentities($value) . '';\n else if ($vkey == 'TITLE')\n echo '' . htmlentities($value) . '';\n else if ($vkey == 'WWW_ADDRESS')\n echo '' . htmlentities($value) . '';\n else\n echo '<' . $vkey . '>' . htmlentities($value) . '';\n }\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def test_digest_object():\n credentials = (\"joe\", \"password\")\n host = None\n request_uri = \"/test/digest/\"\n headers = {}\n response = {\n \"www-authenticate\": 'Digest realm=\"myrealm\", nonce=\"KBAA=35\", algorithm=MD5, qop=\"auth\"'\n }\n content = b\"\"\n\n d = httplib2.DigestAuthentication(\n credentials, host, request_uri, headers, response, content, None\n )\n d.request(\"GET\", request_uri, headers, content, cnonce=\"33033375ec278a46\")\n our_request = \"authorization: \" + headers[\"authorization\"]\n working_request = (\n 'authorization: Digest username=\"joe\", realm=\"myrealm\", '\n 'nonce=\"KBAA=35\", uri=\"/test/digest/\"'\n + ', algorithm=MD5, response=\"de6d4a123b80801d0e94550411b6283f\", '\n 'qop=auth, nc=00000001, cnonce=\"33033375ec278a46\"'\n )\n assert our_request == working_request", "label": 0, "label_name": "vulnerable"} -{"code": "static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,\n\tdouble *pv)\n{\n\tunsigned int field_type;\n\tunsigned int value_count;\n\tunsigned int value_pos;\n\tunsigned int numer, denom;\n\n\tfield_type = get_exif_ui16(e, tag_pos+2);\n\tvalue_count = get_exif_ui32(e, tag_pos+4);\n\n\tif(value_count!=1) return 0;\n\n\tif(field_type!=5) return 0; // 5=Rational (two uint32's)\n\n\t// A rational is 8 bytes. Since 8>4, it is stored indirectly. First, read\n\t// the location where it is stored.\n\n\tvalue_pos = get_exif_ui32(e, tag_pos+8);\n\tif(value_pos > e->d_len-8) return 0;\n\n\t// Read the actual value.\n\tnumer = get_exif_ui32(e, value_pos);\n\tdenom = get_exif_ui32(e, value_pos+4);\n\tif(denom==0) return 0;\n\n\t*pv = ((double)numer)/denom;\n\treturn 1;\n}", "label": 1, "label_name": "safe"} -{"code": " public function __construct($message, $code = 0, Exception $previous = null)\n {\n parent::__construct($message, $code, $previous);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"the parameter '#{param_name.to_s}' should match #{param_value.inspect}\" do\n # booleans get cludged to string \"true\"\n if param_value == true then\n expect(resource[param_name]).to be_true\n else\n expect(resource[param_name]).to eq(data[:params][param_name])\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": "static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)\n{\n\tint start = 0;\n\tint i;\n\tu32 prev_legacy, cur_legacy;\n\tmutex_lock(&kvm->arch.vpit->pit_state.lock);\n\tprev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;\n\tcur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;\n\tif (!prev_legacy && cur_legacy)\n\t\tstart = 1;\n\tmemcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,\n\t sizeof(kvm->arch.vpit->pit_state.channels));\n\tkvm->arch.vpit->pit_state.flags = ps->flags;\n\tfor (i = 0; i < 3; i++)\n\t\tkvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count, start);\n\tmutex_unlock(&kvm->arch.vpit->pit_state.lock);\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": " public function getMethod()\n {\n return 'listWith';\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getConfiguration(array $config, ContainerBuilder $container)\n {\n $reflected = new \\ReflectionClass($this);\n $namespace = $reflected->getNamespaceName();\n\n $class = $namespace.'\\\\Configuration';\n if (class_exists($class)) {\n $r = new \\ReflectionClass($class);\n $container->addResource(new FileResource($r->getFileName()));\n\n if (!method_exists($class, '__construct')) {\n return new $class();\n }\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "func relPath(root, member string) string {\n\treturn filepath.Join(root, filepath.Join(\"/\", member))\n}", "label": 1, "label_name": "safe"} -{"code": "func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) {\n\tif !config.Cache.Enabled {\n\t\treturn nil, false\n\t}\n\n\titem, found := a.tokenCache.Get(token)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\ti := item.(*AuthenticatorOAuth2IntrospectionResult)\n\texpires := time.Unix(i.Expires, 0)\n\tif expires.Before(time.Now()) {\n\t\ta.tokenCache.Del(token)\n\t\treturn nil, false\n\t}\n\n\treturn i, true\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testBlockAllowedInNonInline()\n {\n $this->isInline = false;\n $this->assertResult(\n '

Allowed.
'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " $val = trim($pfx);\n if (! empty($val)) {\n $arpfx[] = $val;\n }\n }\n if (count($arpfx) > 0) {\n $prefixList = $arpfx;\n }\n }\n break;\n }\n $node = $node->nextSibling;\n }\n break;\n case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':\n case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':\n if (!$includeCommentNodes) {\n /* We remove comment nodes by forcing it to use a canonicalization\n * without comments.\n */\n $canonicalMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';\n } else {\n $canonicalMethod = $algorithm;\n }\n\n break;\n case 'http://www.w3.org/TR/1999/REC-xpath-19991116':\n $node = $transform->firstChild;\n while ($node) {\n if ($node->localName == 'XPath') {\n $arXPath = array();\n $arXPath['query'] = '(.//. | .//@* | .//namespace::*)['.$node->nodeValue.']';\n $arXPath['namespaces'] = array();\n $nslist = $xpath->query('./namespace::*', $node);\n foreach ($nslist AS $nsnode) {\n if ($nsnode->localName != \"xml\") {\n $arXPath['namespaces'][$nsnode->localName] = $nsnode->nodeValue;\n }\n }\n break;\n }\n $node = $node->nextSibling;\n }\n break;\n }\n }\n if ($data instanceof DOMNode) {\n $data = $this->canonicalizeData($objData, $canonicalMethod, $arXPath, $prefixList);\n }\n return $data;\n }", "label": 1, "label_name": "safe"} -{"code": "\tthis.error = function() {\n\t\tvar arg = arguments[0];\n\t\treturn arguments.length == 1 && typeof(arg) == 'function'\n\t\t\t? self.bind('error', arg)\n\t\t\t: self.trigger('error', {error : arg});\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "function(){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)))),D=mxUtils.parseXml(C).getElementsByTagName(\"svg\");0u.dir.index = 0;\n\tif (object->u.dir.dirp) {\n\t\tphp_stream_rewinddir(object->u.dir.dirp);\n\t}\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 (iterator->current) {\n\t\tzval_ptr_dtor(&iterator->current);\n\t\titerator->current = NULL;\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": "exports.database.prototype.findKeys = function (key, notKey, callback)\n{\n var query=\"SELECT `key` FROM `store` WHERE `key` LIKE ?\"\n , params=[]\n ;\n \n //desired keys are key, e.g. pad:%\n key=key.replace(/\\*/g,'%');\n params.push(key);\n \n if(notKey!=null && notKey != undefined){\n //not desired keys are notKey, e.g. %:%:%\n notKey=notKey.replace(/\\*/g,'%');\n query+=\" AND `key` NOT LIKE ?\"\n params.push(notKey);\n }\n this.db.query(query, params, function(err,results)\n {\n var value = [];\n \n if(!err && results.length > 0)\n {\n results.forEach(function(val){\n value.push(val.key);\n });\n }\n \n callback(err,value);\n });\n\n this.schedulePing();\n}", "label": 0, "label_name": "vulnerable"} -{"code": "1);break}D.className=la.join(\" \")}null!=ha?(D=ha,D.className+=\" \"+da,K=ca,Aa.className=\"geTempDlgCreateBtn\"):(K=D=null,Aa.className=\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function z(ha,da){if(null!=K){var ca=function(pa){ra.isExternal?g(ra,function(na){la(na,pa)},ia):ra.url?mxUtils.get(TEMPLATE_PATH+\"/\"+ra.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?la(na.getText(),pa):ia()})):la(b.emptyDiagramXml,pa)},la=function(pa,na){y||b.hideDialog(!0);e(pa,na,ra,da)},ia=function(){A(mxResources.get(\"cannotLoad\"));", "label": 1, "label_name": "safe"} -{"code": " def exists?\n properties[:ensure] != :absent\n end", "label": 0, "label_name": "vulnerable"} -{"code": "def default_dir_win(tmp_dir=None):\n \"\"\"\n Create or find default catalog store for Windows systems\n\n purpose of 'tmp_dir' is to enable way how to test this function easily\n \"\"\"\n def create_win_temp_dir(prefix, inner_dir=None, tmp_dir=None):\n \"\"\"\n create temp dir starting with 'prefix' in 'tmp_dir' or\n 'tempfile.gettempdir'; if 'inner_dir' is specified, it should be\n created inside\n \"\"\"\n tmp_dir_path = find_valid_temp_dir(prefix, tmp_dir)\n if tmp_dir_path:\n if inner_dir:\n tmp_dir_path = os.path.join(tmp_dir_path, inner_dir)\n if not os.path.isdir(tmp_dir_path):\n os.mkdir(tmp_dir_path, 0o700)\n else:\n tmp_dir_path = create_temp_dir(prefix, inner_dir, tmp_dir)\n return tmp_dir_path\n\n python_name = \"python%d%d_compiled\" % tuple(sys.version_info[:2])\n tmp_dir = tmp_dir or tempfile.gettempdir()\n\n temp_dir_name = \"%s\" % whoami()\n temp_root_dir = os.path.join(tmp_dir, temp_dir_name)\n temp_dir_path = os.path.join(temp_root_dir, python_name)\n _create_dirs(temp_dir_path)\n if check_dir(temp_dir_path) and check_dir(temp_root_dir):\n return temp_dir_path\n else:\n if check_dir(temp_root_dir):\n return create_win_temp_dir(python_name, tmp_dir=temp_root_dir)\n else:\n return create_win_temp_dir(temp_dir_name, python_name, tmp_dir)", "label": 1, "label_name": "safe"} -{"code": " public function testSimpleNoParsing()\n {\n\n $parser = new JBBCode\\Parser();\n $parser->addCodeDefinitionSet(new JBBCode\\DefaultCodeDefinitionSet());\n $parser->addBBCode('verbatim', '{param}', false, false);\n\n $parser->parse('[verbatim]plain text[/verbatim]');\n $this->assertEquals('plain text', $parser->getAsHtml());\n\n $parser->parse('[verbatim][b]bold[/b][/verbatim]');\n $this->assertEquals('[b]bold[/b]', $parser->getAsHtml());\n\n }", "label": 1, "label_name": "safe"} -{"code": "function coverQuery (context, coverage, statMode) {\n coverage = parseFloat(coverage)\n var usage = browserslist.usage.global\n if (statMode) {\n if (statMode.match(/^my\\s+stats$/)) {\n if (!context.customUsage) {\n throw new BrowserslistError(\n 'Custom usage statistics was not provided'\n )\n }\n usage = context.customUsage\n } else {\n var place\n if (statMode.length === 2) {\n place = statMode.toUpperCase()\n } else {\n place = statMode.toLowerCase()\n }\n env.loadCountry(browserslist.usage, place, browserslist.data)\n usage = browserslist.usage[place]\n }\n }\n var versions = Object.keys(usage).sort(function (a, b) {\n return usage[b] - usage[a]\n })\n var coveraged = 0\n var result = []\n var version\n for (var i = 0; i <= versions.length; i++) {\n version = versions[i]\n if (usage[version] === 0) break\n coveraged += usage[version]\n result.push(version)\n if (coveraged >= coverage) break\n }\n return result\n}", "label": 1, "label_name": "safe"} -{"code": " public function serialize()\n {\n return serialize($this->data);\n }", "label": 0, "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, "label_name": "vulnerable"} -{"code": "export function DefaultConfig() {\n return defaultConfig;\n}", "label": 1, "label_name": "safe"} -{"code": "static void snd_timer_user_ccallback(struct snd_timer_instance *timeri,\n\t\t\t\t int event,\n\t\t\t\t struct timespec *tstamp,\n\t\t\t\t unsigned long resolution)\n{\n\tstruct snd_timer_user *tu = timeri->callback_data;\n\tstruct snd_timer_tread r1;\n\tunsigned long flags;\n\n\tif (event >= SNDRV_TIMER_EVENT_START &&\n\t event <= SNDRV_TIMER_EVENT_PAUSE)\n\t\ttu->tstamp = *tstamp;\n\tif ((tu->filter & (1 << event)) == 0 || !tu->tread)\n\t\treturn;\n\tmemset(&r1, 0, sizeof(r1));\n\tr1.event = event;\n\tr1.tstamp = *tstamp;\n\tr1.val = resolution;\n\tspin_lock_irqsave(&tu->qlock, flags);\n\tsnd_timer_user_append_to_tqueue(tu, &r1);\n\tspin_unlock_irqrestore(&tu->qlock, flags);\n\tkill_fasync(&tu->fasync, SIGIO, POLL_IN);\n\twake_up(&tu->qchange_sleep);\n}", "label": 1, "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 ' + requisition.foreignSource + ' has been updated.');\n },\n $scope.errorHandler\n );\n };", "label": 0, "label_name": "vulnerable"} -{"code": " public function pinCommentAction(CustomerComment $comment, string $token, CsrfTokenManagerInterface $csrfTokenManager)\n {\n $customerId = $comment->getCustomer()->getId();\n\n if (!$csrfTokenManager->isTokenValid(new CsrfToken('customer.pin_comment', $token))) {\n $this->flashError('action.csrf.error');\n\n return $this->redirectToRoute('customer_details', ['id' => $customerId]);\n }\n\n $csrfTokenManager->refreshToken($token);\n\n $comment->setPinned(!$comment->isPinned());\n try {\n $this->repository->saveComment($comment);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n\n return $this->redirectToRoute('customer_details', ['id' => $customerId]);\n }", "label": 1, "label_name": "safe"} -{"code": "\t\t\terrorHandler: function (key, msg) {\n\t\t\t\terrors[key] = msg\n\t\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " function &getAll(&$dbh, $proposalId)\n {\n $sql = \"SELECT *, UNIX_TIMESTAMP(timestamp) AS timestamp FROM package_proposal_votes WHERE pkg_prop_id = \". $dbh->quoteSmart($proposalId) .\" ORDER BY timestamp ASC\";\n $res = $dbh->query($sql);\n if (DB::isError($res)) {\n return $res;\n }\n $votes = array();\n while ($set = $res->fetchRow(DB_FETCHMODE_ASSOC)) {\n $set['reviews'] = unserialize($set['reviews']);\n $votes[$set['user_handle']] = new ppVote($set);\n }\n return $votes;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "Mocha.prototype.run = function(fn) {\n if (this.files.length) this.loadFiles();\n var suite = this.suite;\n var options = this.options;\n var runner = new exports.Runner(suite);\n var reporter = new this._reporter(runner);\n runner.ignoreLeaks = false !== options.ignoreLeaks;\n runner.asyncOnly = options.asyncOnly;\n if (options.grep) runner.grep(options.grep, options.invert);\n if (options.globals) runner.globals(options.globals);\n if (options.growl) this._growl(runner, reporter);\n exports.reporters.Base.useColors = options.useColors;\n exports.reporters.Base.inlineDiffs = options.useInlineDiffs;\n return runner.run(fn);\n};", "label": 1, "label_name": "safe"} -{"code": "mxCodecRegistry.register(function(){var a=new mxObjectCodec(new mxCell,[\"children\",\"edges\",\"overlays\",\"mxTransient\"],[\"parent\",\"source\",\"target\"]);a.isCellCodec=function(){return!0};a.isNumericAttribute=function(b,c,d){return\"value\"!==c.nodeName&&mxObjectCodec.prototype.isNumericAttribute.apply(this,arguments)};a.isExcluded=function(b,c,d,e){return mxObjectCodec.prototype.isExcluded.apply(this,arguments)||e&&\"value\"==c&&mxUtils.isNode(d)};a.afterEncode=function(b,c,d){if(null!=c.value&&mxUtils.isNode(c.value)){var e=", "label": 1, "label_name": "safe"} -{"code": "static inline int ip_ufo_append_data(struct sock *sk,\n\t\t\tstruct sk_buff_head *queue,\n\t\t\tint getfrag(void *from, char *to, int offset, int len,\n\t\t\t int odd, struct sk_buff *skb),\n\t\t\tvoid *from, int length, int hh_len, int fragheaderlen,\n\t\t\tint transhdrlen, int maxfraglen, unsigned int flags)\n{\n\tstruct sk_buff *skb;\n\tint err;\n\n\t/* There is support for UDP fragmentation 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(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\n\t\tif (skb == NULL)\n\t\t\treturn err;\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\n\t\t/* specify the length of each IP datagram fragment */\n\t\tskb_shinfo(skb)->gso_size = maxfraglen - fragheaderlen;\n\t\tskb_shinfo(skb)->gso_type = SKB_GSO_UDP;\n\t\t__skb_queue_tail(queue, skb);\n\t}\n\n\treturn skb_append_datato_frags(sk, skb, getfrag, from,\n\t\t\t\t (length - transhdrlen));\n}", "label": 0, "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, "label_name": "vulnerable"} -{"code": " public function checkCode($secret, $code, $discrepancy = 3)\n {\n /*\n $time = floor(time() / 30);\n for ($i = -1; $i <= 1; $i++) {\n if ($this->getCode($secret, $time + $i) == $code) {\n return true;\n }\n }\n \t\t*/\n \t$currentTimeSlice = floor(time() / 30);\n\n \tfor ($i = -$discrepancy; $i <= $discrepancy; $i++) {\n \t\t$calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);\n \t\tif ($calculatedCode == $code ) {\n \t\t\treturn true;\n \t\t}\n \t}\n\n return false;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\tresize = function(init) {\n\t\t\t\tvar initHeight = function() {\n\t\t\t\t\tvar h = 0;\n\t\t\t\t\twrapper.siblings('div.elfinder-panel:visible').each(function() {\n\t\t\t\t\t\th += $(this).outerHeight(true);\n\t\t\t\t\t});\n\t\t\t\t\twrapper.height(wz.height() - h - wrapper._padding);\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tinit && initHeight();\n\t\t\t\t\n\t\t\t\trestm && clearTimeout(restm);\n\t\t\t\trestm = setTimeout(function(){\n\t\t\t\t\t!init && initHeight();\n\t\t\t\t\tvar wph, cwdoh;\n\t\t\t\t\t// fix cwd height if it less then wrapper\n\t\t\t\t\tcwd.css('height', 'auto');\n\t\t\t\t\twph = wrapper[0].clientHeight - parseInt(wrapper.css('padding-top')) - parseInt(wrapper.css('padding-bottom')),\n\t\t\t\t\tcwdoh = cwd.outerHeight(true);\n\t\t\t\t\tif (cwdoh < wph) {\n\t\t\t\t\t\tcwd.height(wph);\n\t\t\t\t\t}\n\t\t\t\t}, 20);\n\t\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\tsuccess: function() {\n\t\t\t\t\t$('#chatroom').append('

[' + getDateString() + '] [whisper to ' + display + '] ' + escapeXmlTags(result));\n\t\t\t\t\t$('#chatroom').get(0).scrollTop = $('#chatroom').get(0).scrollHeight;\n\t\t\t\t}", "label": 1, "label_name": "safe"} -{"code": " foreach ($day as $extevent) {\n $event_cache = new stdClass();\n $event_cache->feed = $extgcalurl;\n $event_cache->event_id = $extevent->event_id;\n $event_cache->title = $extevent->title;\n $event_cache->body = $extevent->body;\n $event_cache->eventdate = $extevent->eventdate->date;\n if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)\n $event_cache->dateFinished = $extevent->dateFinished;\n if (isset($extevent->eventstart))\n $event_cache->eventstart = $extevent->eventstart;\n if (isset($extevent->eventend))\n $event_cache->eventend = $extevent->eventend;\n if (isset($extevent->is_allday))\n $event_cache->is_allday = $extevent->is_allday;\n $found = false;\n if ($extevent->eventdate->date < $start) // prevent duplicating events crossing month boundaries\n $found = $db->selectObject('event_cache','feed=\"'.$extgcalurl.'\" AND event_id=\"'.$event_cache->event_id.'\" AND eventdate='.$event_cache->eventdate);\n if (!$found)\n $db->insertObject($event_cache,'event_cache');\n }", "label": 1, "label_name": "safe"} -{"code": "get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_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 *)ip6t_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 ip6t_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->ipv6)) {\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_IP6_TRACE_COMMENT_POLICY]\n\t\t\t\t: comments[NF_IP6_TRACE_COMMENT_RETURN];\n\t\t}\n\t\treturn 1;\n\t} else\n\t\t(*rulenum)++;\n\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def set_permissions\n unless @permissions_set\n @permissions_set = true\n resource[:configure_permission] ||= configure_permission\n resource[:read_permission] ||= read_permission\n resource[:write_permission] ||= write_permission\n rabbitmqctl('set_permissions', '-p', should_vhost, should_user,\n resource[:configure_permission], resource[:write_permission],\n resource[:read_permission]\n )\n end\n end", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " public static int getStatusCode(HttpURLConnection conn) {\n try {\n return conn.getResponseCode();\n } catch (IOException e) {\n throw ErrorUtil\n .createCommandException(\"connection to the remote repository host failed: \" + e.getMessage());\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "void nodeRename(Proxy &node, const RegexMatchConfigs &rename_array, extra_settings &ext)\n{\n std::string &remark = node.Remark, original_remark = node.Remark, returned_remark, real_rule;\n\n for(const RegexMatchConfig &x : rename_array)\n {\n if(!x.Script.empty() && ext.authorized)\n {\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 rename = (std::function) ctx.eval(\"rename\");\n returned_remark = rename(node);\n if(!returned_remark.empty())\n remark = returned_remark;\n }\n catch (qjs::exception)\n {\n script_print_stack(ctx);\n }\n }, global.scriptCleanContext);\n continue;\n }\n if(applyMatcher(x.Match, real_rule, node) && real_rule.size())\n remark = regReplace(remark, real_rule, x.Replace);\n }\n if(remark.empty())\n remark = original_remark;\n return;\n}", "label": 1, "label_name": "safe"} -{"code": " protected function hmac($data, $key)\n {\n if (function_exists('hash_hmac')) {\n return hash_hmac('md5', $data, $key);\n }\n\n // The following borrowed from\n // http://php.net/manual/en/function.mhash.php#27225\n\n // RFC 2104 HMAC implementation for php.\n // Creates an md5 HMAC.\n // Eliminates the need to install mhash to compute a HMAC\n // by Lance Rushing\n\n $bytelen = 64; // byte length for md5\n if (strlen($key) > $bytelen) {\n $key = pack('H*', md5($key));\n }\n $key = str_pad($key, $bytelen, chr(0x00));\n $ipad = str_pad('', $bytelen, chr(0x36));\n $opad = str_pad('', $bytelen, chr(0x5c));\n $k_ipad = $key ^ $ipad;\n $k_opad = $key ^ $opad;\n\n return md5($k_opad . pack('H*', md5($k_ipad . $data)));\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct() {\n $this->parser = new HTMLPurifier_VarParser();\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " protected function getDefaultParameters()\n {\n return array(\n 'foo' => ('wiz'.$this->targetDirs[1]),\n 'bar' => __DIR__,\n 'baz' => (__DIR__.'/PhpDumperTest.php'),\n 'buz' => $this->targetDirs[2],\n );\n }", "label": 0, "label_name": "vulnerable"} -{"code": "PLANT_URL+\"/svg/\")+function(y){r=\"\";for(i=0;ithis.status)if(\"txt\"==e)g(this.response);else{var A=new FileReader;A.readAsDataURL(this.response);A.onloadend=function(z){var L=new Image;L.onload=\nfunction(){try{var M=L.width,n=L.height;if(0==M&&0==n){var x=A.result,K=x.indexOf(\",\"),B=decodeURIComponent(escape(atob(x.substring(K+1)))),F=mxUtils.parseXml(B).getElementsByTagName(\"svg\");0req.dev);\n\n if (!r->iov.iov_base) {\n r->buflen = SCSI_DMA_BUF_SIZE;\n r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);\n }\n r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);\n qemu_iovec_init_external(&r->qiov, &r->iov, 1);\n return r->qiov.size / 512;\n}", "label": 1, "label_name": "safe"} -{"code": " it 'should return a second factor prompt' do\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n response_body = CGI.unescapeHTML(response.body)\n\n expect(response_body).to include(I18n.t(\n \"login.second_factor_title\"\n ))\n\n expect(response_body).to_not include(I18n.t(\n \"login.invalid_second_factor_code\"\n ))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function testSetProperty($property, $changeKey)\n {\n $def = new DefinitionDecorator('foo');\n\n $getter = 'get'.ucfirst($property);\n $setter = 'set'.ucfirst($property);\n\n $this->assertNull($def->$getter());\n $this->assertSame($def, $def->$setter('foo'));\n $this->assertEquals('foo', $def->$getter());\n $this->assertEquals(array($changeKey => true), $def->getChanges());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testOnKernelResponseWithoutSession()\n {\n $tokenStorage = new TokenStorage();\n $tokenStorage->setToken(new UsernamePasswordToken('test1', 'pass1', 'phpunit'));\n $request = new Request();\n $request->attributes->set('_security_firewall_run', '_security_session');\n $session = new Session(new MockArraySessionStorage());\n $request->setSession($session);\n\n $event = new ResponseEvent(\n $this->createMock(HttpKernelInterface::class),\n $request,\n HttpKernelInterface::MAIN_REQUEST,\n new Response()\n );\n\n $listener = new ContextListener($tokenStorage, [], 'session', null, new EventDispatcher());\n $listener->onKernelResponse($event);\n\n $this->assertTrue($session->isStarted());\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "10)!==0)&&(a=-1);return a}:CKEDITOR.env.webkit?function(){var a=this.$.tabIndex;if(a==void 0){a=parseInt(this.getAttribute(\"tabindex\"),10);isNaN(a)&&(a=-1)}return a}:function(){return this.$.tabIndex},getText:function(){return this.$.textContent||this.$.innerText||\"\"},getWindow:function(){return this.getDocument().getWindow()},getId:function(){return this.$.id||null},getNameAtt:function(){return this.$.name||null},getName:function(){var a=this.$.nodeName.toLowerCase();if(CKEDITOR.env.ie&&!(document.documentMode>", "label": 1, "label_name": "safe"} -{"code": " def move\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n @item = Item.find(params[:id])\n\n unless params[:thetisBoxSelKeeper].nil?\n\n folder_id = params[:thetisBoxSelKeeper].split(':').last\n\n if Folder.check_user_auth(folder_id, @login_user, 'w', true)\n\n @item.update_attribute(:folder_id, folder_id)\n flash[:notice] = t('msg.move_success')\n else\n flash[:notice] = 'ERROR:' + t('folder.need_auth_to_write_in')\n end\n end\n\n render(:partial => 'ajax_move', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n\n flash[:notice] = 'ERROR:' + evar.to_s[0, 64]\n render(:partial => 'ajax_move', :layout => false)\n end", "label": 1, "label_name": "safe"} -{"code": " public static function loader() {\r\n $data = \"\";\r\n if (isset($_GET['page']) && $_GET['page'] == \"modules\") {\r\n if (isset($_GET['act'])) {\r\n\r\n if ($_GET['act'] == ACTIVATE) {\r\n\r\n if(!Token::isExist($_GET['token'])){\r\n $alertDanger[] = TOKEN_NOT_EXIST;\r\n }\r\n\r\n if(!isset($alertDanger)){\r\n self::activate($_GET['modules']);\r\n $GLOBALS['alertSuccess'] = MODULES_ACTIVATED;\r\n }else{\r\n $GLOBALS['alertDanger'] = $alertDanger;\r\n }\r\n }elseif($_GET['act'] == DEACTIVATE){\r\n if(!Token::isExist($_GET['token'])){\r\n $alertDanger[] = TOKEN_NOT_EXIST;\r\n }\r\n\r\n if(!isset($alertDanger)){\r\n self::deactivate($_GET['modules']);\r\n $GLOBALS['alertSuccess'] = MODULES_DEACTIVATED;\r\n }else{\r\n $GLOBALS['alertDanger'] = $alertDanger;\r\n }\r\n }elseif ($_GET['act'] == 'remove') {\r\n if(!Token::isExist($_GET['token'])){\r\n $alertDanger[] = TOKEN_NOT_EXIST;\r\n }\r\n if (Mod::isActive($_GET['modules'])) {\r\n $alertDanger[] = \"Module is Active. Please deactivate first.\";\r\n }\r\n if(!isset($alertDanger)){\r\n self::deactivate($_GET['modules']);\r\n Files::delTree(GX_MOD.\"/\".$_GET['modules']);\r\n $GLOBALS['alertSuccess'] = MODULES_DELETED;\r\n }else{\r\n $GLOBALS['alertDanger'] = $alertDanger;\r\n }\r\n }\r\n\r\n }\r\n }\r\n\r\n $json = Options::v('modules');\r\n $mods = json_decode($json, true);\r\n if (!is_array($mods) || $mods == \"\") {\r\n $mods = array();\r\n }\r\n foreach ($mods as $m) {\r\n if (self::exist($m)) {\r\n self::load($m);\r\n }\r\n\r\n }\r\n\r\n return $data;\r\n\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false)\n {\n $this->outputPrecision = $output_precision;\n $this->internalPrecision = $internal_precision;\n $this->bcmath = !$force_no_bcmath && function_exists('bcmul');\n }", "label": 1, "label_name": "safe"} -{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);\n expHistory::back();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " Status CalculateOutputIndex(OpKernelContext* context, int dimension,\n const vector& parent_output_index,\n INDEX_TYPE output_index_multiplier,\n INDEX_TYPE output_size,\n vector* result) {\n const RowPartitionTensor row_partition_tensor =\n GetRowPartitionTensor(context, dimension);\n auto partition_type = GetRowPartitionTypeByDimension(dimension);\n switch (partition_type) {\n case RowPartitionType::VALUE_ROWIDS:\n return CalculateOutputIndexValueRowID(\n row_partition_tensor, parent_output_index, output_index_multiplier,\n output_size, result);\n case RowPartitionType::ROW_SPLITS:\n if (row_partition_tensor.size() - 1 > parent_output_index.size()) {\n return errors::InvalidArgument(\n \"Row partition size is greater than output size: \",\n row_partition_tensor.size() - 1, \" > \",\n parent_output_index.size());\n }\n return CalculateOutputIndexRowSplit(\n row_partition_tensor, parent_output_index, output_index_multiplier,\n output_size, result);\n default:\n return errors::InvalidArgument(\n \"Unsupported partition type:\",\n RowPartitionTypeToString(partition_type));\n }\n }", "label": 1, "label_name": "safe"} -{"code": " it \"should exist\" do\n expect(Puppet::Parser::Functions.function(\"num2bool\")).to eq(\"function_num2bool\")\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function updatePreferences(Codendi_Request $request)\n {\n $request->valid(new Valid_String('cancel'));\n if (!$request->exist('cancel')) {\n $job_id = $request->get($this->widget_id . '_job_id');\n $sql = \"UPDATE plugin_hudson_widget SET job_id=\" . $job_id . \" WHERE owner_id = \" . $this->owner_id . \" AND owner_type = '\" . $this->owner_type . \"' AND id = \" . (int) $request->get('content_id');\n $res = db_query($sql);\n }", "label": 0, "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": 1, "label_name": "safe"} -{"code": " public function addAlias($key, $new_key)\n {\n $obj = new stdClass;\n $obj->key = $new_key;\n $obj->isAlias = true;\n $this->info[$key] = $obj;\n }", "label": 1, "label_name": "safe"} -{"code": "{},m.models.oRow,{src:c?\"dom\":\"data\",idx:e});f._aData=b;a.aoData.push(f);for(var g=a.aoColumns,j=0,i=g.length;j N ) {\n ret = parsed_params[ N ];\n }\n\n if ( ret > PARAM_MAX ) {\n ret = defaultval;\n }\n\n if ( ret < 1 ) ret = defaultval;\n\n return ret;\n}", "label": 1, "label_name": "safe"} -{"code": "static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_blkcipher rblkcipher;\n\n\tstrncpy(rblkcipher.type, \"givcipher\", sizeof(rblkcipher.type));\n\tstrncpy(rblkcipher.geniv, alg->cra_ablkcipher.geniv ?: \"\",\n\t\tsizeof(rblkcipher.geniv));\n\n\trblkcipher.blocksize = alg->cra_blocksize;\n\trblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize;\n\trblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize;\n\trblkcipher.ivsize = alg->cra_ablkcipher.ivsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,\n\t\t sizeof(struct crypto_report_blkcipher), &rblkcipher))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label": 1, "label_name": "safe"} -{"code": " public function testLengthCrashFixDisabled()\n {\n $this->config->set('HTML.MaxImgLength', null);\n $this->assertResult(\n '\"\"'\n );\n $this->assertResult(\n '\"\"'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " write: function (chunk, enc, cb) {\n parser.parse(chunk)\n cb() // nothing to do\n }", "label": 1, "label_name": "safe"} -{"code": "var InputToolTip = function() {\n WrappedElement.call(this);\n this._promptText = gettext('search or ask your question');\n};", "label": 1, "label_name": "safe"} -{"code": " it \"should return an array of keys when given a hash\" do\n result = scope.function_keys([{'a'=>1, 'b'=>2}])\n # =~ performs 'array with same elements' (set) matching\n # For more info see RSpec::Matchers::MatchArray\n expect(result).to match_array(['a','b'])\n end", "label": 0, "label_name": "vulnerable"} -{"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.get(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": 0, "label_name": "vulnerable"} -{"code": "def check_session_tracks(resource):\n \"\"\"Make sure that a user requesting a resource is authenticated and resource is in session IGV tracks\n\n Args:\n resource(str): a resource on the server or on a remote URL\n\n Returns\n True is user has access to resource else False\n \"\"\"\n # Check that user is logged in or that file extension is valid\n if current_user.is_authenticated is False:\n LOG.warning(\"Unauthenticated user requesting resource via remote_static\")\n return False\n if resource not in session.get(\"igv_tracks\", []):\n LOG.warning(f\"{resource} not in {session.get('igv_tracks', [])}\")\n return False\n return True", "label": 1, "label_name": "safe"} -{"code": " function update_option_master() { \n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $opt = new option_master($id);\n $oldtitle = $opt->title;\n \n $opt->update($this->params);\n \n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $opt->title) {\n \n }$db->sql('UPDATE '.$db->prefix.'option SET title=\"'.$opt->title.'\" WHERE option_master_id='.$opt->id);\n \n expHistory::back();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " \"should return unmodified object\": function(res) {\n assert.isObject(res);\n assert.isObject(res.a);\n assert.isString(res.a.b);\n assert.equal(res.a.b, 'c');\n },", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\t\trotateable = function(destroy) {\n\t\t\t\t\t\tif ($.fn.draggable && $.fn.resizable) {\n\t\t\t\t\t\t\tif (destroy) {\n\t\t\t\t\t\t\t\timgr.hide();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\timgr.show()\n\t\t\t\t\t\t\t\t\t.width(rwidth)\n\t\t\t\t\t\t\t\t\t.height(rheight)\n\t\t\t\t\t\t\t\t\t.css('margin-top', (pheight-rheight)/2 + 'px')\n\t\t\t\t\t\t\t\t\t.css('margin-left', (pwidth-rwidth)/2 + 'px');\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": "def test_digest_object_stale():\n credentials = (\"joe\", \"password\")\n host = None\n request_uri = \"/digest/stale/\"\n headers = {}\n response = httplib2.Response({})\n response[\"www-authenticate\"] = (\n 'Digest realm=\"myrealm\", nonce=\"bd669f\", '\n 'algorithm=MD5, qop=\"auth\", stale=true'\n )\n response.status = 401\n content = b\"\"\n d = httplib2.DigestAuthentication(\n credentials, host, request_uri, headers, response, content, None\n )\n # Returns true to force a retry\n assert d.response(response, content)", "label": 0, "label_name": "vulnerable"} -{"code": "fa,la,ra){R.addItem(la,null,mxUtils.bind(this,function(){var u=new CreateGraphDialog(O,la,ra);O.showDialog(u.container,620,420,!0,!1);u.init()}),fa)};this.put(\"insertLayout\",new Menu(mxUtils.bind(this,function(R,fa){for(var la=0;la<]*>/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 = 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 return value;\n },", "label": 0, "label_name": "vulnerable"} -{"code": "func (web *Web) Main(fds [3]*os.File, _ []string) error {\n\trestore := shell.IncSHLVL()\n\tdefer restore()\n\tev := shell.MakeEvaler(fds[2])\n\n\th := httpHandler{ev}\n\n\thttp.HandleFunc(\"/\", h.handleMainPage)\n\thttp.HandleFunc(\"/execute\", h.handleExecute)\n\taddr := fmt.Sprintf(\"localhost:%d\", web.Port)\n\tlog.Println(\"going to listen\", addr)\n\terr := http.ListenAndServe(addr, nil)\n\n\tlog.Println(err)\n\treturn nil\n}", "label": 0, "label_name": "vulnerable"} -{"code": "struct pipe_inode_info *alloc_pipe_info(void)\n{\n\tstruct pipe_inode_info *pipe;\n\n\tpipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL);\n\tif (pipe) {\n\t\tunsigned long pipe_bufs = PIPE_DEF_BUFFERS;\n\t\tstruct user_struct *user = get_current_user();\n\n\t\tif (!too_many_pipe_buffers_hard(user)) {\n\t\t\tif (too_many_pipe_buffers_soft(user))\n\t\t\t\tpipe_bufs = 1;\n\t\t\tpipe->bufs = kzalloc(sizeof(struct pipe_buffer) * pipe_bufs, GFP_KERNEL);\n\t\t}\n\n\t\tif (pipe->bufs) {\n\t\t\tinit_waitqueue_head(&pipe->wait);\n\t\t\tpipe->r_counter = pipe->w_counter = 1;\n\t\t\tpipe->buffers = pipe_bufs;\n\t\t\tpipe->user = user;\n\t\t\taccount_pipe_buffers(pipe, 0, pipe_bufs);\n\t\t\tmutex_init(&pipe->mutex);\n\t\t\treturn pipe;\n\t\t}\n\t\tfree_uid(user);\n\t\tkfree(pipe);\n\t}\n\n\treturn NULL;\n}", "label": 1, "label_name": "safe"} -{"code": "ast2obj_type_ignore(void* _o)\n{\n type_ignore_ty o = (type_ignore_ty)_o;\n PyObject *result = NULL, *value = NULL;\n if (!o) {\n Py_INCREF(Py_None);\n return Py_None;\n }\n\n switch (o->kind) {\n case TypeIgnore_kind:\n result = PyType_GenericNew(TypeIgnore_type, NULL, NULL);\n if (!result) goto failed;\n value = ast2obj_int(o->v.TypeIgnore.lineno);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_lineno, value) == -1)\n goto failed;\n Py_DECREF(value);\n break;\n }\n return result;\nfailed:\n Py_XDECREF(value);\n Py_XDECREF(result);\n return NULL;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "a.div_overlay_no_check=new q({opacity:\"1\",id:\"no_check_over\",background:\"#fff url(\"+a.loadIconEmptyEditor+\") no-repeat 50% 50%\",target:a.OverlayPlace});c&&(D(a.dialog),a.dialog.setupContent(a.dialog))})}else a.dialog.hide()},onHide:function(){a.dataTemp=\"\"},contents:[{id:\"SpellTab\",label:\"SpellChecker\",accessKey:\"S\",elements:[{type:\"html\",id:\"banner\",label:\"banner\",style:\"\",html:\"

\"},{type:\"html\",id:\"Content\",label:\"spellContent\",html:\"\",setup:function(b){var b=a.iframeNumber+\"_\"+b._.currentTabId,\nc=document.getElementById(b);a.targetFromFrame[b]=c.contentWindow}},{type:\"hbox\",id:\"bottomGroup\",style:\"width:560px; margin: 0 auto;\",widths:[\"50%\",\"50%\"],children:[{type:\"hbox\",id:\"leftCol\",align:\"left\",width:\"50%\",children:[{type:\"vbox\",id:\"rightCol1\",widths:[\"50%\",\"50%\"],children:[{type:\"text\",id:\"text\",label:a.LocalizationLabel.ChangeTo.text+\":\",labelLayout:\"horizontal\",labelStyle:\"font: 12px/25px arial, sans-serif;\",width:\"140px\",\"default\":\"\",onShow:function(){a.textNode.SpellTab=this;a.LocalizationLabel.ChangeTo.instance=", "label": 1, "label_name": "safe"} -{"code": "TfLiteStatus LogicalImpl(TfLiteContext* context, TfLiteNode* node,\n bool (*func)(bool, bool)) {\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 (data->requires_broadcast) {\n reference_ops::BroadcastBinaryFunction4DSlow(\n GetTensorShape(input1), GetTensorData(input1),\n GetTensorShape(input2), GetTensorData(input2),\n GetTensorShape(output), GetTensorData(output), func);\n } else {\n reference_ops::BinaryFunction(\n GetTensorShape(input1), GetTensorData(input1),\n GetTensorShape(input2), GetTensorData(input2),\n GetTensorShape(output), GetTensorData(output), func);\n }\n\n return kTfLiteOk;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "TagSearch.prototype.reset = function() {\n if (this.getIsRunning() === false) {\n this.setQuery('');\n this._toolTip.show();\n this._xButton.hide();\n this.runSearch();\n this._element.focus();\n }\n};", "label": 1, "label_name": "safe"} -{"code": "function deleteDomain() {\n var tr = $(this).closest(\"tr\");\n var id = tr.attr(\"data-id\");\n var domain = utils.escapeHtml(tr.find(\"#domain_\" + id).text());\n var type = tr.find(\"#type_\" + id).val();\n\n var domainRegex;\n if (type === \"0\" || type === \"1\") {\n domainRegex = \"domain\";\n } else if (type === \"2\" || type === \"3\") {\n domainRegex = \"regex\";\n }\n\n utils.disableAll();\n utils.showAlert(\"info\", \"\", \"Deleting \" + domainRegex + \"...\", domain);\n $.ajax({\n url: \"scripts/pi-hole/php/groups.php\",\n method: \"post\",\n dataType: \"json\",\n data: { action: \"delete_domain\", id: id, token: token },\n success: function (response) {\n utils.enableAll();\n if (response.success) {\n utils.showAlert(\n \"success\",\n \"far fa-trash-alt\",\n \"Successfully deleted \" + domainRegex,\n domain\n );\n table.row(tr).remove().draw(false).ajax.reload(null, false);\n } else {\n utils.showAlert(\n \"error\",\n \"\",\n \"Error while deleting \" + domainRegex + \" with ID \" + id,\n response.message\n );\n }\n },\n error: function (jqXHR, exception) {\n utils.enableAll();\n utils.showAlert(\n \"error\",\n \"\",\n \"Error while deleting \" + domainRegex + \" with ID \" + id,\n jqXHR.responseText\n );\n console.log(exception); // eslint-disable-line no-console\n }\n });\n}", "label": 1, "label_name": "safe"} -{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n // figure out if should limit the results\n if (isset($this->params['limit'])) {\n $limit = $this->params['limit'] == 'none' ? null : $this->params['limit'];\n } else {\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n }\n $order = isset($this->config['order']) ? $this->config['order'] : 'publish DESC';\n\n // pull the news posts from the database\n $items = $this->news->find('all', $this->aggregateWhereClause(), $order);\n\n // merge in any RSS news and perform the sort and limit the number of posts we return to the configured amount.\n if (!empty($this->config['pull_rss'])) $items = $this->mergeRssData($items);\n\n // setup the pagination object to paginate the news stories.\n $page = new expPaginator(array(\n 'records'=>$items,\n 'limit'=>$limit,\n 'order'=>$order,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'view'=>empty($this->params['view']) ? null : $this->params['view']\n ));\n\n assign_to_template(array(\n 'page'=>$page,\n 'items'=>$page->records,\n 'rank'=>($order==='rank')?1:0,\n 'params'=>$this->params,\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "\"url(\"+mxWindow.prototype.normalizeImage+\")\";aa.style.backgroundPosition=\"top center\";aa.style.backgroundRepeat=\"no-repeat\";aa.setAttribute(\"title\",\"Minimize\");var va=!1,la=mxUtils.bind(this,function(){P.innerHTML=\"\";if(!va){var ca=function(ia,ma,qa){ia=F(\"\",ia.funct,null,ma,ia,qa);ia.style.width=\"40px\";ia.style.opacity=\"0.7\";return ba(ia,null,\"pointer\")},ba=function(ia,ma,qa){null!=ma&&ia.setAttribute(\"title\",ma);ia.style.cursor=null!=qa?qa:\"default\";ia.style.margin=\"2px 0px\";P.appendChild(ia);mxUtils.br(P);\nreturn ia};ba(E.sidebar.createVertexTemplate(\"text;strokeColor=none;fillColor=none;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\",60,30,\"Text\",mxResources.get(\"text\"),!0,!1,null,!0,!0),mxResources.get(\"text\")+\" (\"+Editor.ctrlKey+\"+Shift+X)\");ba(E.sidebar.createVertexTemplate(\"shape=note;whiteSpace=wrap;html=1;backgroundOutline=1;fontColor=#000000;darkOpacity=0.05;fillColor=#FFF9B2;strokeColor=none;fillStyle=solid;direction=west;gradientDirection=north;gradientColor=#FFF2A1;shadow=1;size=20;pointerEvents=1;\",", "label": 1, "label_name": "safe"} -{"code": " public void HandleRightMouseUp()\n {\n var inputDesktop = new Desktop();\n inputDesktop.OpenInput();\n var setCurrent = Desktop.SetCurrent(inputDesktop);\n if (setCurrent)\n {\n new InputSimulator().Mouse.RightButtonUp();\n }\n\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def should_user\n if @should_user\n @should_user\n else\n @should_user = resource[:name].split('@')[0]\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public static function setUpBeforeClass()\n {\n self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');\n require_once self::$fixturesPath.'/includes/foo.php';\n require_once self::$fixturesPath.'/includes/ProjectExtension.php';\n }", "label": 0, "label_name": "vulnerable"} -{"code": "if(null!=P&&null!=P.originalSrc)if(!G)P={src:P.originalSrc};else if(G&&null!=this.themes&&\"darkTheme\"==this.defaultThemeName){var J=this.stylesheet,F=this.shapeForegroundColor,H=this.shapeBackgroundColor;this.stylesheet=this.getDefaultStylesheet();this.shapeBackgroundColor=\"#ffffff\";this.shapeForegroundColor=\"#000000\";P=d.createImageForPageLink(P.originalSrc);this.shapeBackgroundColor=H;this.shapeForegroundColor=F;this.stylesheet=J}return P};var x=this.clearDefaultStyle;this.clearDefaultStyle=function(){x.apply(this,\narguments)};this.isOffline()||\"undefined\"===typeof window.EditDataDialog||(EditDataDialog.placeholderHelpLink=\"https://www.diagrams.net/doc/faq/predefined-placeholders\");if(/viewer\\.diagrams\\.net$/.test(window.location.hostname)||/embed\\.diagrams\\.net$/.test(window.location.hostname))this.editor.editBlankUrl=\"https://app.diagrams.net/\";var y=d.editor.getEditBlankUrl;this.editor.getEditBlankUrl=function(E){E=null!=E?E:\"\";\"1\"==urlParams.dev&&(E+=(0DirectLex = new HTMLPurifier_Lexer_DirectLex();\n }", "label": 1, "label_name": "safe"} -{"code": " public function testIgnoreExtraSpaceWithLeadingInlineNode()\n {\n $this->assertResult(\n'Par1a\n\n\n\nPar2',\n'

Par1a

\n\n

Par2

'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " returnTo: new URL('/foo', withoutApi.baseURL).toString()\n });\n });", "label": 1, "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, "label_name": "safe"} -{"code": " protected void afterFeaturesReceived() throws NotConnectedException, InterruptedException {\n StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);\n if (startTlsFeature != null) {\n if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {\n notifyConnectionError(new SecurityRequiredByServerException());\n return;\n }\n\n if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {\n sendNonza(new StartTls());\n }\n }\n\n if (getSASLAuthentication().authenticationSuccessful()) {\n // If we have received features after the SASL has been successfully completed, then we\n // have also *maybe* received, as it is an optional feature, the compression feature\n // from the server.\n maybeCompressFeaturesReceived.reportSuccess();\n }\n }", "label": 1, "label_name": "safe"} -{"code": "function timezoneToOffset(timezone, fallback) {\n // IE/Edge do not \"understand\" colon (`:`) in timezone\n timezone = timezone.replace(ALL_COLONS, '');\n var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;\n return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_addElement()\n {\n $module = new HTMLPurifier_HTMLModule();\n $def = $module->addElement(\n 'a', 'Inline', 'Optional: #PCDATA', array('Common'),\n array(\n 'href' => 'URI'\n )\n );\n\n $module2 = new HTMLPurifier_HTMLModule();\n $def2 = new HTMLPurifier_ElementDef();\n $def2->content_model = '#PCDATA';\n $def2->content_model_type = 'optional';\n $def2->attr = array(\n 'href' => 'URI',\n 0 => array('Common')\n );\n $module2->info['a'] = $def2;\n $module2->elements = array('a');\n $module2->content_sets['Inline'] = 'a';\n\n $this->assertIdentical($module, $module2);\n $this->assertIdentical($def, $def2);\n $this->assertReference($def, $module->info['a']);\n\n }", "label": 1, "label_name": "safe"} -{"code": " it 'should allow me to set set-mark with mask' do\n @resource[:set_mark] = '0x3e8/0xffffffff'\n @resource[:set_mark].should == '0x3e8/0xffffffff'\n end", "label": 0, "label_name": "vulnerable"} -{"code": "static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_hash rhash;\n\tstruct shash_alg *salg = __crypto_shash_alg(alg);\n\n\tsnprintf(rhash.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"shash\");\n\trhash.blocksize = alg->cra_blocksize;\n\trhash.digestsize = salg->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, "label_name": "vulnerable"} -{"code": "\tpublic function __construct() {\r\n\t\t$opts = array(\r\n\t\t\t'accesskey' => '',\r\n\t\t\t'secretkey' => '',\r\n\t\t\t'bucket' => '',\r\n\t\t\t'tmpPath' => '',\r\n\t\t);\r\n\t\t$this->options = array_merge($this->options, $opts); \r\n\t\t$this->options['mimeDetect'] = 'internal';\r\n\r\n\t}\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask($task);\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label": 1, "label_name": "safe"} -{"code": " public function border($width, $color = null)\n {\n $this->border_width = is_numeric($width) ? intval($width) : 0;\n $this->border_color = is_null($color) ? '#000000' : $color;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tif rf, ok := ret.Get(0).(func(string, kube.ResourceKey, func(v1alpha1.ResourceNode, string)) error); ok {\n\t\tr0 = rf(server, key, action)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "label": 0, "label_name": "vulnerable"} -{"code": "process_demand_active(STREAM s)\n{\n\tuint8 type;\n\tuint16 len_src_descriptor, len_combined_caps;\n\tstruct stream packet = *s;\n\n\t/* at this point we need to ensure that we have ui created */\n\trd_create_ui();\n\n\tin_uint32_le(s, g_rdp_shareid);\n\tin_uint16_le(s, len_src_descriptor);\n\tin_uint16_le(s, len_combined_caps);\n\n\tif (!s_check_rem(s, len_src_descriptor))\n\t{\n\t\trdp_protocol_error(\"rdp_demand_active(), consume of source descriptor from stream would overrun\", &packet);\n\t}\n\tin_uint8s(s, len_src_descriptor);\n\n\tlogger(Protocol, Debug, \"process_demand_active(), shareid=0x%x\", g_rdp_shareid);\n\n\trdp_process_server_caps(s, len_combined_caps);\n\n\trdp_send_confirm_active();\n\trdp_send_synchronise();\n\trdp_send_control(RDP_CTL_COOPERATE);\n\trdp_send_control(RDP_CTL_REQUEST_CONTROL);\n\trdp_recv(&type);\t/* RDP_PDU_SYNCHRONIZE */\n\trdp_recv(&type);\t/* RDP_CTL_COOPERATE */\n\trdp_recv(&type);\t/* RDP_CTL_GRANT_CONTROL */\n\trdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0,\n\t\t g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0);\n\n\tif (g_rdp_version >= RDP_V5)\n\t{\n\t\trdp_enum_bmpcache2();\n\t\trdp_send_fonts(3);\n\t}\n\telse\n\t{\n\t\trdp_send_fonts(1);\n\t\trdp_send_fonts(2);\n\t}\n\n\trdp_recv(&type);\t/* RDP_PDU_UNKNOWN 0x28 (Fonts?) */\n\treset_order_state();\n}", "label": 1, "label_name": "safe"} -{"code": " public function generateKey($config) {\n return $config->version . ',' . // possibly replace with function calls\n $config->getBatchSerial($this->type) . ',' .\n $config->get($this->type . '.DefinitionRev');\n }", "label": 1, "label_name": "safe"} -{"code": "def have_printed(what)\n HavePrintedMatcher.new(what)\nend", "label": 0, "label_name": "vulnerable"} -{"code": "this.init=function(){function G(H){if(null!=H){var S=H.getAttribute(\"background\");if(null==S||\"\"==S||S==mxConstants.NONE)S=Editor.isDarkMode()?\"transparent\":\"#ffffff\";B.style.backgroundColor=S;(new mxCodec(H.ownerDocument)).decode(H,I.getModel());I.maxFitScale=1;I.fit(8);I.center()}return H}function P(H){null!=H&&(H=G(Editor.parseDiagramNode(H)));return H}mxEvent.addListener(E,\"change\",function(H){z=parseInt(E.value);P(L[z]);mxEvent.consume(H)});if(\"mxfile\"==t.nodeName){var J=t.getElementsByTagName(\"diagram\");", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public function getFrequency($tagName)\n {\n if (!isset($this->frequencies[$tagName])) {\n return 0;\n } else {\n return $this->frequencies[$tagName];\n }\n }", "label": 1, "label_name": "safe"} -{"code": " it 'should accept a user name' do\n @user[:name].should == 'test'\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tdrag : function(e, ui) {\n\t\t\tvar helper = ui.helper;\n\t\t\tif (helper.data('refreshPositions') && $(this).draggable('instance')) {\n\t\t\t\tif (helper.data('refreshPositions') > 0) {\n\t\t\t\t\t$(this).draggable('option', { refreshPositions : true });\n\t\t\t\t\thelper.data('refreshPositions', -1);\n\t\t\t\t} else {\n\t\t\t\t\t$(this).draggable('option', { refreshPositions : false });\n\t\t\t\t\thelper.data('refreshPositions', null);\n\t\t\t\t}\n\t\t\t}\n\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " QUInt16() : value(0) {}", "label": 1, "label_name": "safe"} -{"code": "\tpublic function &storeicms_ipf_Object($debug=false, $xparam = false) {\n\t\t$ret =& $this->storeFromDefaultForm('', '', null, $debug, $xparam);\n\n\t\treturn $ret;\n\t}", "label": 1, "label_name": "safe"} -{"code": "if(jQuery)(function(jQuery){jQuery.extend(jQuery.fn,{uploadify:function(options){jQuery(this).each(function(){settings=jQuery.extend({id:jQuery(this).attr('id'),uploader:'uploadify.swf',script:'uploadify.php',expressInstall:null,folder:'',height:30,width:110,cancelImg:'cancel.png',wmode:'opaque',scriptAccess:'sameDomain',fileDataName:'Filedata',method:'POST',queueSizeLimit:999,simUploadLimit:1,queueID:false,displayData:'percentage',onInit:function(){},onSelect:function(){},onQueueFull:function(){},onCheck:function(){},onCancel:function(){},onError:function(){},onProgress:function(){},onComplete:function(){},onAllComplete:function(){}},options);var pagePath=location.pathname;pagePath=pagePath.split('/');pagePath.pop();pagePath=pagePath.join('/')+'/';var data={};data.uploadifyID=settings.id;data.pagepath=pagePath;if(settings.buttonImg)data.buttonImg=escape(settings.buttonImg);if(settings.buttonText)data.buttonText=escape(settings.buttonText);if(settings.rollover)data.rollover=true;data.script=settings.script;data.folder=escape(settings.folder);if(settings.scriptData){var scriptDataString='';for(var name in settings.scriptData){scriptDataString+='&'+name+'='+settings.scriptData[name];}", "label": 0, "label_name": "vulnerable"} -{"code": "void check_option(const char *opt)\n{\n\tint i;\n\tfor (i = 0; invalid_opts[i] != NULL; i++)\n\t\tif (strcmp(opt, invalid_opts[i]) == 0)\n\t\t\terrx(1, \"%s: not allowed option\", opt);\n}", "label": 1, "label_name": "safe"} -{"code": " private function catchWarning ($errno, $errstr, $errfile, $errline) {\n $this->error[] = array(\n 'error' => \"Connecting to the POP3 server raised a PHP warning: \",\n 'errno' => $errno,\n 'errstr' => $errstr\n );\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function F(){};", "label": 0, "label_name": "vulnerable"} -{"code": "PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_pli(\n\t\t\t\t\tconst void *buf,\n\t\t\t\t\tpj_size_t length)\n{\n pjmedia_rtcp_fb_common *hdr = (pjmedia_rtcp_fb_common*) buf;\n\n PJ_ASSERT_RETURN(buf, PJ_EINVAL);\n\n if (length < 12)\n \treturn PJ_ETOOSMALL;\n\n /* PLI uses pt==RTCP_PSFB and FMT==1 */\n if (hdr->rtcp_common.pt != RTCP_PSFB || hdr->rtcp_common.count != 1)\n\treturn PJ_ENOTFOUND;\n\n return PJ_SUCCESS;\n}", "label": 1, "label_name": "safe"} -{"code": "\tfunction manage_vendors () {\n\t expHistory::set('viewable', $this->params);\n\t\t$vendor = new vendor();\n\n\t\t$vendors = $vendor->find('all');\n\t\tassign_to_template(array(\n 'vendors'=>$vendors\n ));\n\t}", "label": 1, "label_name": "safe"} -{"code": " def users(name, vhost)\n self.class.users(name, vhost)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " protected function assertParse($file, $expect)\n {\n $result = $this->parser->parseFile(dirname(__FILE__) . '/StringHashParser/' . $file);\n $this->assertIdentical($result, $expect);\n }", "label": 1, "label_name": "safe"} -{"code": " onNodeTextChange: function(node, text, oldText) {\n if (node.attributes && node.attributes.filterPanel) {\n node.attributes.filterPanel.setTitle(text);\n }\n },", "label": 0, "label_name": "vulnerable"} -{"code": "hphp_libxml_input_buffer_noload(const char *URI, xmlCharEncoding enc) {\n return nullptr;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public static function create($config, $schema = null) {\n if ($config instanceof HTMLPurifier_Config) {\n // pass-through\n return $config;\n }\n if (!$schema) {\n $ret = HTMLPurifier_Config::createDefault();\n } else {\n $ret = new HTMLPurifier_Config($schema);\n }\n if (is_string($config)) $ret->loadIni($config);\n elseif (is_array($config)) $ret->loadArray($config);\n return $ret;\n }", "label": 1, "label_name": "safe"} -{"code": "\t\tprivate void submit_Click(object sender, EventArgs e)\r\n\t\t{\r\n\t\t\ttempFileName = \"justDelete_\" + Guid.NewGuid().ToString() + \".udt\";\r\n\t\t\tvar fileName = IOHelper.MapPath(SystemDirectories.Data + \"/\" + tempFileName);\r\n\t\t\ttempFile.Value = fileName;\r\n\r\n\t\t\tdocumentTypeFile.PostedFile.SaveAs(fileName);\r\n\r\n\t\t\tvar xd = new XmlDocument();\r\n\t\t\txd.Load(fileName);\r\n\t\t\tdtName.Text = xd.DocumentElement.SelectSingleNode(\"//DocumentType/Info/Name\").FirstChild.Value;\r\n\t\t\tdtAlias.Text = xd.DocumentElement.SelectSingleNode(\"//DocumentType/Info/Alias\").FirstChild.Value;\r\n\r\n\t\t\tWizard.Visible = false;\r\n\t\t\tdone.Visible = false;\r\n\t\t\tConfirm.Visible = true;\r\n\t\t}\r", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should return the size of a string\" do\n result = scope.function_size([\"asdf\"])\n expect(result).to(eq(4))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function testPropertyParametersShouldBeResolved()\n {\n $this->assertSame(array('bar' => 'baz'), $this->fooDefinition->getProperties());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public void existingDocumentFromUIDeprecated() 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\n when(mockRequest.getParameter(\"space\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"page\")).thenReturn(\"Y\");\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 since the deprecated parameters were creating terminal documents by default.\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def test_get_student_progress_url_nostudent(self):\n \"\"\" Test that the endpoint 400's when requesting an unknown email. \"\"\"\n url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 400)", "label": 0, "label_name": "vulnerable"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link = $this->getInternalTaskLink($task);\n\n $this->response->html($this->template->render('task_internal_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label": 1, "label_name": "safe"} -{"code": " protected function styleCallback($matches) {\n $this->_styleMatches[] = $matches[1];\n }", "label": 1, "label_name": "safe"} -{"code": " public function filter(Filters\\FilterInterface $filter)\n {\n return $filter->applyFilter($this);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected function sendCommand($command, $commandstring, $expect)\n {\n if (!$this->connected()) {\n $this->setError(\"Called $command without being connected\");\n return false;\n }\n $this->client_send($commandstring . self::CRLF);\n\n $this->last_reply = $this->get_lines();\n // Fetch SMTP code and possible error code explanation\n $matches = array();\n if (preg_match(\"/^([0-9]{3})[ -](?:([0-9]\\\\.[0-9]\\\\.[0-9]) )?/\", $this->last_reply, $matches)) {\n $code = $matches[1];\n $code_ex = (count($matches) > 2 ? $matches[2] : null);\n // Cut off error code from each response line\n $detail = preg_replace(\n \"/{$code}[ -]\".($code_ex ? str_replace('.', '\\\\.', $code_ex).' ' : '').\"/m\",\n '',\n $this->last_reply\n );\n } else {", "label": 1, "label_name": "safe"} -{"code": " private function getProxyInstantiator()\n {\n if (!$this->proxyInstantiator) {\n $this->proxyInstantiator = new RealServiceInstantiator();\n }\n\n return $this->proxyInstantiator;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function info_application($bp_name, $bdd){\n\t$sql = \"select * from bp where name = ?\";\n\t$req = $bdd->prepare($sql);\n\t$req->execute(array($bp_name));\n\t$info = $req->fetch();\n\techo json_encode($info);\n}", "label": 1, "label_name": "safe"} -{"code": "\tprotected function _basename($path) {\n\t\t$parts = explode($this->separator, trim($path, $this->separator));\n\t\treturn array_pop($parts);\n\t}", "label": 1, "label_name": "safe"} -{"code": "\tprotected function _filePutContents($path, $content) {\n\t\treturn $this->query(sprintf('UPDATE %s SET content=\"%s\", size=%d, mtime=%d WHERE id=%d LIMIT 1', $this->tbf, $this->db->real_escape_string($content), strlen($content), time(), $path));\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def update_config\n Log.add_info(request, params.inspect)\n\n @yaml = ApplicationHelper.get_config_yaml\n\n unless params[:desktop].nil? or params[:desktop].empty?\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": 0, "label_name": "vulnerable"} -{"code": "\t\t\tsync = function(start) {\n\t\t\t\tvar timeout;\n\t\t\t\tif (cwdOptions.syncMinMs && (start || syncInterval)) {\n\t\t\t\t\tstart && self.trigger('autosync', {action : 'start'});\n\t\t\t\t\ttimeout = Math.max(self.options.sync, cwdOptions.syncMinMs);\n\t\t\t\t\tsyncInterval && clearTimeout(syncInterval);\n\t\t\t\t\tsyncInterval = setTimeout(function() {\n\t\t\t\t\t\tvar dosync = true, hash = cwd, cts;\n\t\t\t\t\t\tif (cwdOptions.syncChkAsTs && (cts = files[hash].ts)) {\n\t\t\t\t\t\t\tself.request({\n\t\t\t\t\t\t\t\tdata : {cmd : 'info', targets : [hash], compare : cts, reload : 1},\n\t\t\t\t\t\t\t\tpreventDefault : true\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.done(function(data) {\n\t\t\t\t\t\t\t\tvar ts;\n\t\t\t\t\t\t\t\tdosync = true;\n\t\t\t\t\t\t\t\tif (data.compare) {\n\t\t\t\t\t\t\t\t\tts = data.compare;\n\t\t\t\t\t\t\t\t\tif (ts == cts) {\n\t\t\t\t\t\t\t\t\t\tdosync = false;\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\tif (dosync) {\n\t\t\t\t\t\t\t\t\tself.sync(hash).always(function() {\n\t\t\t\t\t\t\t\t\t\tif (ts) {\n\t\t\t\t\t\t\t\t\t\t\t// update ts for cache clear etc.\n\t\t\t\t\t\t\t\t\t\t\tfiles[hash].ts = ts;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tsync();\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tsync();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.fail(function(error, xhr) {\n\t\t\t\t\t\t\t\tif (error && xhr.status != 0) {\n\t\t\t\t\t\t\t\t\tself.error(error);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tsyncInterval = setTimeout(function() {\n\t\t\t\t\t\t\t\t\t\tsync();\n\t\t\t\t\t\t\t\t\t}, timeout);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself.sync(cwd, true).always(function() {\n\t\t\t\t\t\t\t\tsync();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}, timeout);\n\t\t\t\t}\n\t\t\t};", "label": 1, "label_name": "safe"} -{"code": " function edit() {\n global $template;\n\n parent::edit();\n $allforms = array();\n $allforms[\"\"] = gt('Disallow Feedback');\n // calculate which event date is the one being edited\n $event_key = 0;\n foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {\n \t if ($d->id == $this->params['date_id']) $event_key = $key;\n \t}\n\n assign_to_template(array(\n 'allforms' => array_merge($allforms, expTemplate::buildNameList(\"forms\", \"event/email\", \"tpl\", \"[!_]*\")),\n 'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,\n 'event_key' => $event_key,\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "def load(doc):\n code = config.retrieveBoilerplateFile(doc, \"bs-extensions\")\n exec(code, globals())", "label": 0, "label_name": "vulnerable"} -{"code": " public function session() {\n // Test if logged in, log in if not, log in.\n try {\n $this->assertElementPresent('css=ul#user-menu');\n } catch (PHPUnit_Framework_AssertionFailedError $e) {\n /* If this isn't the first time we've logged in, we have a problem;\n * the user should have been logged in throughout the life of the\n * test case class. Append t\n */\n if (!$this->firstLogin)\n array_push($this->verificationErrors, $e->toString());\n $this->firstLogin = false;\n $this->login();\n return 0;\n }\n try {\n $this->assertCorrectUser();\n } catch (PHPUnit_Framework_AssertionFailedError $e) {\n /**\n * The browser is logged in but not as the correct user.\n */\n $this->logout();\n $this->login();\n $this->firstLogin = false;\n return 0;\n }\n // Indicator of whether the session was already initialized properly\n return 1;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $column = $this->getColumn($project);\n\n if ($this->columnModel->remove($column['id'])) {\n $this->flash->success(t('Column removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this column.'));\n }\n\n $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));\n }", "label": 1, "label_name": "safe"} -{"code": " public AddOn GetAddOn(string addOnCode)\n {\n var addOn = new AddOn();\n\n var status = Client.Instance.PerformRequest(Client.HttpRequestMethod.Get,\n UrlPrefix + Uri.EscapeUriString(PlanCode) + \"/add_ons/\" + Uri.EscapeUriString(addOnCode),\n addOn.ReadXml);\n\n if (status != HttpStatusCode.OK) return null;\n\n // PlanCode is needed to update the AddOn\n // TODO: need a cleaner way of getting the plan code from xml\n // should be using the hrefs of the resources\n addOn.PlanCode = PlanCode;\n\n return addOn;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " value = value.replace(/href=\" *javascript\\:(.*?)\"/gi, function(m, $1) {\n return 'removed=\"\"';\n });", "label": 0, "label_name": "vulnerable"} -{"code": " fn detect_from(&mut self, from: &'a str, path: &mut Vec<&'a Spanning<&'a str>>) {\n self.visited.insert(from);\n\n if !self.spreads.contains_key(from) {\n return;\n }\n\n self.path_indices.insert(from, path.len());\n\n for node in &self.spreads[from] {\n let name = &node.item;\n let index = self.path_indices.get(name).cloned();\n\n if let Some(index) = index {\n let err_pos = if index < path.len() {\n path[index]\n } else {\n node\n };\n\n self.errors\n .push(RuleError::new(&error_message(name), &[err_pos.start]));\n } else if !self.visited.contains(name) {\n path.push(node);\n self.detect_from(name, path);\n path.pop();\n }\n }\n\n self.path_indices.remove(from);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def cluster_status_gui(session, cluster_name, dont_update_config=false)\n cluster_nodes = get_cluster_nodes(cluster_name)\n status = cluster_status_from_nodes(session, cluster_nodes, cluster_name)\n unless status\n return 403, 'Permission denied'\n end\n\n new_cluster_nodes = []\n new_cluster_nodes += status[:corosync_offline] if status[:corosync_offline]\n new_cluster_nodes += status[:corosync_online] if status[:corosync_online]\n new_cluster_nodes += status[:pacemaker_offline] if status[:pacemaker_offline]\n new_cluster_nodes += status[:pacemaker_online] if status[:pacemaker_online]\n new_cluster_nodes.uniq!\n\n if new_cluster_nodes.length > 0\n config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())\n if !(dont_update_config or config.cluster_nodes_equal?(cluster_name, new_cluster_nodes))\n old_cluster_nodes = config.get_nodes(cluster_name)\n $logger.info(\"Updating node list for: #{cluster_name} #{old_cluster_nodes}->#{new_cluster_nodes}\")\n config.update_cluster(cluster_name, new_cluster_nodes)\n sync_config = Cfgsync::PcsdSettings.from_text(config.text())\n # on version conflict just go on, config will be corrected eventually\n # by displaying the cluster in the web UI\n Cfgsync::save_sync_new_version(\n sync_config, get_corosync_nodes(), $cluster_name, true\n )\n return cluster_status_gui(session, cluster_name, true)\n end\n end\n return JSON.generate(status)\nend", "label": 0, "label_name": "vulnerable"} -{"code": " protected function getStorePath($key)\n {\n $r = new \\ReflectionObject($this->store);\n $m = $r->getMethod('getPath');\n $m->setAccessible(true);\n\n return $m->invoke($this->store, $key);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic void testUpdateMapper_serializade_withExpirationDate() {\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-until\");\n\t\tPersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, 60000);\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 = MapperDAO.fromXML(pMapper.getXmlConfiguration());\n\t\tAssert.assertTrue(objReloaded instanceof PersistentMapper);\n\t\tPersistentMapper sMapperReloaded = (PersistentMapper)objReloaded;\n\t\tAssert.assertEquals(\"mapper-to-persist-until\", sMapperReloaded.getKey());\n\t\tAssert.assertNotNull(loadedMapper.getExpirationDate());\n\t\t\n\t\t//update\n\t\tPersistentMapper sMapper2 = new PersistentMapper(\"mapper-to-update-until\");\n\t\tboolean updated = mapperDao.updateConfiguration(mapperId, sMapper2, 120000);\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 = MapperDAO.fromXML(loadedMapper2.getXmlConfiguration());\n\t\tAssert.assertTrue(objReloaded2 instanceof PersistentMapper);\n\t\tPersistentMapper sMapperReloaded2 = (PersistentMapper)objReloaded2;\n\t\tAssert.assertEquals(\"mapper-to-update-until\", sMapperReloaded2.getKey());\n\t\tAssert.assertNotNull(loadedMapper2.getExpirationDate());\n\t}", "label": 1, "label_name": "safe"} -{"code": "\t\t $controller = new $ctlname();\n\t\t if (method_exists($controller,'isSearchable') && $controller->isSearchable()) {\n//\t\t\t $mods[$controller->name()] = $controller->addContentToSearch();\n $mods[$controller->searchName()] = $controller->addContentToSearch();\n\t\t }\n\t }\n\n\t uksort($mods,'strnatcasecmp');\n\t assign_to_template(array(\n 'mods'=>$mods\n ));\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "$(\"#fc_addPage_parent_page_id\").val($(\".page_tree_open_options\").children(\"input[name=page_id]\").val());$(\".fc_side_add\").click()});$(\"select[id=fc_addPage_template]\").change(function(){var a={_cat_ajax:1,template:$(\"#fc_addPage_template\").val()};$.ajax({type:\"POST\",url:CAT_ADMIN_URL+\"/settings/ajax_get_template_variants.php\",dataType:\"json\",data:a,cache:!1,success:function(a,c,d){!0===a.success?($(this),$(\"#fc_default_template_variant\").empty(),0<$(a.variants).size()?($.each(a.variants,function(a,\nb){$(\"

\n\nevent->find('first', 'id=' . $this->params['id']);\n if ($item && $item->is_recurring == 1) {\n $event_remaining = false;\n $eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);\n foreach ($eventdates as $ed) {\n if (array_key_exists($ed->id, $this->params['dates'])) {\n $ed->delete();\n } else {\n $event_remaining = true;\n }\n }\n if (!$event_remaining) {\n $item->delete(); // model will also ensure we delete all event dates\n }\n expHistory::back();\n } else {\n notfoundController::handle_not_found();\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public function addLogMessage($string)\n {\n $this->log[] = $string;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "ka&&null!=ka.message?ka.message:mxResources.get(\"disconnected\")));mxEvent.consume(U)}));ea.setAttribute(\"title\",X);O.style.paddingRight=\"4px\";O.appendChild(ea)}}}};var y=App.prototype.updateButtonContainer;App.prototype.updateButtonContainer=function(){y.apply(this,arguments);if(null!=this.shareButton){var O=this.shareButton;O.style.cssText=\"display:inline-block;position:relative;box-sizing:border-box;margin-right:4px;cursor:pointer;\";O.className=\"geToolbarButton\";O.innerHTML=\"\";O.style.backgroundImage=\n\"url(\"+Editor.shareImage+\")\";O.style.backgroundPosition=\"center center\";O.style.backgroundRepeat=\"no-repeat\";O.style.backgroundSize=\"24px 24px\";O.style.height=\"24px\";O.style.width=\"24px\";\"1\"==urlParams.sketch&&(this.shareButton.style.display=\"none\")}null!=this.buttonContainer&&(this.buttonContainer.style.marginTop=\"-2px\",this.buttonContainer.style.paddingTop=\"4px\")};EditorUi.prototype.addEmbedButtons=function(){if(null!=this.buttonContainer&&\"1\"!=urlParams.embedInline){var O=document.createElement(\"div\");", "label": 0, "label_name": "vulnerable"} -{"code": "header_put_marker (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_marker */", "label": 0, "label_name": "vulnerable"} -{"code": " protected function generateVerifyCode()\n {\n if ($this->minLength > $this->maxLength) {\n $this->maxLength = $this->minLength;\n }\n if ($this->minLength < 3) {\n $this->minLength = 3;\n }\n if ($this->maxLength > 20) {\n $this->maxLength = 20;\n }\n $length = mt_rand($this->minLength, $this->maxLength);\n\n $letters = 'bcdfghjklmnpqrstvwxyz';\n $vowels = 'aeiou';\n $code = '';\n for ($i = 0; $i < $length; ++$i) {\n if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {\n $code .= $vowels[mt_rand(0, 4)];\n } else {\n $code .= $letters[mt_rand(0, 20)];\n }\n }\n\n return $code;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function buildControl() {\n $control = new colorcontrol();\n if (!empty($this->params['value'])) $control->value = $this->params['value'];\n if ($this->params['value'][0] != '#') $this->params['value'] = '#' . $this->params['value'];\n $control->default = $this->params['value'];\n if (!empty($this->params['hide'])) $control->hide = $this->params['hide'];\n if (isset($this->params['flip'])) $control->flip = $this->params['flip'];\n $this->params['name'] = !empty($this->params['name']) ? $this->params['name'] : '';\n $control->name = $this->params['name'];\n $this->params['id'] = !empty($this->params['id']) ? $this->params['id'] : '';\n $control->id = isset($this->params['id']) && $this->params['id'] != \"\" ? $this->params['id'] : \"\";\n //echo $control->id;\n if (empty($control->id)) $control->id = $this->params['name'];\n if (empty($control->name)) $control->name = $this->params['id'];\n\n // attempt to translate the label\n if (!empty($this->params['label'])) {\n $this->params['label'] = gt($this->params['label']);\n } else {\n $this->params['label'] = null;\n }\n echo $control->toHTML($this->params['label'], $this->params['name']);\n// $ar = new expAjaxReply(200, gt('The control was created'), json_encode(array('data'=>$code)));\n// $ar->send();\n }", "label": 1, "label_name": "safe"} -{"code": " public function search($q, $page=''){\r\n $q = str_replace(' ', '+', trim($q));\r\n if(isset($page) && $page !=''){\r\n $page = \"&page=\".$page;\r\n }else{\r\n $page = \"\";\r\n }\r\n $url = \"http://api.themoviedb.org/3/search/movie?query=\".$q.\"&api_key=\".$this->apikey.$page;\r\n $search = $this->curl($url);\r\n //echo $search;\r\n return $search;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic static function simple($input)\n\t{\n\t\treturn empty($str) ? '' : pts_strings::keep_in_string($input, pts_strings::CHAR_LETTER | pts_strings::CHAR_NUMERIC | pts_strings::CHAR_DASH | pts_strings::CHAR_DECIMAL | pts_strings::CHAR_SPACE | pts_strings::CHAR_UNDERSCORE | pts_strings::CHAR_COMMA | pts_strings::CHAR_AT | pts_strings::CHAR_COLON);\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "init_connection_options(MYSQL *mysql)\n{\n SSL_SET_OPTIONS(mysql);\n\n if (opt_protocol)\n mysql_options(mysql, MYSQL_OPT_PROTOCOL, (char*) &opt_protocol);\n\n#ifdef HAVE_SMEM\n if (shared_memory_base_name)\n mysql_options(mysql, MYSQL_SHARED_MEMORY_BASE_NAME, shared_memory_base_name);\n#endif\n}", "label": 1, "label_name": "safe"} -{"code": " void testUri() {\n final HttpHeadersBase headers = newHttp2Headers();\n assertThat(headers.uri()).isEqualTo(URI.create(\"https://netty.io/index.html\"));\n }", "label": 1, "label_name": "safe"} -{"code": "function getResourceGroups($type='', $id='') {\n\t$return = array();\n\t$query = \"SELECT g.id AS id, \"\n\t . \"g.name AS name, \"\n\t . \"t.name AS type, \"\n\t . \"g.ownerusergroupid AS ownerid, \"\n\t . \"CONCAT(u.name, '@', a.name) AS owner \"\n\t . \"FROM resourcegroup g, \"\n\t . \"resourcetype t, \"\n\t . \"usergroup u, \"\n\t . \"affiliation a \"\n\t . \"WHERE g.resourcetypeid = t.id AND \"\n\t . \"g.ownerusergroupid = u.id AND \"\n\t . \"u.affiliationid = a.id \";\n\n\tif(! empty($type))\n\t\t$query .= \"AND t.name = '$type' \";\n\n\tif(! empty($id))\n\t\t$query .= \"AND g.id = $id \";\n\n\t$query .= \"ORDER BY t.name, g.name\";\n\t$qh = doQuery($query, 281);\n\twhile($row = mysql_fetch_assoc($qh)) {\n\t\tif(empty($type))\n\t\t\t$return[$row[\"id\"]][\"name\"] = $row[\"type\"] . \"/\" . $row[\"name\"];\n\t\telse\n\t\t\t$return[$row[\"id\"]][\"name\"] = $row[\"name\"];\n\t\t$return[$row[\"id\"]][\"ownerid\"] = $row[\"ownerid\"];\n\t\t$return[$row[\"id\"]][\"owner\"] = $row[\"owner\"];\n\t}\n\treturn $return;\n}", "label": 1, "label_name": "safe"} -{"code": "int prepareForShutdown() {\n redisLog(REDIS_WARNING,\"User requested shutdown, saving DB...\");\n /* Kill the saving child if there is a background saving in progress.\n We want to avoid race conditions, for instance our saving child may\n overwrite the synchronous saving did by SHUTDOWN. */\n if (server.bgsavechildpid != -1) {\n redisLog(REDIS_WARNING,\"There is a live saving child. Killing it!\");\n kill(server.bgsavechildpid,SIGKILL);\n rdbRemoveTempFile(server.bgsavechildpid);\n }\n if (server.appendonly) {\n /* Append only file: fsync() the AOF and exit */\n aof_fsync(server.appendfd);\n if (server.vm_enabled) unlink(server.vm_swap_file);\n } else if (server.saveparamslen > 0) {\n /* Snapshotting. Perform a SYNC SAVE and exit */\n if (rdbSave(server.dbfilename) != REDIS_OK) {\n /* Ooops.. error saving! The best we can do is to continue\n * operating. Note that if there was a background saving process,\n * in the next cron() Redis will be notified that the background\n * saving aborted, handling special stuff like slaves pending for\n * synchronization... */\n redisLog(REDIS_WARNING,\"Error trying to save the DB, can't exit\");\n return REDIS_ERR;\n }\n } else {\n redisLog(REDIS_WARNING,\"Not saving DB.\");\n }\n if (server.daemonize) unlink(server.pidfile);\n redisLog(REDIS_WARNING,\"Server exit now, bye bye...\");\n return REDIS_OK;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function reqAgentFwd(chan, cb) {\n var wantReply = (typeof cb === 'function');\n\n if (chan.outgoing.state !== 'open') {\n wantReply && cb(new Error('Channel is not open'));\n return true;\n } else if (chan._client._agentFwdEnabled) {\n wantReply && cb(false);\n return true;\n }\n\n chan._client._agentFwdEnabled = true;\n\n chan._callbacks.push(function(had_err) {\n if (had_err) {\n chan._client._agentFwdEnabled = false;\n wantReply && cb(had_err !== true\n ? had_err\n : new Error('Unable to request agent forwarding'));\n return;\n }\n\n wantReply && cb();\n });\n\n return chan._client._sshstream.openssh_agentForward(chan.outgoing.id, true);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "TEST(DefaultCertValidatorTest, TestMultiLevelMatch) {\n // san_multiple_dns_cert matches *.example.com\n bssl::UniquePtr cert = readCertFromFile(TestEnvironment::substitute(\n \"{{ test_rundir \"\n \"}}/test/extensions/transport_sockets/tls/test_data/san_multiple_dns_cert.pem\"));\n envoy::type::matcher::v3::StringMatcher matcher;\n matcher.set_exact(\"foo.api.example.com\");\n std::vector>\n subject_alt_name_matchers;\n subject_alt_name_matchers.push_back(Matchers::StringMatcherImpl(matcher));\n EXPECT_FALSE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers));\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static struct clock_source *dce120_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(*clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce112_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\t\t regs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "label": 1, "label_name": "safe"} -{"code": " it 'test loading class with no parameters' do\n pp = <<-EOS.unindent\n class { 'postgresql::lib::devel': }\n EOS\n\n apply_manifest(pp, :catch_failures => true)\n apply_manifest(pp, :catch_changes => true)\n end\nend", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t$AVFieldsNVP .= $AVFieldsVal != '' ? '&' . strtoupper($AVFieldsVar) . '=' . urlencode($AVFieldsVal) : '';\n\t\t}\n\t\t\n\t\t$NVPRequest = $this->NVPCredentials . $AVFieldsNVP;\n\t\t$NVPResponse = $this->CURLRequest($NVPRequest);\n\t\t$NVPRequestArray = $this->NVPToArray($NVPRequest);\n\t\t$NVPResponseArray = $this->NVPToArray($NVPResponse);\n\t\t\n\t\t$Errors = $this->GetErrors($NVPResponseArray);\n\n $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest));\n $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse);\n\t\t\n\t\t$NVPResponseArray['ERRORS'] = $Errors;\n\t\t$NVPResponseArray['REQUESTDATA'] = $NVPRequestArray;\n\t\t$NVPResponseArray['RAWREQUEST'] = $NVPRequest;\n\t\t$NVPResponseArray['RAWRESPONSE'] = $NVPResponse;\n\t\t\t\t\t\t\t\t\n\t\treturn $NVPResponseArray;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " function mapTOC(suite, obj) {\n var ret = obj;\n obj = obj[suite.title] = obj[suite.title] || { suite: suite };\n suite.suites.forEach(function(suite) {\n mapTOC(suite, obj);\n });\n return ret;\n }", "label": 1, "label_name": "safe"} -{"code": " function categoryBreadcrumb() {\n// global $db, $router;\n\n //eDebug($this->category);\n\n /*if(isset($router->params['action']))\n {\n $ancestors = $this->category->pathToNode();\n }else if(isset($router->params['section']))\n {\n $current = $db->selectObject('section',' id= '.$router->params['section']);\n $ancestors[] = $current;\n if( $current->parent != -1 || $current->parent != 0 )\n {\n while ($db->selectObject('section',' id= '.$router->params['section']);)\n if ($section->id == $id) {\n $current = $section;\n break;\n }\n }\n }\n eDebug($sections);\n $ancestors = $this->category->pathToNode();\n }*/\n\n $ancestors = $this->category->pathToNode();\n // eDebug($ancestors);\n assign_to_template(array(\n 'ancestors' => $ancestors\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "function mapToRegistry (name, config, cb) {\n log.silly('mapToRegistry', 'name', name)\n var registry\n\n // the name itself takes precedence\n var data = npa(name)\n if (data.scope) {\n // the name is definitely scoped, so escape now\n name = name.replace('/', '%2f')\n\n log.silly('mapToRegistry', 'scope (from package name)', data.scope)\n\n registry = config.get(data.scope + ':registry')\n if (!registry) {\n log.verbose('mapToRegistry', 'no registry URL found in name for scope', data.scope)\n }\n }\n\n // ...then --scope=@scope or --scope=scope\n var scope = config.get('scope')\n if (!registry && scope) {\n // I'm an enabler, sorry\n if (scope.charAt(0) !== '@') scope = '@' + scope\n\n log.silly('mapToRegistry', 'scope (from config)', scope)\n\n registry = config.get(scope + ':registry')\n if (!registry) {\n log.verbose('mapToRegistry', 'no registry URL found in config for scope', scope)\n }\n }\n\n // ...and finally use the default registry\n if (!registry) {\n log.silly('mapToRegistry', 'using default registry')\n registry = config.get('registry')\n }\n\n log.silly('mapToRegistry', 'registry', registry)\n\n var auth = config.getCredentialsByURI(registry)\n\n // normalize registry URL so resolution doesn't drop a piece of registry URL\n var normalized = registry.slice(-1) !== '/' ? registry + '/' : registry\n var uri\n log.silly('mapToRegistry', 'data', data)\n if (data.type === 'remote') {\n uri = data.spec\n } else {\n uri = url.resolve(normalized, name)\n }\n\n log.silly('mapToRegistry', 'uri', uri)\n\n cb(null, uri, scopeAuth(uri, registry, auth), normalized)\n}", "label": 1, "label_name": "safe"} -{"code": " public function create_media_dir($params)\n {\n\n $clean = new HTMLClean();\n $_REQUEST = $clean->cleanArray($_REQUEST);\n\n must_have_access();\n $resp = array();\n // $target_path = media_base_path() . 'uploaded' . DS;\n $target_path = media_uploads_path();\n $fn_path = media_base_path();\n if (isset($_REQUEST['path']) and trim($_REQUEST['path']) != '') {\n $_REQUEST['path'] = urldecode($_REQUEST['path']);\n\n $fn_path = $target_path . DS . $_REQUEST['path'] . DS;\n $fn_path = str_replace('..', '', $fn_path);\n $fn_path = normalize_path($fn_path, false);\n\n $target_path = $fn_path;\n }\n if (!isset($_REQUEST['name']) || empty($_REQUEST['name'])) {\n $resp = array('error' => 'You must send new_folder parameter');\n } else {\n $fn_new_folder_path = $_REQUEST['name'];\n $fn_new_folder_path = urldecode($fn_new_folder_path);\n $fn_new_folder_path = str_replace('..', '', $fn_new_folder_path);\n $fn_new_folder_path_new = $target_path . DS . $fn_new_folder_path;\n $fn_path = normalize_path($fn_new_folder_path_new, false);\n if (!is_dir($fn_path)) {\n mkdir_recursive($fn_path);\n $resp = array('success' => 'Folder ' . $fn_path . ' is created');\n } else {\n $resp = array('error' => 'Folder ' . $fn_new_folder_path . ' already exists');\n }\n }\n\n return $resp;\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "def remove_constraint(auth_user, constraint_id)\n stdout, stderror, retval = run_cmd(\n auth_user, PCS, \"constraint\", \"remove\", constraint_id\n )\n $logger.info stdout\n return retval\nend", "label": 1, "label_name": "safe"} -{"code": "\tvoid verifyDirectoryPermissions(const string &path, struct stat &buf) {\n\t\tTRACE_POINT();\n\n\t\tif (buf.st_mode != (S_IFDIR | parseModeString(\"u=rwx,g=rx,o=rx\"))) {\n\t\t\tthrow RuntimeException(\"Tried to reuse existing server instance directory \" +\n\t\t\t\tpath + \", but it has wrong permissions\");\n\t\t} else if (buf.st_uid != geteuid() || buf.st_gid != getegid()) {\n\t\t\t/* The server instance directory is always created by the Watchdog. Its UID/GID never\n\t\t\t * changes because:\n\t\t\t * 1. Disabling user switching only lowers the privilege of the HelperAgent.\n\t\t\t * 2. For the UID/GID to change, the web server must be completely restarted\n\t\t\t * (not just graceful reload) so that the control process can change its UID/GID.\n\t\t\t * This causes the PID to change, so that an entirely new server instance\n\t\t\t * directory is created.\n\t\t\t */\n\t\t\tthrow RuntimeException(\"Tried to reuse existing server instance directory \" +\n\t\t\t\tpath + \", but it has wrong owner and group\");\n\t\t}\n\t}", "label": 1, "label_name": "safe"} -{"code": "static inline signed short ReadProfileShort(const EndianType endian,\n unsigned char *buffer)\n{\n union\n {\n unsigned int\n unsigned_value;\n\n signed int\n signed_value;\n } quantum;\n\n unsigned short\n value;\n\n if (endian == LSBEndian)\n {\n value=(unsigned short) buffer[1] << 8;\n value|=(unsigned short) buffer[0];\n quantum.unsigned_value=value & 0xffff;\n return(quantum.signed_value);\n }\n value=(unsigned short) buffer[0] << 8;\n value|=(unsigned short) buffer[1];\n quantum.unsigned_value=value & 0xffff;\n return(quantum.signed_value);\n}", "label": 1, "label_name": "safe"} -{"code": " public function testNestedSpansWithoutAttributes()\n {\n $this->assertResult(\n 'onetwothree',\n 'onetwothree'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " bool canContinue() override { return true; }", "label": 0, "label_name": "vulnerable"} -{"code": "static struct ip_options *ip_options_get_alloc(const int optlen)\n{\n\treturn kzalloc(sizeof(struct ip_options) + ((optlen + 3) & ~3),\n\t\t GFP_KERNEL);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " $input = ['name' => 'ldap', 'rootdn_passwd' => $password];", "label": 0, "label_name": "vulnerable"} -{"code": " scope.findPirate = function (pirate) {\n return Array.prototype.slice.call(arguments);\n };", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": "int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)\n{\n\tstruct sc_path path;\n\tstruct sc_file *file;\n\tunsigned char *p;\n\tint ok = 0;\n\tint r;\n\tsize_t len;\n\n\tsc_format_path(str_path, &path);\n\tif (SC_SUCCESS != sc_select_file(card, &path, &file)) {\n\t\tgoto err;\n\t}\n\n\tlen = file ? file->size : 4096;\n\tp = realloc(*data, len);\n\tif (!p) {\n\t\tgoto err;\n\t}\n\t*data = p;\n\t*data_len = len;\n\n\tr = sc_read_binary(card, 0, p, len, 0);\n\tif (r < 0)\n\t\tgoto err;\n\n\t*data_len = r;\n\tok = 1;\n\nerr:\n\tsc_file_free(file);\n\n\treturn ok;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "def try_ldap_login(login, password):\n \"\"\" Connect to a LDAP directory to verify user login/passwords\"\"\"\n result = \"Wrong login/password\"\n s = Server(config.LDAPURI, port=config.LDAPPORT,\n use_ssl=False, get_info=ALL)\n # 1. connection with service account to find the user uid\n uid = useruid(s, login)\n \n if uid: \n # 2. Try to bind the user to the LDAP\n c = Connection(s, user = uid , password = password, auto_bind = True)\n c.open()\n c.bind()\n result = c.result[\"description\"] # \"success\" if bind is ok\n c.unbind()\n\n return result", "label": 0, "label_name": "vulnerable"} -{"code": "def remote_pcsd_restart(params, request, auth_user)\n pcsd_restart()\n return [200, 'success']\nend", "label": 1, "label_name": "safe"} -{"code": "QString Utils::String::toHtmlEscaped(const QString &str)\n{\n#ifdef QBT_USES_QT5\n return str.toHtmlEscaped();\n#else\n return Qt::escape(str);\n#endif\n}", "label": 1, "label_name": "safe"} -{"code": "l,q=W(a);g=a._iDisplayStart;i=!1!==d.bPaginate?a._iDisplayLength:-1;var k=function(a,b){j.push({name:a,value:b})};k(\"sEcho\",a.iDraw);k(\"iColumns\",c);k(\"sColumns\",D(b,\"sName\").join(\",\"));k(\"iDisplayStart\",g);k(\"iDisplayLength\",i);var S={draw:a.iDraw,columns:[],order:[],start:g,length:i,search:{value:e.sSearch,regex:e.bRegex}};for(g=0;gactivation, 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 TF_LITE_ENSURE(context, type::AveragePool(op_params, GetTensorShape(input), \\\n GetTensorData(input), \\\n 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 return kTfLiteOk;\n}", "label": 1, "label_name": "safe"} -{"code": "\tprivate static async Task ResponseTradingBlacklistRemove(EAccess access, string botNames, string targetSteamIDs) {\n\t\tif (!Enum.IsDefined(access)) {\n\t\t\tthrow new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(botNames)) {\n\t\t\tthrow new ArgumentNullException(nameof(botNames));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(targetSteamIDs)) {\n\t\t\tthrow new ArgumentNullException(nameof(targetSteamIDs));\n\t\t}\n\n\t\tHashSet? bots = Bot.GetBots(botNames);\n\n\t\tif ((bots == null) || (bots.Count == 0)) {\n\t\t\treturn access >= EAccess.Owner ? FormatStaticResponse(string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)) : null;\n\t\t}\n\n\t\tIList results = await Utilities.InParallel(bots.Select(bot => Task.Run(() => bot.Commands.ResponseTradingBlacklistRemove(access, targetSteamIDs)))).ConfigureAwait(false);\n\n\t\tList responses = new(results.Where(static result => !string.IsNullOrEmpty(result))!);\n\n\t\treturn responses.Count > 0 ? string.Join(Environment.NewLine, responses) : null;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " protected function _mkfile($path, $name)\n {\n $path = $this->_joinPath($path, $this->_basename($name));\n return $this->connect->put($path, '') ? $path : false;\n/*\n if ($this->tmp) {\n $path = $this->_joinPath($path, $name);\n $local = $this->getTempFile();\n $res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);\n unlink($local);\n return $res ? $path : false;\n }\n\n return false;\n */\n }", "label": 1, "label_name": "safe"} -{"code": " public static function incFunc($var) {\r\n if (self::functionExist($var)) {\r\n include(GX_THEME.$var.'/function.php');\r\n }\r\n\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " callback: (request: PublishRequest, response: PublishResponse) => void;", "label": 0, "label_name": "vulnerable"} -{"code": " public function shouldRun(DateTime $date)\n {\n global $timedate;\n\n $runDate = clone $date;\n $this->handleTimeZone($runDate);\n\n $cron = Cron\\CronExpression::factory($this->schedule);\n if (empty($this->last_run) && $cron->isDue($runDate)) {\n return true;\n }\n\n $lastRun = $this->last_run ? $timedate->fromDb($this->last_run) : $timedate->fromDb($this->date_entered);\n \n $this->handleTimeZone($lastRun);\n $next = $cron->getNextRunDate($lastRun);\n\n return $next <= $runDate;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it { should contain_postgresql__server__config_entry('config_entry') }", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct(\n protected RequestHelper $requestHelper,\n protected ContentSecurityPolicyHandler $contentSecurityPolicyHandler,\n protected Config $config\n )\n {\n }", "label": 1, "label_name": "safe"} -{"code": " function work () {\n var packet = packets.shift()\n var done = completeParse\n\n if (packet) {\n that._handlePacket(packet, nextTickWork)\n } else {\n completeParse = null\n done()\n }\n }", "label": 1, "label_name": "safe"} -{"code": " it 'applies the manifest twice with no stderr' do\n expect(apply_manifest(pp, :catch_failures => true).stderr).to eq(\"\")\n expect(apply_manifest(pp, :catch_changes => true).stderr).to eq(\"\")\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function privateCore(&$response, $user, $permissions)\n {\n parent::privateCore($response, $user, $permissions);\n $this->model = new PageOption();\n $this->loadSelectedViewName();\n $this->backPage = $this->request->get('url') ?: $this->selectedViewName;\n $this->selectedUser = $this->user->admin ? $this->request->get('nick') : $this->user->nick;\n $this->loadPageOptions();\n\n $action = $this->request->get('action', '');\n switch ($action) {\n case 'delete':\n $this->deleteAction();\n break;\n\n case 'save':\n $this->saveAction();\n break;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function insertAfter($t) {\n if ($t !== NULL) array_push($this->back, $t);\n }", "label": 1, "label_name": "safe"} -{"code": "\t\t\t\ttext : fm.i18n('confirmUnmount', drive.name),\n\t\t\t\taccept : {\n\t\t\t\t\tlabel : 'btnUnmount',\n\t\t\t\t\tcallback : function() { \n\t\t\t\t\t\tfm.request({\n\t\t\t\t\t\t\tdata : {cmd : 'netmount', protocol : 'netunmount', host: drive.netkey, user : drive.hash, pass : 'dum'}, \n\t\t\t\t\t\t\tnotify : {type : 'netunmount', cnt : 1, hideCnt : true},\n\t\t\t\t\t\t\tpreventFail : true\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.fail(function(error) {\n\t\t\t\t\t\t\tdfrd.reject(error);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.done(function(data) {\n\t\t\t\t\t\t\tvar chDrive = (fm.root() == drive.hash);\n\t\t\t\t\t\t\tdata.removed = [ drive.hash ];\n\t\t\t\t\t\t\tfm.remove(data);\n\t\t\t\t\t\t\tif (chDrive) {\n\t\t\t\t\t\t\t\tvar files = fm.files();\n\t\t\t\t\t\t\t\tfor (var i in files) {\n\t\t\t\t\t\t\t\t\tif (fm.file(i).mime == 'directory') {\n\t\t\t\t\t\t\t\t\t\tfm.exec('open', i);\n\t\t\t\t\t\t\t\t\t\tbreak;\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}\n\t\t\t\t\t\t\tdfrd.resolve();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tcancel : {\n\t\t\t\t\tlabel : 'btnCancel',\n\t\t\t\t\tcallback : function() { dfrd.reject(); }\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\t\n\t\treturn dfrd;\n\t};", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic RoundedNorth(double width, double height, HColor backColor, double rounded) {\n\t\tif (width == 0)\n\t\t\tthrow new IllegalArgumentException();\n\t\tif (height == 0)\n\t\t\tthrow new IllegalArgumentException();\n\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.rounded = rounded;\n\t\tthis.backColor = backColor;\n\t}", "label": 1, "label_name": "safe"} -{"code": "a;\"boolean\"==typeof b.isChanged&&(this.isChanged=function(){return b.isChanged});\"function\"==typeof b.isChanged&&(this.isChanged=b.isChanged);\"function\"==typeof b.setValue&&(this.setValue=CKEDITOR.tools.override(this.setValue,function(a){return function(c){a.call(this,b.setValue.call(this,c))}}));\"function\"==typeof b.getValue&&(this.getValue=CKEDITOR.tools.override(this.getValue,function(a){return function(){return b.getValue.call(this,a.call(this))}}));CKEDITOR.event.implementOn(this);this.registerEvents(b);", "label": 1, "label_name": "safe"} -{"code": "reference_queue_proccess_all (void)\n{\n\tMonoReferenceQueue **iter;\n\tMonoReferenceQueue *queue = ref_queues;\n\tfor (; queue; queue = queue->next)\n\t\treference_queue_proccess (queue);\n\nrestart:\n\tEnterCriticalSection (&reference_queue_mutex);\n\tfor (iter = &ref_queues; *iter;) {\n\t\tqueue = *iter;\n\t\tif (!queue->should_be_deleted) {\n\t\t\titer = &queue->next;\n\t\t\tcontinue;\n\t\t}\n\t\tif (queue->queue) {\n\t\t\tLeaveCriticalSection (&reference_queue_mutex);\n\t\t\treference_queue_proccess (queue);\n\t\t\tgoto restart;\n\t\t}\n\t\t*iter = queue->next;\n\t\tg_free (queue);\n\t}\n\tLeaveCriticalSection (&reference_queue_mutex);\n}", "label": 1, "label_name": "safe"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = NULL;\n\tattr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr && sz >= offset) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR;\n\t\tattr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\tif (attr->info.annotation_default_attr.default_value) {\n\t\t\toffset += attr->info.annotation_default_attr.default_value->size;\n\t\t}\n\t}\n\tr_bin_java_print_annotation_default_attr_summary (attr);\n\treturn attr;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tjQuery.cleanData = function(elems) {\n\t\t\tvar events;\n\t\t\tfor (var i = 0, elem; (elem = elems[i]) != null; i++) {\n\t\t\t\tevents = jQuery._data(elem, \"events\");\n\t\t\t\tif (events && events.$destroy) {\n\t\t\t\t\tjQuery(elem).triggerHandler(\"$destroy\");\n\t\t\t\t}\n\t\t\t}\n\t\t\toriginalCleanData(elems);\n\t\t};", "label": 1, "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\n // Reinterprete the opaque data provided by user.\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 TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);\n\n const TfLiteType type = input1->type;\n if (type != kTfLiteBool) {\n context->ReportError(context, \"Logical ops only support bool type.\");\n return kTfLiteError;\n }\n output->type = 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": 1, "label_name": "safe"} -{"code": " def testInputPreProcessFormats(self):\n input_str = 'input1=/path/file.txt[ab3];input2=file2'\n input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]'\n input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str)\n input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string(\n input_expr_str, safe=False)\n self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3'))\n self.assertTrue(input_dict['input2'] == ('file2', None))\n print(input_expr_dict['input3'])\n self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2]))\n self.assertAllClose(input_expr_dict['input4'], [4, 5])\n self.assertTrue(len(input_dict) == 2)\n self.assertTrue(len(input_expr_dict) == 2)", "label": 1, "label_name": "safe"} -{"code": "function bindJQuery() {\n var originalCleanData;\n\n if (bindJQueryFired) {\n return;\n }\n\n // bind to jQuery if present;\n var jqName = jq();\n jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)\n !jqName ? undefined : // use jqLite\n window[jqName]; // use jQuery specified by `ngJq`\n\n // Use jQuery if it exists with proper functionality, otherwise default to us.\n // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.\n // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older\n // versions. It will not work for sure with jQuery <1.7, though.\n if (jQuery && jQuery.fn.on) {\n jqLite = jQuery;\n extend(jQuery.fn, {\n scope: JQLitePrototype.scope,\n isolateScope: JQLitePrototype.isolateScope,\n controller: JQLitePrototype.controller,\n injector: JQLitePrototype.injector,\n inheritedData: JQLitePrototype.inheritedData\n });\n\n // All nodes removed from the DOM via various jQuery APIs like .remove()\n // are passed through jQuery.cleanData. Monkey-patch this method to fire\n // the $destroy event on all removed nodes.\n originalCleanData = jQuery.cleanData;\n jQuery.cleanData = function(elems) {\n var events;\n for (var i = 0, elem; (elem = elems[i]) != null; i++) {\n events = jQuery._data(elem, 'events');\n if (events && events.$destroy) {\n jQuery(elem).triggerHandler('$destroy');\n }\n }\n originalCleanData(elems);\n };\n } else {\n jqLite = JQLite;\n }\n\n angular.element = jqLite;\n\n // Prevent double-proxying.\n bindJQueryFired = true;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "CKEDITOR.tools.extend(CKEDITOR.dom.node.prototype,{appendTo:function(a,e){a.append(this,e);return a},clone:function(a,e){var b=this.$.cloneNode(a),c=function(d){d[\"data-cke-expando\"]&&(d[\"data-cke-expando\"]=false);if(d.nodeType==CKEDITOR.NODE_ELEMENT){e||d.removeAttribute(\"id\",false);if(a)for(var d=d.childNodes,b=0;bprocess($container);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function prepareInputForAdd($input) {\n\n //If it's the first ldap directory then set it as the default directory\n if (!self::getNumberOfServers()) {\n $input['is_default'] = 1;\n }\n\n if (isset($input[\"rootdn_passwd\"]) && !empty($input[\"rootdn_passwd\"])) {\n $input[\"rootdn_passwd\"] = Toolbox::encrypt(stripslashes($input[\"rootdn_passwd\"]), GLPIKEY);\n }\n\n return $input;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException {\n prepareStandardInitialisation();\n StringWriter sw = initRequestResponseMocks(\n new Runnable() {\n public void run() {\n expect(request.getHeader(\"Origin\")).andStubReturn(null);\n expect(request.getHeader(\"Referer\")).andStubReturn(null);\n expect(request.getRemoteHost()).andReturn(\"localhost\");\n expect(request.getRemoteAddr()).andReturn(\"127.0.0.1\");\n expect(request.getRequestURI()).andReturn(\"/jolokia/\");\n expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);\n expect(request.getParameterMap()).andThrow(new UnsupportedOperationException(\"\"));\n Vector params = new Vector();\n params.add(\"debug\");\n expect(request.getParameterNames()).andReturn(params.elements());\n expect(request.getParameterValues(\"debug\")).andReturn(new String[] {\"false\"});\n }\n },\n getStandardResponseSetup());\n expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);\n replay(request,response);\n\n servlet.doGet(request,response);\n servlet.destroy();\n }", "label": 1, "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, "label_name": "safe"} -{"code": "\t\t\tfunction parseNextFile()\n\t\t\t{\n\t\t\t\tif (queue.length === 0)\n\t\t\t\t{\n\t\t\t\t\tif (isFunction(options.complete))\n\t\t\t\t\t\toptions.complete();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tvar f = queue[0];\n\n\t\t\t\tif (isFunction(options.before))\n\t\t\t\t{\n\t\t\t\t\tvar returned = options.before(f.file, f.inputElem);\n\n\t\t\t\t\tif (typeof returned === 'object')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (returned.action === 'abort')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror('AbortError', f.file, f.inputElem, returned.reason);\n\t\t\t\t\t\t\treturn;\t// Aborts all queued files immediately\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (returned.action === 'skip')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfileComplete();\t// parse the next file in the queue, if any\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (typeof returned.config === 'object')\n\t\t\t\t\t\t\tf.instanceConfig = $.extend(f.instanceConfig, returned.config);\n\t\t\t\t\t}\n\t\t\t\t\telse if (returned === 'skip')\n\t\t\t\t\t{\n\t\t\t\t\t\tfileComplete();\t// parse the next file in the queue, if any\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Wrap up the user's complete callback, if any, so that ours also gets executed\n\t\t\t\tvar userCompleteFunc = f.instanceConfig.complete;\n\t\t\t\tf.instanceConfig.complete = function(results)\n\t\t\t\t{\n\t\t\t\t\tif (isFunction(userCompleteFunc))\n\t\t\t\t\t\tuserCompleteFunc(results, f.file, f.inputElem);\n\t\t\t\t\tfileComplete();\n\t\t\t\t};\n\n\t\t\t\tPapa.parse(f.file, f.instanceConfig);\n\t\t\t}", "label": 1, "label_name": "safe"} -{"code": " function getIso()\n {\n return $this->dateTime->format(\\DateTime::ATOM);\n }", "label": 1, "label_name": "safe"} -{"code": " public static function mb_output_handler($contents, $status)\n {\n return $contents;\n }", "label": 1, "label_name": "safe"} -{"code": " public void setXMLReaderClassName(String xmlReaderClassName)\n throws SAXException {\n setXMLReader(XMLReaderFactory.createXMLReader(xmlReaderClassName));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function rules() {\n $parentRules = parent::rules();\n $parentRules[] = array(\n 'firstName,lastName', 'required', 'on' => 'webForm');\n return $parentRules;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected function getComment(array $task)\n {\n $comment = $this->commentModel->getById($this->request->getIntegerParam('comment_id'));\n\n if (empty($comment)) {\n throw new PageNotFoundException();\n }\n\n if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {\n throw new AccessForbiddenException();\n }\n\n if ($comment['task_id'] != $task['id']) {\n throw new AccessForbiddenException();\n }\n\n return $comment;\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function setLoggerChannel($channel = 'Organizr', $username = null)\n\t{\n\t\tif ($this->hasDB()) {\n\t\t\t$setLogger = false;\n\t\t\tif ($username) {\n\t\t\t\t$username = htmlspecialchars($username);\n\t\t\t}\n\t\t\tif ($this->logger) {\n\t\t\t\tif ($channel) {\n\t\t\t\t\tif (strtolower($this->logger->getChannel()) !== strtolower($channel)) {\n\t\t\t\t\t\t$setLogger = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ($username) {\n\t\t\t\t\tif (strtolower($this->logger->getTraceId()) !== strtolower($channel)) {\n\t\t\t\t\t\t$setLogger = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$setLogger = true;\n\t\t\t}\n\t\t\tif ($setLogger) {\n\t\t\t\t$channel = $channel ?: 'Organizr';\n\t\t\t\treturn $this->setupLogger($channel, $username);\n\t\t\t} else {\n\t\t\t\treturn $this->logger;\n\t\t\t}\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " protected function importRecordAttribute($modelName, X2Model &$model, $fieldName, $importAttribute,\n &$relationships, &$modelContainer, &$createdLinkedModels) {\n\n $fieldRecord = Fields::model()->findByAttributes(array(\n 'modelName' => $modelName,\n 'fieldName' => $fieldName,\n ));\n /**\n * Skip setting the attribute if it has already been set or if the entry from\n * the CSV is empty.\n */\n if (empty($importAttribute) && ($importAttribute !== 0 && $importAttribute !== '0')) {\n return;\n }\n if ($fieldName === 'actionDescription' && $modelName === 'Actions') {\n $text = new ActionText;\n $text->text = $importAttribute;\n if (isset($model->id))\n $text->actionId = $model->id;\n $modelContainer['ActionText'][] = $text->attributes;\n return;\n }\n\n\n // ensure the provided id is valid\n if ((strtolower($fieldName) === 'id')\n && (!preg_match('/^\\d+$/', $importAttribute) || $importAttribute >= 4294967295)) {\n return;\n }\n switch($fieldRecord->type){\n case \"link\":\n $this->importRecordLinkAttribute ($modelName, $model, $fieldRecord, $importAttribute,\n $relationships, $modelContainer, $createdLinkedModels);\n break;\n case \"dateTime\":\n case \"date\":\n if(strtotime($importAttribute) !== false){\n $model->$fieldName = strtotime($importAttribute);\n }elseif(is_numeric($importAttribute)){\n $model->$fieldName = $importAttribute;\n }else{\n\n }\n break;\n case \"visibility\":\n switch ($importAttribute) {\n case 'Private':\n $model->$fieldName = 0;\n break;\n case 'Public':\n $model->$fieldName = 1;\n break;\n case 'User\\'s Groups':\n $model->$fieldName = 2;\n break;\n default:\n $model->$fieldName = $importAttribute;\n }\n break;\n default:\n $model->$fieldName = $importAttribute;\n }\n }", "label": 1, "label_name": "safe"} -{"code": "function checkExistingNode() {\n var node = \"\";\n $('input[name=\"node-name\"]').each(function(i,e) {\n node = e.value;\n });\n\n $.ajax({\n type: 'GET',\n url: '/manage/check_pcsd_status',\n data: {\"nodes\": node},\n timeout: pcs_timeout,\n success: function (data) {\n mydata = jQuery.parseJSON(data);\n update_existing_cluster_dialog(mydata);\n\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n alert(\"ERROR: Unable to contact server\");\n }\n });\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_tokenizeHTML_textAndTags()\n {\n $this->assertTokenization(\n 'This is bold text',\n array(\n new HTMLPurifier_Token_Text('This is '),\n new HTMLPurifier_Token_Start('b', array()),\n new HTMLPurifier_Token_Text('bold'),\n new HTMLPurifier_Token_End('b'),\n new HTMLPurifier_Token_Text(' text'),\n )\n );\n }", "label": 1, "label_name": "safe"} -{"code": " public function getHeaders()\n {\n return $this->headers;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testResponseFromString()\n {\n $mock = new HTTP_Request2_Adapter_Mock();\n $mock->addResponse(\n \"HTTP/1.1 200 OK\\r\\n\" .\n \"Content-Type: text/plain; charset=iso-8859-1\\r\\n\" .\n \"\\r\\n\" .\n \"This is a string\"\n );\n $req = new HTTP_Request2('http://www.example.com/');\n $req->setAdapter($mock);\n\n $response = $req->send();\n $this->assertEquals(200, $response->getStatus());\n $this->assertEquals(1, count($response->getHeader()));\n $this->assertEquals('This is a string', $response->getBody());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $category = $this->getCategory($project);\n\n if ($this->categoryModel->remove($category['id'])) {\n $this->flash->success(t('Category removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this category.'));\n }\n\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));\n }", "label": 1, "label_name": "safe"} -{"code": "void cJSON_AddItemToObject( cJSON *object, const char *string, cJSON *item )\n{\n\tif ( ! item )\n\t\treturn;\n\tif ( item->string )\n\t\tcJSON_free( item->string );\n\titem->string = cJSON_strdup( string );\n\tcJSON_AddItemToArray( object, item );\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def test_list_instructor_tasks_running(self, act):\n \"\"\" Test list of all running tasks. \"\"\"\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 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, "label_name": "vulnerable"} -{"code": "mxEvent.getSource(F);null!=G;){if(G==v||G==x){F.stopPropagation();F.preventDefault();break}G=G.parentNode}});var K=function(F){return function(G,N,J,E,H,S,U,Q,W){null!=W&&(/(\\.v(dx|sdx?))($|\\?)/i.test(W.name)||/(\\.vs(x|sx?))($|\\?)/i.test(W.name))?b.importVisio(W,mxUtils.bind(this,function(V){c(V,N,J,E,H,S,U,\"fixed\",mxEvent.isAltDown(F)?null:U.substring(0,U.lastIndexOf(\".\")).replace(/_/g,\" \"))})):null!=W&&(new XMLHttpRequest).upload&&b.isRemoteFileFormat(G,W.name)?b.isExternalDataComms()?b.parseFile(W,\nmxUtils.bind(this,function(V){4==V.readyState&&(b.spinner.stop(),200<=V.status&&299>=V.status&&(c(V.responseText,N,J,E,H,S,U,\"fixed\",mxEvent.isAltDown(F)?null:U.substring(0,U.lastIndexOf(\".\")).replace(/_/g,\" \")),v.scrollTop=v.scrollHeight))})):(b.spinner.stop(),b.showError(mxResources.get(\"error\"),mxResources.get(\"notInOffline\"))):(c(G,N,J,E,H,S,U,\"fixed\",mxEvent.isAltDown(F)?null:U.substring(0,U.lastIndexOf(\".\")).replace(/_/g,\" \")),v.scrollTop=v.scrollHeight)}};mxEvent.addListener(v,\"dragover\",e);", "label": 0, "label_name": "vulnerable"} -{"code": " } elseif ($node->nodeType === XML_COMMENT_NODE) {\n // this is code is only invoked for comments in script/style in versions\n // of libxml pre-2.6.28 (regular comments, of course, are still\n // handled regularly)\n $tokens[] = $this->factory->createComment($node->data);\n return false;\n } elseif ($node->nodeType !== XML_ELEMENT_NODE) {", "label": 1, "label_name": "safe"} -{"code": " public function getPath()\n {\n return $this->path == null ? '' : $this->path;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " var filter = function(data) {\r\n if (data) {\r\n data = data.replace(new RegExp('', '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, "label_name": "safe"} -{"code": "z.y,t.width/L,t.height/L,\"fillColor=none;strokeColor=red;\")}));c.actions.addAction(\"testCheckFile\",mxUtils.bind(this,function(){var t=null!=c.pages&&null!=c.getCurrentFile()?c.getCurrentFile().getAnonymizedXmlForPages(c.pages):\"\";t=new TextareaDialog(c,\"Paste Data:\",t,function(z){if(0 :user,\n :user => matches[0],\n :host => matches[1]\n }\n when 4\n {\n :type => :db,\n :user => matches[0],\n :host => matches[1],\n :db => matches[3]\n }\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public synchronized MultiMap headers() {\n if (headers == null) {\n headers = new VertxHttpHeaders();\n }\n return headers;\n }", "label": 1, "label_name": "safe"} -{"code": "function(aa){T--;N()}),!0,null,\"data:\"+Z+\";charset=utf-8;base64,\")}))}})(Editor.trimCssUrl(J[u].substring(0,Q)),R)}N()}else E(u)};Editor.prototype.loadFonts=function(u){null!=this.fontCss&&null==this.resolvedFontCss?this.embedCssFonts(this.fontCss,mxUtils.bind(this,function(E){this.resolvedFontCss=E;null!=u&&u()})):null!=u&&u()};Editor.prototype.createGoogleFontCache=function(){var u={},E;for(E in Graph.fontMapping)Graph.isCssFontUrl(E)&&(u[E]=Graph.fontMapping[E]);return u};Editor.prototype.embedExtFonts=", "label": 0, "label_name": "vulnerable"} -{"code": " def test_filename(self):\n tmpname = mktemp('', 'mmap')\n fp = memmap(tmpname, dtype=self.dtype, mode='w+',\n shape=self.shape)\n abspath = os.path.abspath(tmpname)\n fp[:] = self.data[:]\n self.assertEqual(abspath, fp.filename)\n b = fp[:1]\n self.assertEqual(abspath, b.filename)\n del b\n del fp\n os.unlink(tmpname)", "label": 0, "label_name": "vulnerable"} -{"code": "TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotTheRightCardinality) {\n SegmentSumOpModel model({TensorType_INT32, {3, 2}},\n {TensorType_INT32, {2}});\n model.PopulateTensor(model.data(), {1, 2, 3, 4, 5, 6});\n model.PopulateTensor(model.segment_ids(), {0, 1});\n ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError);\n}", "label": 1, "label_name": "safe"} -{"code": " $callback = function (array $matches) {\n return 'a';\n };", "label": 1, "label_name": "safe"} -{"code": " it 'should write the public key to disk if its the first time its been seen' 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 File.stubs(:directory?).with('ssh/pkd').returns(true)\n File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(false)\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 @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function setUp()\n {\n $this->request = new VoidRequest($this->getHttpClient(), $this->getHttpRequest());\n $this->request->setTransactionReference('ch_12RgN9L7XhO9mI')\n ->setRefundApplicationFee(true);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " fn find_undef_vars_inner(\n &'a self,\n scope: &Scope<'a>,\n defined: &HashSet<&'a str>,\n unused: &mut Vec<&'a Spanning<&'a str>>,\n visited: &mut HashSet>,\n ) -> Option<&'a Vec<&'a str>> {\n if visited.contains(scope) {\n return None;\n }\n\n visited.insert(scope.clone());\n\n if let Some(used_vars) = self.used_variables.get(scope) {\n for var in used_vars {\n if !defined.contains(&var.item) {\n unused.push(var);\n }\n }\n }\n\n self.spreads.get(scope)\n }", "label": 1, "label_name": "safe"} -{"code": "function genOpenSSLECDSAPub(oid, Q) {\n const asnWriter = new Ber.Writer();\n asnWriter.startSequence();\n // algorithm\n asnWriter.startSequence();\n asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey\n // algorithm parameters (namedCurve)\n asnWriter.writeOID(oid);\n asnWriter.endSequence();\n\n // subjectPublicKey\n asnWriter.startSequence(Ber.BitString);\n asnWriter.writeByte(0x00);\n // XXX: hack to write a raw buffer without a tag -- yuck\n asnWriter._ensure(Q.length);\n asnWriter._buf.set(Q, asnWriter._offset);\n asnWriter._offset += Q.length;\n // end hack\n asnWriter.endSequence();\n asnWriter.endSequence();\n return makePEM('PUBLIC', asnWriter.buffer);\n}", "label": 1, "label_name": "safe"} -{"code": "function createTrailing (_options, _next) {\n var next = typeof _options === 'function' ? _options : _next\n var options = typeof _options === 'object' ? _options : {}\n var status = options.status || 302\n var slash = typeof options.slash === 'undefined' ? true : options.slash\n var middleware = !next\n\n return function trailingSlash () {\n var args = Array.prototype.slice.call(arguments)\n var done = middleware ? args.slice(-1)[0] : next\n\n var req = args[0]\n var res = args[1]\n var url = u.parse(req.url)\n var length = url.pathname.length\n var hasSlash = url.pathname.charAt(length - 1) === '/'\n\n if (hasSlash === slash) {\n if (middleware) {\n return done()\n }\n return next.apply(null, args)\n }\n\n if (slash) {\n url.pathname = url.pathname + '/'\n } else {\n url.pathname = url.pathname.slice(0, -1)\n }\n\n res.statusCode = status\n res.setHeader('Location', escapeLeadingSlashes(u.format(url)))\n res.end()\n }\n}", "label": 1, "label_name": "safe"} -{"code": " public static function filter()\n {\n //print_r(self::$hooks[$var]);\n $hooks = self::$hooks;\n $num_args = func_num_args();\n $args = func_get_args();\n // print_r($args);\n // if ($num_args < 2)\n // trigger_error(\"Insufficient arguments\", E_USER_ERROR);\n\n // Hook name should always be first argument\n $hook_name = array_shift($args);\n\n if (!isset($hooks[$hook_name])) {\n return;\n } // No plugins have registered this hook\n // print_r($args[0]);\n // $args = (is_array($args))?$args[0]: $args;\n if (is_array($hooks[$hook_name])) {\n foreach ($hooks[$hook_name] as $func) {\n if ($func != '') {\n // $args = call_user_func_array($func, $args); //\n $args = $func((array) $args);\n } else {\n $args = $args;\n }\n }\n\n $args = $args;\n } else {\n $args = $args;\n }\n\n $args = is_array($args) ? $args[0] : $args;\n\n return $args;\n }", "label": 1, "label_name": "safe"} -{"code": "func testExternalNameServiceInsecure(namespace string) {\n\tSpecify(\"external name services work over http\", func() {\n\t\tt := f.T()\n\n\t\tf.Fixtures.Echo.Deploy(namespace, \"ingress-conformance-echo\")\n\n\t\texternalNameService := &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName: \"external-name-service\",\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tType: corev1.ServiceTypeExternalName,\n\t\t\t\tExternalName: \"ingress-conformance-echo.\" + namespace,\n\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"http\",\n\t\t\t\t\t\tPort: 80,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\trequire.NoError(t, f.Client.Create(context.TODO(), externalNameService))\n\n\t\tp := &contourv1.HTTPProxy{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName: \"external-name-proxy\",\n\t\t\t},\n\t\t\tSpec: contourv1.HTTPProxySpec{\n\t\t\t\tVirtualHost: &contourv1.VirtualHost{\n\t\t\t\t\tFqdn: \"externalnameservice.projectcontour.io\",\n\t\t\t\t},\n\t\t\t\tRoutes: []contourv1.Route{\n\t\t\t\t\t{\n\t\t\t\t\t\tServices: []contourv1.Service{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: externalNameService.Name,\n\t\t\t\t\t\t\t\tPort: 80,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tRequestHeadersPolicy: &contourv1.HeadersPolicy{\n\t\t\t\t\t\t\tSet: []contourv1.HeaderValue{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\t\t\t\tValue: externalNameService.Spec.ExternalName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tf.CreateHTTPProxyAndWaitFor(p, httpProxyValid)\n\n\t\tres, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{\n\t\t\tHost: p.Spec.VirtualHost.Fqdn,\n\t\t\tCondition: e2e.HasStatusCode(200),\n\t\t})\n\t\trequire.Truef(t, ok, \"expected 200 response code, got %d\", res.StatusCode)\n\t})\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"creates a new cursor\" do\n cursor = mock(Moped::Cursor, next: nil)\n Moped::Cursor.should_receive(:new).\n with(session, query.operation).and_return(cursor)\n\n query.each\n end", "label": 0, "label_name": "vulnerable"} -{"code": "static void tiny_dispatch(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size)\n{\n if (!pb_parse(entry, msg, msg_size, msg_tiny)) {\n call_msg_failure_handler(FailureType_Failure_UnexpectedMessage,\n \"Could not parse tiny protocol buffer message\");\n return;\n }\n\n msg_tiny_id = entry->msg_id;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " protected function redirectToGroup(Thread $thread, $group_id)\n {\n if ($thread->state != Thread::STATE_CHATTING) {\n // We can redirect only threads which are in proggress now.\n return false;\n }\n\n // Redirect the thread\n $thread->state = Thread::STATE_WAITING;\n $thread->nextAgent = 0;\n $thread->groupId = $group_id;\n $thread->agentId = 0;\n $thread->agentName = '';\n $thread->save();\n\n // Send notification message\n $thread->postMessage(\n Thread::KIND_EVENTS,\n getlocal(\n 'Operator {0} redirected you to another operator. Please wait a while.',\n array(get_operator_name($this->getOperator())),\n $thread->locale,\n true\n )\n );\n\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tfunction renderFile(file)\n\t{\n\t\tif (prevDiv == null)\n\t\t{\n\t\t\treturn;\t\n\t\t}\n\t\t\n\t\tprevDiv.style.background = 'transparent';\n\t\tprevDiv.innerHTML = '';\n\t\t\n\t\tfunction showRenderMsg(msg)\n\t\t{\n\t\t\tprevDiv.style.background = 'transparent';\n\t\t\tprevDiv.innerHTML = '';\t\n\n\t\t\tvar status = document.createElement('div');\n\t\t\tstatus.className = 'odPreviewStatus';\n\t\t\tmxUtils.write(status, msg);\n\t\t\tprevDiv.appendChild(status);\n\t\t\tspinner.stop();\n\t\t};\n\t\t\n\t\tif (file == null || file.folder || /\\.drawiolib$/.test(file.name)) \n\t\t{\n\t\t\tshowRenderMsg(mxResources.get('noPreview'));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\t// Workaround for parentReference access\n\t\t\tif (file.remoteItem != null)\n\t\t\t{\n\t\t\t\tfile = file.remoteItem;\n\t\t\t}\n\n\t\t\tloadingPreviewFile = file;\n\t\t\tspinner.spin(prevDiv);\n\t\t\n\t\t\tgetDrawioFileDoc(file, function(doc)\n\t\t\t{\n\t\t\t\tspinner.stop();\n\n\t\t\t\tif (loadingPreviewFile != file)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (doc.documentElement.nodeName == 'mxlibrary')\n\t\t\t\t{\n\t\t\t\t\tshowRenderMsg(mxResources.get('noPreview'));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar diagrams = doc.getElementsByTagName('diagram');\n\t\t\t\t\tcurViewer = AspectDialog.prototype.createViewer(prevDiv,\n\t\t\t\t\t\t\tdiagrams.length == 0? doc.documentElement : diagrams[0],\n\t\t\t\t\t\t\tnull, 'transparent');\n\t\t\t\t}\n\t\t\t}, \n\t\t\tfunction() //If the file is not a draw.io diagram\n\t\t\t{\n\t\t\t\tselectedFile = null;\n\t\t\t\tshowRenderMsg(mxResources.get('notADiagramFile'));\n\t\t\t});\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\tselectedFile = null;\n\t\t\tshowRenderMsg(mxResources.get('notADiagramFile'));\n\t\t}\n\t};", "label": 0, "label_name": "vulnerable"} -{"code": "ber_parse_header(STREAM s, int tagval, uint32 *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": 1, "label_name": "safe"} -{"code": "buflist_match(\n regmatch_T\t*rmp,\n buf_T\t*buf,\n int\t\tignore_case) // when TRUE ignore case, when FALSE use 'fic'\n{\n char_u\t*match;\n\n // First try the short file name, then the long file name.\n match = fname_match(rmp, buf->b_sfname, ignore_case);\n if (match == NULL)\n\tmatch = fname_match(rmp, buf->b_ffname, ignore_case);\n\n return match;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "_PyObject_Malloc(void *ctx, size_t nbytes)\n{\n return _PyObject_Alloc(0, ctx, 1, nbytes);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)\n {\n $str = '';\n\n if ($title !== false && $title instanceof Title) {\n $str .= $title->tshort . ' ';\n }\n\n $str .= mb_strtoupper($name, 'UTF-8') . ' ' .\n ucwords(mb_strtolower($surname, 'UTF-8'), \" \\t\\r\\n\\f\\v-_|\");\n\n if ($id !== false || $nick !== false) {\n $str .= ' (';\n }\n if ($nick !== false) {\n $str .= $nick;\n }\n if ($id !== false) {\n if ($nick !== false && !empty($nick)) {\n $str .= ', ';\n }\n $str .= $id;\n }\n if ($id !== false || $nick !== false) {\n $str .= ')';\n }\n return strip_tags($str);\n }", "label": 1, "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, "label_name": "safe"} -{"code": "R_API bool r_anal_vtable_begin(RAnal *anal, RVTableContext *context) {\n\tcontext->anal = anal;\n\tcontext->abi = anal->cxxabi;\n\tcontext->word_size = (ut8) (anal->config->bits / 8);\n\tconst bool is_arm = anal->cur->arch && r_str_startswith (anal->cur->arch, \"arm\");\n\tif (is_arm && context->word_size < 4) {\n\t\tcontext->word_size = 4;\n\t}\n\tconst bool be = anal->config->big_endian;\n\tswitch (context->word_size) {\n\tcase 1:\n\t\tcontext->read_addr = be? vtable_read_addr_be8 : vtable_read_addr_le8;\n\t\tbreak;\n\tcase 2:\n\t\tcontext->read_addr = be? vtable_read_addr_be16 : vtable_read_addr_le16;\n\t\tbreak;\n\tcase 4:\n\t\tcontext->read_addr = be? vtable_read_addr_be32 : vtable_read_addr_le32;\n\t\tbreak;\n\tcase 8:\n\t\tcontext->read_addr = be? vtable_read_addr_be64 : vtable_read_addr_le64;\n\t\tbreak;\n\tdefault:\n\t\t// cant be null. assume 32bit \"->read_addr = NULL;\n\t\tcontext->read_addr = be? vtable_read_addr_be32 : vtable_read_addr_le32;\n\t\treturn false;\n\t}\n\treturn true;\n}", "label": 1, "label_name": "safe"} -{"code": " protected function parseImplementation($var, $type, $allow_null)\n {\n return $this->evalExpression($var);\n }", "label": 1, "label_name": "safe"} -{"code": " public function add(CacheClearerInterface $clearer)\n {\n $this->clearers[] = $clearer;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "j,!0)}function o(a,c,d){if(!m(c))return c.size=null;if(c.size){if(c.size.ignoreScroll==d&&c.size.date>new Date-ba)return null}else c.size={};return q(c.size,P(a,c,d),{date:+new Date},!0)}function C(a,c){a.view.editable=P(a,a.editable,c,!0)}function I(a,c){a.view||(a.view={});var d=a.view;if(c||!(d&&d.date>new Date-ba)){var b=a.win,d=b.getScrollPosition(),b=b.getViewPaneSize();q(a.view,{scroll:{x:d.x,y:d.y,width:a.doc.$.documentElement.scrollWidth-b.width,height:a.doc.$.documentElement.scrollHeight-", "label": 1, "label_name": "safe"} -{"code": " public function setPosition($x, $y)\n {\n $this->setX($x);\n $this->setY($y);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "Runner.prototype.hooks = function(name, suites, fn){\n var self = this\n , orig = this.suite;\n\n function next(suite) {\n self.suite = suite;\n\n if (!suite) {\n self.suite = orig;\n return fn();\n }\n\n self.hook(name, function(err){\n if (err) {\n var errSuite = self.suite;\n self.suite = orig;\n return fn(err, errSuite);\n }\n\n next(suites.pop());\n });\n }\n\n next(suites.pop());\n};", "label": 0, "label_name": "vulnerable"} -{"code": "TEST_F(AsStringGraphTest, FillWithChar4) {\n Status s = Init(DT_INT32, /*fill=*/\"n\");\n ASSERT_EQ(error::INVALID_ARGUMENT, s.code());\n ASSERT_TRUE(\n absl::StrContains(s.error_message(), \"Fill argument not supported\"));\n}", "label": 1, "label_name": "safe"} -{"code": " $percent = round($percent, 0);\n } else {\n $percent = round($percent, 2); // school default\n }\n if ($ret == '%')\n return $percent;\n\n if (!$_openSIS['_makeLetterGrade']['grades'][$grade_scale_id])\n $_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] = DBGet(DBQuery('SELECT TITLE,ID,BREAK_OFF FROM report_card_grades WHERE SYEAR=\\'' . $cp[1]['SYEAR'] . '\\' AND SCHOOL_ID=\\'' . $cp[1]['SCHOOL_ID'] . '\\' AND GRADE_SCALE_ID=\\'' . $grade_scale_id . '\\' ORDER BY BREAK_OFF IS NOT NULL DESC,BREAK_OFF DESC,SORT_ORDER'));\n\n foreach ($_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] as $grade) {\n if ($does_breakoff == 'Y' ? $percent >= $programconfig[$staff_id][$course_period_id . '-' . $grade['ID']] && is_numeric($programconfig[$staff_id][$course_period_id . '-' . $grade['ID']]) : $percent >= $grade['BREAK_OFF'])\n return $ret == 'ID' ? $grade['ID'] : $grade['TITLE'];\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function getPriority()\n {\n return -2;\n }", "label": 1, "label_name": "safe"} -{"code": " public function setUp()\n {\n list($this->config, $this->context) = $this->createCommon();\n $this->config->set('Output.Newline', '\n');\n $this->purifier = new HTMLPurifier();\n }", "label": 1, "label_name": "safe"} -{"code": " $comments->records[$key]->avatar = $db->selectObject('user_avatar',\"user_id='\".$record->poster.\"'\");\n }\n\n if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);\n // eDebug($sql, true);\n\n // count the unapproved comments\n if ($require_approval == 1 && $user->isAdmin()) {\n $sql = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';\n $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';\n $sql .= 'WHERE cnt.content_id='.$this->params['content_id'].\" AND cnt.content_type='\".expString::escape($this->params['content_type']).\"' \";\n $sql .= 'AND com.approved=0';\n $unapproved = $db->countObjectsBySql($sql);\n } else {\n $unapproved = 0;\n }\n\n $this->config = $this->params['config'];\n $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');\n $ratings = !empty($this->params['ratings']) ? true : false;\n\n assign_to_template(array(\n 'comments'=>$comments,\n 'config'=>$this->params['config'],\n 'unapproved'=>$unapproved,\n\t\t\t'content_id'=>$this->params['content_id'],\n\t\t\t'content_type'=>$this->params['content_type'],\n\t\t\t'user'=>$user,\n\t\t\t'hideform'=>$this->params['hideform'],\n\t\t\t'hidecomments'=>$this->params['hidecomments'],\n\t\t\t'title'=>$this->params['title'],\n\t\t\t'formtitle'=>$this->params['formtitle'],\n 'type'=>$type,\n 'ratings'=>$ratings,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n\t\t));\n\t}", "label": 1, "label_name": "safe"} -{"code": " public function test_finalize()\n {\n // test finalization\n\n $this->schema->add('Poem.Meter', 'iambic', 'string', false);\n\n $config = new HTMLPurifier_Config($this->schema);\n $config->autoFinalize = false;\n $config->chatty = false;\n\n $config->set('Poem.Meter', 'irregular');\n\n $config->finalize();\n\n $this->expectError('Cannot set directive after finalization');\n $config->set('Poem.Meter', 'vedic');\n\n $this->expectError('Cannot load directives after finalization');\n $config->loadArray(array('Poem.Meter' => 'octosyllable'));\n\n $this->expectError('Cannot load directives after finalization');\n $config->loadIni(dirname(__FILE__) . '/ConfigTest-finalize.ini');\n\n }", "label": 1, "label_name": "safe"} -{"code": "static void pipe_advance(struct iov_iter *i, size_t size)\n{\n\tstruct pipe_inode_info *pipe = i->pipe;\n\tstruct pipe_buffer *buf;\n\tint idx = i->idx;\n\tsize_t off = i->iov_offset, orig_sz;\n\t\n\tif (unlikely(i->count < size))\n\t\tsize = i->count;\n\torig_sz = size;\n\n\tif (size) {\n\t\tif (off) /* make it relative to the beginning of buffer */\n\t\t\tsize += off - pipe->bufs[idx].offset;\n\t\twhile (1) {\n\t\t\tbuf = &pipe->bufs[idx];\n\t\t\tif (size <= buf->len)\n\t\t\t\tbreak;\n\t\t\tsize -= buf->len;\n\t\t\tidx = next_idx(idx, pipe);\n\t\t}\n\t\tbuf->len = size;\n\t\ti->idx = idx;\n\t\toff = i->iov_offset = buf->offset + size;\n\t}\n\tif (off)\n\t\tidx = next_idx(idx, pipe);\n\tif (pipe->nrbufs) {\n\t\tint unused = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);\n\t\t/* [curbuf,unused) is in use. Free [idx,unused) */\n\t\twhile (idx != unused) {\n\t\t\tpipe_buf_release(pipe, &pipe->bufs[idx]);\n\t\t\tidx = next_idx(idx, pipe);\n\t\t\tpipe->nrbufs--;\n\t\t}\n\t}\n\ti->count -= orig_sz;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "int CLua::loadfile(lua_State *ls, const char *filename, bool trusted,\n bool die_on_fail)\n{\n if (!ls)\n return -1;\n\n if (!is_path_safe(filename, trusted))\n {\n lua_pushstring(\n ls,\n make_stringf(\"invalid filename: %s\", filename).c_str());\n return -1;\n }\n\n string file = datafile_path(filename, die_on_fail);\n if (file.empty())\n {\n lua_pushstring(ls,\n make_stringf(\"Can't find \\\"%s\\\"\", filename).c_str());\n return -1;\n }\n\n FileLineInput f(file.c_str());\n string script;\n while (!f.eof())\n script += f.get_line() + \"\\n\";\n\n if (script[0] == 0x1b)\n abort();\n\n // prefixing with @ stops lua from adding [string \"%s\"]\n return luaL_loadbuffer(ls, &script[0], script.length(),\n (\"@\" + file).c_str());\n}", "label": 1, "label_name": "safe"} -{"code": " def receive_replies(operations)\n operations.map do |operation|\n read if operation.is_a?(Protocol::Query) || operation.is_a?(Protocol::GetMore)\n end\n end", "label": 1, "label_name": "safe"} -{"code": "\tprotected void doGet(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException\n\t{\n // GAE can't serve dot prefixed folders\n String uri = request.getRequestURI().replace(\"/.\", \"/\");\n\n if (uri.toLowerCase().contains(\".json\"))\n {\n \tresponse.setContentType(\"application/json\");\n }\n\n // Serve whatever was requested from .well-known\n try (InputStream in = getServletContext().getResourceAsStream(uri))\n {\n if (in == null)\n {\n \tresponse.sendError(404);\n return;\n }\n \n byte[] buffer = new byte[8192];\n int count;\n\n while ((count = in.read(buffer)) > 0)\n {\n \tresponse.getOutputStream().write(buffer, 0, count);\n }\n \n response.getOutputStream().flush();\n response.getOutputStream().close();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testMethodSafe($method, $safe)\n {\n $request = new Request();\n $request->setMethod($method);\n $this->assertEquals($safe, $request->isMethodSafe());\n }", "label": 1, "label_name": "safe"} -{"code": "\"1\":null},ea.getVerticesAndEdges())},{install:function(ja){this.listener=function(){ja(Editor.sketchMode)};X.addListener(\"sketchModeChanged\",this.listener)},destroy:function(){X.removeListener(this.listener)}});O.appendChild(ka)}return O};var ba=Menus.prototype.init;Menus.prototype.init=function(){ba.apply(this,arguments);var O=this.editorUi,X=O.editor.graph;O.actions.get(\"editDiagram\").label=mxResources.get(\"formatXml\")+\"...\";O.actions.get(\"createShape\").label=mxResources.get(\"shape\")+\"...\";O.actions.get(\"outline\").label=", "label": 1, "label_name": "safe"} -{"code": " public function prepare($config)\n {\n $this->regexp = $config->get('URI.SafeIframeRegexp');\n return true;\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function setSectionSeparators( ?array $separators ) {\n\t\t$this->sectionSeparators = $separators ?? [];\n\t}", "label": 1, "label_name": "safe"} -{"code": " function onFinish() {\n self.eof();\n if (server || (!server && !self.allowHalfOpen))\n self.close();\n self.writable = false;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "X){null!=X.shortcut&&900>n&&!mxClient.IS_IOS?O.firstChild.nextSibling.setAttribute(\"title\",X.shortcut):m.apply(this,arguments)};var q=App.prototype.updateUserElement;App.prototype.updateUserElement=function(){q.apply(this,arguments);if(null!=this.userElement){var O=this.userElement;O.style.cssText=\"position:relative;margin-right:4px;cursor:pointer;display:\"+O.style.display;O.className=\"geToolbarButton\";O.innerHTML=\"\";O.style.backgroundImage=\"url(\"+Editor.userImage+\")\";O.style.backgroundPosition=\"center center\";\nO.style.backgroundRepeat=\"no-repeat\";O.style.backgroundSize=\"24px 24px\";O.style.height=\"24px\";O.style.width=\"24px\";O.style.cssFloat=\"right\";O.setAttribute(\"title\",mxResources.get(\"changeUser\"));if(\"none\"!=O.style.display){O.style.display=\"inline-block\";var X=this.getCurrentFile();if(null!=X&&X.isRealtimeEnabled()&&X.isRealtimeSupported()){var ea=document.createElement(\"img\");ea.setAttribute(\"border\",\"0\");ea.style.position=\"absolute\";ea.style.left=\"18px\";ea.style.top=\"2px\";ea.style.width=\"12px\";ea.style.height=\n\"12px\";var ka=X.getRealtimeError();X=X.getRealtimeState();var ja=mxResources.get(\"realtimeCollaboration\");1==X?(ea.src=Editor.syncImage,ja+=\" (\"+mxResources.get(\"online\")+\")\"):(ea.src=Editor.syncProblemImage,ja=null!=ka&&null!=ka.message?ja+(\" (\"+ka.message+\")\"):ja+(\" (\"+mxResources.get(\"disconnected\")+\")\"));ea.setAttribute(\"title\",ja);O.style.paddingRight=\"4px\";O.appendChild(ea)}}}};var y=App.prototype.updateButtonContainer;App.prototype.updateButtonContainer=function(){y.apply(this,arguments);if(null!=", "label": 0, "label_name": "vulnerable"} -{"code": "PJ_DEF(pj_status_t) pjsip_endpt_send_request_stateless(pjsip_endpoint *endpt, \n\t\t\t\t pjsip_tx_data *tdata,\n\t\t\t\t void *token,\n\t\t\t\t pjsip_send_callback cb)\n{\n pjsip_host_info dest_info;\n pjsip_send_state *stateless_data;\n pj_status_t status;\n\n PJ_ASSERT_RETURN(endpt && tdata, PJ_EINVAL);\n\n /* Get destination name to contact. */\n status = pjsip_process_route_set(tdata, &dest_info);\n if (status != PJ_SUCCESS)\n\treturn status;\n\n /* Keep stateless data. */\n stateless_data = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_send_state);\n stateless_data->token = token;\n stateless_data->endpt = endpt;\n stateless_data->tdata = tdata;\n stateless_data->app_cb = cb;\n\n /* If destination info has not been initialized (this applies for most\n * all requests except CANCEL), resolve destination host. The processing\n * then resumed when the resolving callback is called. For CANCEL, the\n * destination info must have been copied from the original INVITE so\n * proceed to sending the request directly.\n */\n if (tdata->dest_info.addr.count == 0) {\n\t/* Copy the destination host name to TX data */\n\tpj_strdup(tdata->pool, &tdata->dest_info.name, &dest_info.addr.host);\n\n\tpjsip_endpt_resolve( endpt, tdata->pool, &dest_info, stateless_data,\n\t\t\t &stateless_send_resolver_callback);\n } else {\n\tPJ_LOG(5,(THIS_FILE, \"%s: skipping target resolution because \"\n\t \"address is already set\",\n\t\t\t pjsip_tx_data_get_info(tdata)));\n\tstateless_send_resolver_callback(PJ_SUCCESS, stateless_data,\n\t\t\t\t\t &tdata->dest_info.addr);\n }\n return PJ_SUCCESS;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function make($string)\n {\n $embeds = ($string === 'embedded');\n return new HTMLPurifier_AttrDef_URI($embeds);\n }", "label": 1, "label_name": "safe"} -{"code": "null,this.container)}));q.appendChild(u);u.className=\"geBtn gePrimaryBtn\";b.editor.cancelFirst||q.appendChild(e);if(null!=k)for(c=0;c {\n const messageBuilder = new MessageBuilder();\n\n let full_message_body_event_received = false;\n let on_message__received = false;\n\n messageBuilder\n .on(\"message\", (message) => {\n on_message__received = true;\n })\n .on(\"full_message_body\", (full_message_body) => {\n full_message_body_event_received = true;\n })\n .on(\"invalid_message\", (err) => {\n expectError.should.eql(false);\n on_message__received.should.equal(false);\n full_message_body_event_received.should.equal(true);\n done();\n })\n .on(\"error\", (err) => {\n err.should.be.instanceOf(Error);\n expectError.should.eql(true);\n done();\n });\n\n messageBuilder.feed(bad_packet); // OpenSecureChannel message\n },\n function () {/** */ }\n );\n }", "label": 1, "label_name": "safe"} -{"code": " public function testProcessAutowireInterface()\n {\n $container = new ContainerBuilder();\n\n $container->register('f', __NAMESPACE__.'\\F');\n $gDefinition = $container->register('g', __NAMESPACE__.'\\G');\n $gDefinition->setAutowired(true);\n\n $pass = new AutowirePass();\n $pass->process($container);\n\n $this->assertCount(3, $container->getDefinition('g')->getArguments());\n $this->assertEquals('f', (string) $container->getDefinition('g')->getArgument(0));\n $this->assertEquals('f', (string) $container->getDefinition('g')->getArgument(1));\n $this->assertEquals('f', (string) $container->getDefinition('g')->getArgument(2));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static int hgcm_call_preprocess_linaddr(\n\tconst struct vmmdev_hgcm_function_parameter *src_parm,\n\tvoid **bounce_buf_ret, size_t *extra)\n{\n\tvoid *buf, *bounce_buf;\n\tbool copy_in;\n\tu32 len;\n\tint ret;\n\n\tbuf = (void *)src_parm->u.pointer.u.linear_addr;\n\tlen = src_parm->u.pointer.size;\n\tcopy_in = src_parm->type != VMMDEV_HGCM_PARM_TYPE_LINADDR_OUT;\n\n\tif (len > VBG_MAX_HGCM_USER_PARM)\n\t\treturn -E2BIG;\n\n\tbounce_buf = kvmalloc(len, GFP_KERNEL);\n\tif (!bounce_buf)\n\t\treturn -ENOMEM;\n\n\tif (copy_in) {\n\t\tret = copy_from_user(bounce_buf, (void __user *)buf, len);\n\t\tif (ret)\n\t\t\treturn -EFAULT;\n\t} else {\n\t\tmemset(bounce_buf, 0, len);\n\t}\n\n\t*bounce_buf_ret = bounce_buf;\n\thgcm_call_add_pagelist_size(bounce_buf, len, extra);\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function andLogAndFinish (spec, tracker, done) {\n validate('SOF|SZF|OOF|OZF', [spec, tracker, done])\n return (er, pkg) => {\n if (er) {\n log.silly('fetchPackageMetaData', 'error for ' + String(spec), er.message)\n if (tracker) tracker.finish()\n }\n return done(er, pkg)\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def sql_insert(self, sentence):\n self.cursor.execute(sentence)\n self.conn.commit()\n return True", "label": 0, "label_name": "vulnerable"} -{"code": " it \"sets the length\" do\n reply.length.should eq raw.length\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\"geCommentActionLnk\";mxUtils.write(da,P);Y.appendChild(da);mxEvent.addListener(da,\"click\",function(ha){O(ha,J);ha.preventDefault();mxEvent.consume(ha)});T.appendChild(Y);R&&(Y.style.display=\"none\")}function W(){function P(Y){O.push(R);if(null!=Y.replies)for(var da=0;dadisable_audio)\n\t\twcall->disable_audio = false;\n\t\n\tif (!wcall->icall) {\n\t\twarning(\"wcall(%p): answer: no call object found\\n\", wcall);\n\t\treturn ENOTSUP;\n\t}\n\tset_state(wcall, WCALL_STATE_ANSWERED);\n\n\tif (call_type == WCALL_CALL_TYPE_VIDEO) {\n\t\tICALL_CALL(wcall->icall,\n\t\t\t set_video_send_state,\n\t\t\t ICALL_VIDEO_STATE_STARTED);\n\t}\n\telse {\n\t\tICALL_CALL(wcall->icall,\n\t\t\t set_video_send_state,\n\t\t\t ICALL_VIDEO_STATE_STOPPED);\n\t}\n\t\n\terr = ICALL_CALLE(wcall->icall, answer,\n\t\t\t call_type, cbr);\n\n\treturn err;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "a[\"for\"];if(!f||f.call(this,c)!==false){b.getContentElement(d[0],d[1]).submit();this.disable()}};b.on(\"load\",function(){b.getContentElement(a[\"for\"][0],a[\"for\"][1])._.buttons.push(e)});CKEDITOR.ui.dialog.button.call(this,b,c,d)}},html:function(){var b=/^\\s*<[\\w:]+\\s+([^>]*)?>/,a=/^(\\s*<[\\w:]+(?:\\s+[^>]*)?)((?:.|\\r|\\n)+)$/,d=/\\/$/;return function(e,c,f){if(!(3>arguments.length)){var h=[],g=c.html;\"<\"!=g.charAt(0)&&(g=\"\"+g+\"\");var k=c.focus;if(k){var j=this.focus;this.focus=function(){(\"function\"==\ntypeof k?k:j).call(this);this.fire(\"focus\")};c.isFocusable&&(this.isFocusable=this.isFocusable);this.keyboardFocusable=!0}CKEDITOR.ui.dialog.uiElement.call(this,e,c,h,\"span\",null,null,\"\");h=h.join(\"\").match(b);g=g.match(a)||[\"\",\"\",\"\"];d.test(g[1])&&(g[1]=g[1].slice(0,-1),g[2]=\"/\"+g[2]);f.push([g[1],\" \",h[1]||\"\",g[2]].join(\"\"))}}}(),fieldset:function(b,a,d,e,c){var f=c.label;this._={children:a};CKEDITOR.ui.dialog.uiElement.call(this,b,c,e,\"fieldset\",null,null,function(){var a=[];f&&a.push(\"mmalloc;\n\tmm_memvalid(mmold, mm, sizeof(*mm));\n\n\tmmalloc = mm_create(NULL, mm->size);\n\tmm = mm_xmalloc(mmalloc, sizeof(struct mm_master));\n\tmemcpy(mm, *pmm, sizeof(struct mm_master));\n\tmm->mmalloc = mmalloc;\n\n\trb_free = mm->rb_free;\n\trb_allocated = mm->rb_allocated;\n\n\tRB_INIT(&mm->rb_free);\n\tRB_INIT(&mm->rb_allocated);\n\n\tmm_sync_list(&rb_free, &mm->rb_free, mm, mmold);\n\tmm_sync_list(&rb_allocated, &mm->rb_allocated, mm, mmold);\n\n\tmm_destroy(mmold);\n\n\t*pmm = mm;\n\t*pmmalloc = mmalloc;\n\n\tdebug3(\"%s: Share sync end\", __func__);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it { should contain_rvm_wrapper('god').with_prefix('bootup') }", "label": 0, "label_name": "vulnerable"} -{"code": "S&&S(La)}};za.onerror=function(wa){null!=S&&S(wa)};za.src=ua}else L()}catch(wa){null!=S&&S(wa)}});$a.onerror=function(L){null!=S&&S(L)};Aa&&this.graph.addSvgShadow(Ua);this.graph.mathEnabled&&this.addMathCss(Ua);var z=mxUtils.bind(this,function(){try{null!=this.resolvedFontCss&&this.addFontCss(Ua,this.resolvedFontCss),$a.src=Editor.createSvgDataUri(mxUtils.getXml(Ua))}catch(L){null!=S&&S(L)}});this.embedExtFonts(mxUtils.bind(this,function(L){try{null!=L&&this.addFontCss(Ua,L),this.loadFonts(z)}catch(M){null!=", "label": 1, "label_name": "safe"} -{"code": " $this->token = array(\n 'name' => strtoupper($char),\n 'type' => self::DOCTYPE,\n 'error' => true\n );\n\n $this->state = 'doctypeName';\n\n } elseif ($char === '>') {", "label": 1, "label_name": "safe"} -{"code": "\t\taddChangeLogEntry($request[\"logid\"], NULL, unixToDatetime($end),\n\t\t $request['start'], NULL, NULL, 0);\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 44,\n\t\t 'errormsg' => 'concurrent license restriction');\n\t}", "label": 1, "label_name": "safe"} -{"code": "sixel_allocator_malloc(\n sixel_allocator_t /* in */ *allocator, /* allocator object */\n size_t /* in */ n) /* allocation size */\n{\n /* precondition */\n assert(allocator);\n assert(allocator->fn_malloc);\n\n if (n == 0) {\n sixel_helper_set_additional_message(\n \"sixel_allocator_malloc: called with n == 0\");\n return NULL;\n }\n\n if (n > SIXEL_ALLOCATE_BYTES_MAX) {\n return NULL;\n }\n\n return allocator->fn_malloc(n);\n}", "label": 1, "label_name": "safe"} -{"code": "fn should_stream_web_content() {\n\t// given\n\tlet (server, fetch) = serve_with_fetch(\"token\", \"https://parity.io\");\n\n\t// when\n\tlet response = request(server,\n\t\t\"\\\n\t\t\tGET / HTTP/1.1\\r\\n\\\n\t\t\tHost: EHQPPSBE5DM78X3GECX2YBVGC5S6JX3S5SMPY.web.web3.site\\r\\n\\\n\t\t\tConnection: close\\r\\n\\\n\t\t\t\\r\\n\\\n\t\t\"\n\t);\n\n\t// then\n\tresponse.assert_status(\"HTTP/1.1 200 OK\");\n\tassert_security_headers_for_embed(&response.headers);\n\n\tfetch.assert_requested(\"https://parity.io/\");\n\tfetch.assert_no_more_requests();\n}", "label": 1, "label_name": "safe"} -{"code": " private static function makeEnum($in) {\n return new HTMLPurifier_AttrDef_Clone(new HTMLPurifier_AttrDef_Enum(explode(',', $in)));\n }", "label": 1, "label_name": "safe"} -{"code": "\tprivate function _lastrevisionbefore( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect( [ 'rev.revactor_rev', 'rev.revactor_timestamp' ] );\n\t\t// tell the query optimizer not to look at rows that the following subquery will filter out anyway\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp < ' . $this->convertTimestamp( $option )\n\t\t\t]\n\t\t);\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp = (SELECT MAX(rev_aux_bef.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_bef WHERE rev_aux_bef.revactor_page=rev.revactor_page AND rev_aux_bef.revactor_timestamp < ' . $this->convertTimestamp( $option ) . ')'\n\t\t\t]\n\t\t);\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def test_received_bad_host_header(self):\n from waitress.utilities import BadRequest\n\n data = b\"\"\"\\\nHTTP/1.0 GET /foobar\n Host: foo\n\n\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 33)\n self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.error.__class__, BadRequest)", "label": 0, "label_name": "vulnerable"} -{"code": "function loadLocale(name) {\n var oldLocale = null,\n aliasedRequire;\n // TODO: Find a better way to register and load all the locales in Node\n if (\n locales[name] === undefined &&\n typeof module !== 'undefined' &&\n module &&\n module.exports &&\n isLocaleNameSane(name)\n ) {\n try {\n oldLocale = globalLocale._abbr;\n aliasedRequire = require;\n aliasedRequire('./locale/' + name);\n getSetGlobalLocale(oldLocale);\n } catch (e) {\n // mark as not found to avoid repeating expensive file require call causing high CPU\n // when trying to find en-US, en_US, en-us for every format call\n locales[name] = null; // null means not found\n }\n }\n return locales[name];\n}", "label": 1, "label_name": "safe"} -{"code": "static void handle_put_publish(struct http_conn *conn,\n\t\t\t const struct http_msg *msg,\n\t\t\t struct mbuf *mb, size_t clen)\n{\n\tstruct ident_entry *ie = NULL;\n\tstruct pl pl;\n\tchar *key = NULL;\n\tint err;\n\n\terr = re_regex(msg->prm.p, msg->prm.l, \"?pairid=[0-9]+\", &pl);\n\tif (err) {\n\t\twarning(\"invalid input\\n\");\n\t\tgoto out;\n\t}\n\n\tpl_strdup(&key, &pl);\n\n\tie = dict_lookup(verifyd.idents, key);\n\tif (!ie) {\n\t\tinfo(\"publish: pairing-id %s not found\\n\", key);\n\t\thttp_ereply(conn, 404, \"Not found\");\n\t\tgoto out;\n\t}\n\n\tdebug(\"publish: saving content(%zu): %b\\n\",\n\t\t clen, mbuf_buf(mb), mbuf_get_left(mb));\n\n\tmbuf_strdup(mb, &ie->content.publish, clen);\n\n\thttp_reply(conn, 200, \"OK\", NULL);\n\n\thttp_conn_close(conn);\n\n out:\n\tmem_deref(key);\n}", "label": 1, "label_name": "safe"} -{"code": "\tpublic boolean importWiki(File file, String filename, File targetDirectory) {\n\t\ttry {\n\t\t\tPath path = FileResource.getResource(file, filename);\n\t\t\tif(path == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tPath destDir = targetDirectory.toPath();\n\t\t\tFiles.walkFileTree(path, new ImportVisitor(destDir));\n\t\t\tPathUtils.closeSubsequentFS(path);\n\t\t\treturn true;\n\t\t} catch (IOException e) {\n\t\t\tlog.error(\"\", e);\n\t\t\treturn false;\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public static function dropdown($vars) {\n if(is_array($vars)){\n //print_r($vars);\n $name = $vars['name'];\n $where = \"WHERE \";\n if(isset($vars['parent'])) {\n $where .= \" `parent` = '{$vars['parent']}' \";\n }else{\n $where .= \"1 \";\n }\n $order_by = \"ORDER BY \";\n if(isset($vars['order_by'])) {\n $order_by .= \" {$vars['order_by']} \";\n }else{\n $order_by .= \" `name` \";\n }\n if (isset($vars['sort'])) {\n $sort = \" {$vars['sort']}\";\n }else{\n $sort = \" ASC\";\n }\n }\n $cat = Db::result(\"SELECT * FROM `cat` {$where} {$order_by} {$sort}\");\n //print_r($cat);\n $drop = \"\";\n\n return $drop;\n }", "label": 1, "label_name": "safe"} -{"code": " public function test_parseData_internalUnescapedAmpersand()\n {\n $this->assertParseData('Procter & Gamble');\n }", "label": 1, "label_name": "safe"} -{"code": "function reducer(result, arg)\n{\n arg = arg.split('=')\n\n // Get key node\n const keypath = arg.shift().split('.')\n\n let key = keypath.shift()\n let node = result\n\n while(keypath.length)\n {\n node[key] = node[key] || {}\n node = node[key]\n\n key = keypath.shift()\n }\n\n // Get value\n let val = true\n if(arg.length)\n {\n val = arg.join('=').split(',')\n if(val.length === 1) val = val[0]\n }\n\n // Store value\n node[key] = val\n\n return result\n}", "label": 0, "label_name": "vulnerable"} -{"code": "ikev1_sub_print(netdissect_options *ndo,\n\t\tu_char np, const struct isakmp_gen *ext, const u_char *ep,\n\t\tuint32_t phase, uint32_t doi, uint32_t proto, int depth)\n{\n\tconst u_char *cp;\n\tint i;\n\tstruct isakmp_gen e;\n\n\tcp = (const u_char *)ext;\n\n\twhile (np) {\n\t\tND_TCHECK(*ext);\n\n\t\tUNALIGNED_MEMCPY(&e, ext, sizeof(e));\n\n\t\tND_TCHECK2(*ext, ntohs(e.len));\n\n\t\tdepth++;\n\t\tND_PRINT((ndo,\"\\n\"));\n\t\tfor (i = 0; i < depth; i++)\n\t\t\tND_PRINT((ndo,\" \"));\n\t\tND_PRINT((ndo,\"(\"));\n\t\tcp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);\n\t\tND_PRINT((ndo,\")\"));\n\t\tdepth--;\n\n\t\tif (cp == NULL) {\n\t\t\t/* Zero-length subitem */\n\t\t\treturn NULL;\n\t\t}\n\n\t\tnp = e.np;\n\t\text = (const struct isakmp_gen *)cp;\n\t}\n\treturn cp;\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(np)));\n\treturn NULL;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "inline typename V::VariantType FBUnserializer::unserialize(\n folly::StringPiece serialized) {\n\n FBUnserializer unserializer(serialized);\n return unserializer.unserializeThing(0);\n}", "label": 1, "label_name": "safe"} -{"code": " public function testEnvParametersResourceIsAdded()\n {\n $container = new ContainerBuilder();\n $kernel = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Tests\\Fixtures\\KernelForTest')\n ->disableOriginalConstructor()\n ->setMethods(array('getContainerBuilder', 'prepareContainer', 'getCacheDir', 'getLogDir'))\n ->getMock();\n $kernel->expects($this->any())\n ->method('getContainerBuilder')\n ->will($this->returnValue($container));\n $kernel->expects($this->any())\n ->method('prepareContainer')\n ->will($this->returnValue(null));\n $kernel->expects($this->any())\n ->method('getCacheDir')\n ->will($this->returnValue(sys_get_temp_dir()));\n $kernel->expects($this->any())\n ->method('getLogDir')\n ->will($this->returnValue(sys_get_temp_dir()));\n\n $reflection = new \\ReflectionClass(get_class($kernel));\n $method = $reflection->getMethod('buildContainer');\n $method->setAccessible(true);\n $method->invoke($kernel);\n\n $found = false;\n foreach ($container->getResources() as $resource) {\n if ($resource instanceof EnvParametersResource) {\n $found = true;\n break;\n }\n }\n\n $this->assertTrue($found);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "void Mounter::umount(const QString &mountPoint, int pid)\n{\n if (calledFromDBus()) {\n registerPid(pid);\n }\n\n if (mpOk(mountPoint)) {\n QProcess *proc=new QProcess(this);\n connect(proc, SIGNAL(finished(int)), SLOT(umountResult(int)));\n proc->start(\"umount\", QStringList() << mountPoint);\n proc->setProperty(\"mp\", mountPoint);\n proc->setProperty(\"pid\", pid);\n procCount++;\n } else {\n emit umountStatus(mountPoint, pid, -1);\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function flagsToHuman(flags) {\n const ret = [];\n\n for (const [name, value] of Object.entries(OPEN_MODE)) {\n if (flags & value)\n ret.push(name);\n }\n\n return ret.join(' | ');\n}", "label": 1, "label_name": "safe"} -{"code": "passwordComplexity.validate = password => {\n const response = passwordStrength(password, passwordComplexityOptions)\n return !(response.id === 0 || response.id === 1)\n}", "label": 1, "label_name": "safe"} -{"code": "App.Actions.DB.update_dns_record_hint = function(elm, hint) {\n // clean hint\n if (hint.trim() == '') {\n $(elm).parent().find('.hint').html('');\n }\n\n // set domain name without rec in case of @ entries\n if (hint == '@') {\n hint = '';\n }\n\n // dont show pregix if domain name = rec value\n if (hint == GLOBAL.DNS_REC_PREFIX + '.') {\n hint = '';\n }\n\n // add dot at the end if needed\n if (hint != '' && hint.slice(-1) != '.') {\n hint += '.';\n }\n\n $(elm).parent().find('.hint').text(hint + GLOBAL.DNS_REC_PREFIX);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "linkaddr_string(netdissect_options *ndo, const u_char *ep,\n\t\tconst unsigned int type, const unsigned int len)\n{\n\tregister u_int i;\n\tregister char *cp;\n\tregister struct enamemem *tp;\n\n\tif (len == 0)\n\t\treturn (\"\");\n\n\tif (type == LINKADDR_ETHER && len == ETHER_ADDR_LEN)\n\t\treturn (etheraddr_string(ndo, ep));\n\n\tif (type == LINKADDR_FRELAY)\n\t\treturn (q922_string(ndo, ep, len));\n\n\ttp = lookup_bytestring(ndo, ep, len);\n\tif (tp->e_name)\n\t\treturn (tp->e_name);\n\n\ttp->e_name = cp = (char *)malloc(len*3);\n\tif (tp->e_name == NULL)\n\t\t(*ndo->ndo_error)(ndo, \"linkaddr_string: malloc\");\n\t*cp++ = hex[*ep >> 4];\n\t*cp++ = hex[*ep++ & 0xf];\n\tfor (i = len-1; i > 0 ; --i) {\n\t\t*cp++ = ':';\n\t\t*cp++ = hex[*ep >> 4];\n\t\t*cp++ = hex[*ep++ & 0xf];\n\t}\n\t*cp = '\\0';\n\treturn (tp->e_name);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function permissions_all() {\n //set the permissions array\n $perms = array();\n foreach ($this->permissions as $perm => $name) {\n if (!in_array($perm, $this->remove_permissions)) $perms[$perm] = $name;\n }\n $perms = array_merge($perms, $this->m_permissions, $this->add_permissions, $this->manage_permissions);\n return $perms;\n }", "label": 1, "label_name": "safe"} -{"code": " public function test()\n {\n $this->assertDef('1');\n $this->assertDef('0');\n\n $this->assertDef('2px', '2'); // rm px suffix\n\n $this->assertDef('dfs', false); // totally invalid value\n\n // conceivably we could repair this value, but we won't for now\n $this->assertDef('9in', false);\n\n // test trim\n $this->assertDef(' 45 ', '45');\n\n // no negatives\n $this->assertDef('-2', '0');\n\n // remove empty\n $this->assertDef('', false);\n\n // round down\n $this->assertDef('4.9', '4');\n\n }", "label": 1, "label_name": "safe"} -{"code": " $attr = substr($attr, 0, strlen($attr) - 1); // remove trailing ]\n $attr = explode('|', $attr);\n foreach ($attr as $key) {\n $attributes[\"$element.$key\"] = true;\n }\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic void testMatchType() {\n\n\t\tJWKMatcher matcher = new JWKMatcher.Builder().keyType(KeyType.RSA).build();\n\n\t\tassertTrue(matcher.matches(new RSAKey.Builder(new Base64URL(\"n\"), new Base64URL(\"e\")).keyID(\"1\").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(\"kty=RSA\", matcher.toString());\n\t}", "label": 1, "label_name": "safe"} -{"code": "TEST(BasicFlatBufferModel, TestHandleMalformedModel) {\n const auto model_paths = {\n // These models use the same tensor as both input and ouput of a node\n \"tensorflow/lite/testdata/add_shared_tensors.bin\",\n };\n\n for (const auto& model_path : model_paths) {\n std::unique_ptr model =\n FlatBufferModel::BuildFromFile(model_path);\n ASSERT_NE(model, nullptr);\n\n tflite::ops::builtin::BuiltinOpResolver resolver;\n InterpreterBuilder builder(*model, resolver);\n std::unique_ptr interpreter;\n ASSERT_EQ(builder(&interpreter), kTfLiteOk);\n ASSERT_NE(interpreter, nullptr);\n ASSERT_NE(interpreter->AllocateTensors(), kTfLiteOk);\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static int hash_recvmsg(struct kiocb *unused, struct socket *sock,\n\t\t\tstruct msghdr *msg, size_t len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct hash_ctx *ctx = ask->private;\n\tunsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req));\n\tint err;\n\n\tif (len > ds)\n\t\tlen = ds;\n\telse if (len < ds)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\tmsg->msg_namelen = 0;\n\n\tlock_sock(sk);\n\tif (ctx->more) {\n\t\tctx->more = 0;\n\t\tahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);\n\t\terr = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),\n\t\t\t\t\t\t &ctx->completion);\n\t\tif (err)\n\t\t\tgoto unlock;\n\t}\n\n\terr = memcpy_toiovec(msg->msg_iov, ctx->result, len);\n\nunlock:\n\trelease_sock(sk);\n\n\treturn err ?: len;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testAddServiceIdWithUnsupportedCharacters()\n {\n $class = 'Symfony_DI_PhpDumper_Test_Unsupported_Characters';\n $container = new ContainerBuilder();\n $container->setParameter(\"'\", 'oh-no');\n $container->register(\"foo*/oh-no\", 'FooClass')->setPublic(true);\n $container->register('bar$', 'FooClass')->setPublic(true);\n $container->register('bar$!', 'FooClass')->setPublic(true);\n $container->compile();\n $dumper = new PhpDumper($container);\n\n $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_unsupported_characters.php', $dumper->dump(['class' => $class]));\n\n require_once self::$fixturesPath.'/php/services_unsupported_characters.php';\n\n $this->assertTrue(method_exists($class, 'getFooOhNoService'));\n $this->assertTrue(method_exists($class, 'getBarService'));\n $this->assertTrue(method_exists($class, 'getBar2Service'));\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"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 assert(pow((float) r+1, dim) > entries);\n assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above\n return r;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "SYSCALL_DEFINE2(osf_getdomainname, char __user *, name, int, namelen)\n{\n\tunsigned len;\n\tint i;\n\n\tif (!access_ok(VERIFY_WRITE, name, namelen))\n\t\treturn -EFAULT;\n\n\tlen = namelen;\n\tif (len > 32)\n\t\tlen = 32;\n\n\tdown_read(&uts_sem);\n\tfor (i = 0; i < len; ++i) {\n\t\t__put_user(utsname()->domainname[i], name + i);\n\t\tif (utsname()->domainname[i] == '\\0')\n\t\t\tbreak;\n\t}\n\tup_read(&uts_sem);\n\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "static int adis_update_scan_mode_burst(struct iio_dev *indio_dev,\n\tconst unsigned long *scan_mask)\n{\n\tstruct adis *adis = iio_device_get_drvdata(indio_dev);\n\tunsigned int burst_length;\n\tu8 *tx;\n\n\t/* All but the timestamp channel */\n\tburst_length = (indio_dev->num_channels - 1) * sizeof(u16);\n\tburst_length += adis->burst->extra_len;\n\n\tadis->xfer = kcalloc(2, sizeof(*adis->xfer), GFP_KERNEL);\n\tif (!adis->xfer)\n\t\treturn -ENOMEM;\n\n\tadis->buffer = kzalloc(burst_length + sizeof(u16), GFP_KERNEL);\n\tif (!adis->buffer)\n\t\treturn -ENOMEM;\n\n\ttx = adis->buffer + burst_length;\n\ttx[0] = ADIS_READ_REG(adis->burst->reg_cmd);\n\ttx[1] = 0;\n\n\tadis->xfer[0].tx_buf = tx;\n\tadis->xfer[0].bits_per_word = 8;\n\tadis->xfer[0].len = 2;\n\tadis->xfer[1].rx_buf = adis->buffer;\n\tadis->xfer[1].bits_per_word = 8;\n\tadis->xfer[1].len = burst_length;\n\n\tspi_message_init(&adis->msg);\n\tspi_message_add_tail(&adis->xfer[0], &adis->msg);\n\tspi_message_add_tail(&adis->xfer[1], &adis->msg);\n\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function approve() {\n expHistory::set('editable', $this->params);\n\n /* The global constants can be overriden by passing appropriate params */\n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for note to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n\n $simplenote = new expSimpleNote($this->params['id']);\n assign_to_template(array(\n 'simplenote'=>$simplenote,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'tab'=>$this->params['tab']\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "void AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride,\n int pad_width, int pad_height, int filter_width,\n int filter_height, int32 output_activation_min,\n int32 output_activation_max, uint8* output_data,\n const Dims<4>& output_dims) {\n AveragePool(input_data, input_dims, stride, stride, pad_width, pad_height,\n filter_width, filter_height, output_activation_min,\n output_activation_max, output_data, output_dims);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function exportAsCSV(scope) {\r\n exportHTML = $(\"#exportButton\").html()\r\n var csvScope = null\r\n var filename = campaign.name + ' - ' + capitalize(scope) + '.csv'\r\n switch (scope) {\r\n case \"results\":\r\n csvScope = campaign.results\r\n break;\r\n case \"events\":\r\n csvScope = campaign.timeline\r\n break;\r\n }\r\n if (!csvScope) {\r\n return\r\n }\r\n $(\"#exportButton\").html('')\r\n var csvString = Papa.unparse(csvScope, {\r\n 'escapeFormulae': true\r\n })\r\n var csvData = new Blob([csvString], {\r\n type: 'text/csv;charset=utf-8;'\r\n });\r\n if (navigator.msSaveBlob) {\r\n navigator.msSaveBlob(csvData, filename);\r\n } else {\r\n var csvURL = window.URL.createObjectURL(csvData);\r\n var dlLink = document.createElement('a');\r\n dlLink.href = csvURL;\r\n dlLink.setAttribute('download', filename)\r\n document.body.appendChild(dlLink)\r\n dlLink.click();\r\n document.body.removeChild(dlLink)\r\n }\r\n $(\"#exportButton\").html(exportHTML)\r\n}\r", "label": 1, "label_name": "safe"} -{"code": " public function testNonSharedServicesReturnsDifferentInstances()\n {\n $builder = new ContainerBuilder();\n $builder->register('bar', 'stdClass')->setShared(false);\n\n $this->assertNotSame($builder->get('bar'), $builder->get('bar'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "pci_lintr_assert(struct pci_vdev *dev)\n{\n\tif (dev->lintr.pin <= 0) {\n\t\tpr_warn(\"%s: Invalid intr pin on dev [%s]\\n\", __func__, dev->name);\n\t\treturn;\n\t}\n\n\tpthread_mutex_lock(&dev->lintr.lock);\n\tif (dev->lintr.state == IDLE) {\n\t\tif (pci_lintr_permitted(dev)) {\n\t\t\tdev->lintr.state = ASSERTED;\n\t\t\tpci_irq_assert(dev);\n\t\t} else\n\t\t\tdev->lintr.state = PENDING;\n\t}\n\tpthread_mutex_unlock(&dev->lintr.lock);\n}", "label": 1, "label_name": "safe"} -{"code": "def format_runtime(runtime):\n ret_val = \"\"\n if runtime.days:\n ret_val = format_unit(runtime.days, 'duration-day', length=\"long\", locale=get_locale()) + ', '\n mins, seconds = divmod(runtime.seconds, 60)\n hours, minutes = divmod(mins, 60)\n # ToDo: locale.number_symbols._data['timeSeparator'] -> localize time separator ?\n if hours:\n ret_val += '{:d}:{:02d}:{:02d}s'.format(hours, minutes, seconds)\n elif minutes:\n ret_val += '{:2d}:{:02d}s'.format(minutes, seconds)\n else:\n ret_val += '{:2d}s'.format(seconds)\n return ret_val", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public function testRemoveCurlAuthorizationOptionsOnRedirectCrossSchemeSamePort($auth)\n {\n if (!defined('\\CURLOPT_HTTPAUTH')) {\n self::markTestSkipped('ext-curl is required for this test');\n }\n\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://example.com:80?a=b']),\n static function (RequestInterface $request, $options) {\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_HTTPAUTH]),\n 'curl options still contain CURLOPT_HTTPAUTH entry'\n );\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_USERPWD]),\n 'curl options still contain CURLOPT_USERPWD entry'\n );\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('https://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);\n }", "label": 1, "label_name": "safe"} -{"code": "const TfLiteTensor* GetIntermediates(TfLiteContext* context,\n const TfLiteNode* node, int index) {\n const int tensor_index = ValidateTensorIndexing(\n context, index, node->intermediates->size, node->intermediates->data);\n if (tensor_index < 0) {\n return nullptr;\n }\n return GetTensorAtIndex(context, tensor_index);\n}", "label": 1, "label_name": "safe"} -{"code": " createTreeNode: function(nodeData, target) {\n var nodeName = nodeData.name;\n if(typeof nodeName == 'object') {\n nodeName = nodeName.name;\n }\n \n var newNodeRecord = new Tine.Filemanager.Model.Node(nodeData);\n \n var newNode = new Ext.tree.AsyncTreeNode({\n text: 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": 0, "label_name": "vulnerable"} -{"code": " public static function dropdown($vars) {\n if(is_array($vars)){\n //print_r($vars);\n $name = $vars['name'];\n $where = \"WHERE \";\n if(isset($vars['parent'])) {\n $where .= \" `parent` = '{$vars['parent']}' \";\n }else{\n $where .= \"1 \";\n }\n $order_by = \"ORDER BY \";\n if(isset($vars['order_by'])) {\n $order_by .= \" {$vars['order_by']} \";\n }else{\n $order_by .= \" `name` \";\n }\n if (isset($vars['sort'])) {\n $sort = \" {$vars['sort']}\";\n }\n }\n $cat = Db::result(\"SELECT * FROM `cat` {$where} {$order_by} {$sort}\");\n $drop = \"\";\n\n return $drop;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $callback = function($str) {\n return ord($str);\n };", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\tfb['set' + capName] = function (value) {\n\n\t\t\t\tif (fbPlayer !== null) {\n\n\t\t\t\t\tswitch (propName) {\n\t\t\t\t\t\tcase 'src':\n\t\t\t\t\t\t\tvar url = typeof value === 'string' ? value : value[0].src;\n\t\t\t\t\t\t\tsrc = url;\n\n\t\t\t\t\t\t\tfbContainer.remove();\n\t\t\t\t\t\t\tfbContainer = document.createElement('div');\n\t\t\t\t\t\t\tfbContainer.id = fb.id;\n\t\t\t\t\t\t\tfbContainer.className = 'fb-video';\n\t\t\t\t\t\t\tfbContainer.setAttribute('data-href', url);\n\t\t\t\t\t\t\tfbContainer.setAttribute('data-allowfullscreen', 'true');\n\t\t\t\t\t\t\tfbContainer.setAttribute('data-controls', 'false');\n\n\t\t\t\t\t\t\tmediaElement.originalNode.parentNode.insertBefore(fbContainer, mediaElement.originalNode);\n\t\t\t\t\t\t\tmediaElement.originalNode.style.display = 'none';\n\n\t\t\t\t\t\t\tFacebookApi.load({\n\t\t\t\t\t\t\t\tlang: fb.options.lang,\n\t\t\t\t\t\t\t\tid: fb.id\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tFB.XFBML.parse();\n\n\t\t\t\t\t\t\tif (autoplay) {\n\t\t\t\t\t\t\t\tfbPlayer.play();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'currentTime':\n\t\t\t\t\t\t\tfbPlayer.seek(value);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'muted':\n\t\t\t\t\t\t\tif (value) {\n\t\t\t\t\t\t\t\tfbPlayer.mute();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tfbPlayer.unmute();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsetTimeout(function () {\n\t\t\t\t\t\t\t\tvar event = mejs.Utils.createEvent('volumechange', fb);\n\t\t\t\t\t\t\t\tmediaElement.dispatchEvent(event);\n\t\t\t\t\t\t\t}, 50);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'volume':\n\t\t\t\t\t\t\tfbPlayer.setVolume(value);\n\t\t\t\t\t\t\tsetTimeout(function () {\n\t\t\t\t\t\t\t\tvar event = mejs.Utils.createEvent('volumechange', fb);\n\t\t\t\t\t\t\t\tmediaElement.dispatchEvent(event);\n\t\t\t\t\t\t\t}, 50);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'readyState':\n\t\t\t\t\t\t\tvar event = mejs.Utils.createEvent('canplay', fb);\n\t\t\t\t\t\t\tmediaElement.dispatchEvent(event);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tapiStack.push({ type: 'set', propName: propName, value: value });\n\t\t\t\t}\n\t\t\t};", "label": 0, "label_name": "vulnerable"} -{"code": " def test_verified_user_has_no_change_user_perm(self, verified_user):\n \"\"\"Sanity check.\"\"\"\n assert not verified_user.has_perm(\"user.change_user\")", "label": 1, "label_name": "safe"} -{"code": " final public function getName()\n {\n if (null !== $this->name) {\n return $this->name;\n }\n\n $name = get_class($this);\n $pos = strrpos($name, '\\\\');\n\n return $this->name = false === $pos ? $name : substr($name, $pos + 1);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "set PipeSocketHandler::listen(const SocketEndpoint& endpoint) {\n lock_guard guard(globalMutex);\n\n string pipePath = endpoint.name();\n if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {\n throw runtime_error(\"Tried to listen twice on the same path\");\n }\n\n sockaddr_un local;\n\n int fd = socket(AF_UNIX, SOCK_STREAM, 0);\n FATAL_FAIL(fd);\n initServerSocket(fd);\n local.sun_family = AF_UNIX; /* local is declared before socket() ^ */\n strcpy(local.sun_path, pipePath.c_str());\n unlink(local.sun_path);\n\n FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));\n ::listen(fd, 5);\n#ifndef WIN32\n FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));\n#endif\n\n pipeServerSockets[pipePath] = set({fd});\n return pipeServerSockets[pipePath];\n}", "label": 0, "label_name": "vulnerable"} -{"code": " PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);\n } else {\n PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['SignonURL']);\n }\n\n if (!defined('TESTSUITE')) {\n exit();\n } else {\n return false;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function p(a){for(var a=(\"\"+a).split(\",\"),b=0,e=a.length;b_joinPath($dir, $name);\n return $this->connect->put($path, $fp)\n ? $path\n : false;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function transform($attr, $config, $context)\n {\n if (isset($attr['rel'])) {\n $rels = explode(' ', $attr['rel']);\n } else {\n $rels = array();\n }\n if (isset($attr['target']) && !in_array('noopener', $rels)) {\n $rels[] = 'noopener';\n }\n if (!empty($rels) || isset($attr['rel'])) {\n $attr['rel'] = implode(' ', $rels);\n }\n\n return $attr;\n }", "label": 1, "label_name": "safe"} -{"code": " $this->headerLines = ['Host' => [$host]] + $this->headerLines;", "label": 0, "label_name": "vulnerable"} -{"code": "pci_lintr_assert(struct pci_vdev *dev)\n{\n\tassert(dev->lintr.pin > 0);\n\n\tpthread_mutex_lock(&dev->lintr.lock);\n\tif (dev->lintr.state == IDLE) {\n\t\tif (pci_lintr_permitted(dev)) {\n\t\t\tdev->lintr.state = ASSERTED;\n\t\t\tpci_irq_assert(dev);\n\t\t} else\n\t\t\tdev->lintr.state = PENDING;\n\t}\n\tpthread_mutex_unlock(&dev->lintr.lock);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public void translate(GeyserSession session, ServerCloseWindowPacket packet) {\n // Sometimes the server can request a window close of ID 0... when the window isn't even open\n // Don't confirm in this instance\n InventoryUtils.closeInventory(session, packet.getWindowId(), (session.getOpenInventory() != null && session.getOpenInventory().getId() == packet.getWindowId()));\n }", "label": 1, "label_name": "safe"} -{"code": "window.parent;q=\"json\"==urlParams.proto?JSON.stringify({event:\"init\"}):urlParams.ready||\"ready\";v.postMessage(q,\"*\");if(\"json\"==urlParams.proto){var y=this.editor.graph.openLink;this.editor.graph.openLink=function(A,z,L){y.apply(this,arguments);v.postMessage(JSON.stringify({event:\"openLink\",href:A,target:z,allowOpener:L}),\"*\")}}};EditorUi.prototype.addEmbedButtons=function(){if(null!=this.menubar&&\"1\"!=urlParams.embedInline){var c=document.createElement(\"div\");c.style.display=\"inline-block\";c.style.position=", "label": 1, "label_name": "safe"} -{"code": "t)for(D=0;D 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": 1, "label_name": "safe"} -{"code": " private function _extract_file($compressed_file_name, $target_file_name = false, $underscore_case = false)\n {\n if (strpos($target_file_name,'..') !== false) {\n return false;\n }\n\n if (strpos($compressed_file_name,'..') !== false) {\n return false;\n }\n\n if (!sizeof($this->compressed_list)) {\n $this->set_debug('Trying to unzip before loading file list... Loading it!');\n $this->_list_files(false, $compressed_file_name);\n }\n\n $fdetails = &$this->compressed_list[$compressed_file_name];\n\n if (!isset($this->compressed_list[$compressed_file_name])) {\n $this->set_error('File \"$compressed_file_name\" is not compressed in the zip.');\n\n return false;\n }\n\n if (substr($compressed_file_name, -1) == '/') {\n $this->set_error('Trying to unzip a folder name \"$compressed_file_name\".');\n\n return false;\n }\n\n if (!$fdetails['uncompressed_size']) {\n $this->set_debug('File \"$compressed_file_name\" is empty.');\n\n return $target_file_name ? file_put_contents($target_file_name, '') : '';\n }\n\n if ($underscore_case) {\n $pathinfo = pathinfo($target_file_name);\n // $pathinfo['filename_new'] = preg_replace('/([^.a-z0-9]+)/i', '_', strtolower($pathinfo['filename']));\n $pathinfo['filename_new'] = ($pathinfo['filename']);\n $target_file_name = $pathinfo['dirname'] . '/' . $pathinfo['filename_new'] . '.' . ($pathinfo['extension']);\n }", "label": 1, "label_name": "safe"} -{"code": "def test_plugins_cli_error_messages_with_example(example):\n result = httpie(*example.split(), no_debug=True)\n assert result.exit_status == ExitStatus.ERROR\n assert 'usage: ' in result.stderr\n assert f'http {example}' in result.stderr\n assert f'https {example}' in result.stderr", "label": 1, "label_name": "safe"} -{"code": "\t\t\t\ttop : parseInt($(document).scrollTop() + ($(window).height() < node.height() ? 2 : ($(window).height() - node.height())/2)),", "label": 0, "label_name": "vulnerable"} -{"code": " def self.get_comment_of(item_id, user_id)\n\n SqlHelper.validate_token([item_id, user_id])\n begin\n comment = Comment.where(\"(user_id=#{user_id.to_i}) and (item_id=#{item_id.to_i}) and (xtype='#{Comment::XTYPE_DIST_ACK}')\").first\n rescue => evar\n Log.add_error(nil, evar)\n end\n\n return comment\n end", "label": 1, "label_name": "safe"} -{"code": " def new\n\n @item = Item.new\n if params[:folder_id].nil? or params[:folder_id].empty?\n my_folder = @login_user.get_my_folder\n if my_folder.nil?\n @item.folder_id = 0\n else\n @item.folder_id = my_folder.id\n end\n else\n @item.folder_id = params[:folder_id].to_i\n end\n @item.xtype= Item::XTYPE_INFO\n @item.layout = 'C'\n\n render(:action => 'edit')\n end", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($var as $key) {\n $new[$key] = true;\n }", "label": 1, "label_name": "safe"} -{"code": " def __init__(self, env):\n self._env = env", "label": 1, "label_name": "safe"} -{"code": "H.x+\" \"+H.y;S=\"\";d=[];for(V=2;Vf;)x.shift()},P=", "label": 0, "label_name": "vulnerable"} -{"code": " array_splice($first, 8 - count($second), 8, $second);\n $aIP = $first;\n unset($first, $second);\n } else {", "label": 1, "label_name": "safe"} -{"code": " $PaymentsNVP .= $CurrentRedeemedOfferVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentRedeemedOfferVar) . $n_item . '=' . urlencode($CurrentRedeemedOfferVal) : '';\n }\n $n_item++;\n } ", "label": 0, "label_name": "vulnerable"} -{"code": " def test_double_linefeed(self):\n self.assertEqual(self._callFUT(b\"\\n\\n\"), -1)", "label": 1, "label_name": "safe"} -{"code": "this.toolbar.staticElements.push(c);c.style.right=\"atlas\"==uiTheme||\"1\"==urlParams.atlas?\"42px\":\"52px\"}};EditorUi.prototype.showImportCsvDialog=function(){null==this.importCsvDialog&&(this.importCsvDialog=new TextareaDialog(this,mxResources.get(\"csv\")+\":\",Editor.defaultCsvValue,mxUtils.bind(this,function(c){this.importCsv(c)}),null,null,620,430,null,!0,!0,mxResources.get(\"import\"),this.isOffline()?null:\"https://drawio-app.com/import-from-csv-to-drawio/\"));this.showDialog(this.importCsvDialog.container,\n640,520,!0,!0,null,null,null,null,!0);this.importCsvDialog.init()};EditorUi.prototype.executeLayoutList=function(c,e){for(var g=this.editor.graph,k=g.getSelectionCells(),m=0;mdal_handle->db_context;\n LDAP *ld = ldap_server_handle->ldap_handle;\n LDAPMessage *result = NULL, *ent;\n char *attrs[] = { \"krbticketpolicyreference\", \"krbprincipalname\", NULL };\n char **values;\n\n LDAP_SEARCH_1(dn, LDAP_SCOPE_BASE, 0, attrs, IGNORE_STATUS);\n if (st != LDAP_SUCCESS)\n return set_ldap_error(context, st, OP_SEARCH);\n\n ent = ldap_first_entry(ld, result);\n CHECK_NULL(ent);\n\n values = ldap_get_values(ld, ent, \"krbticketpolicyreference\");\n if (values != NULL)\n ldap_value_free(values);\n\n values = ldap_get_values(ld, ent, \"krbprincipalname\");\n if (values != NULL) {\n ldap_value_free(values);\n if (nonkrb_only) {\n st = EINVAL;\n k5_setmsg(context, st, _(\"ldap object is already kerberized\"));\n goto cleanup;\n }\n }\n\ncleanup:\n ldap_msgfree(result);\n return st;\n}", "label": 1, "label_name": "safe"} -{"code": "AvahiService::AvahiService(const QString &n, const QString &type, const QString &domain)\n : name(n)\n , port(0)\n{\n static bool registeredTypes=false;\n if (!registeredTypes) {\n qDBusRegisterMetaType >();\n registeredTypes=true;\n }\n\n org::freedesktop::Avahi::Server server(\"org.freedesktop.Avahi\", \"/\", QDBusConnection::systemBus());\n QDBusReply reply=server.ServiceResolverNew(-1, -1, name, type, Avahi::domainToDNS(domain), -1, 8 /*AVAHI_LOOKUP_NO_ADDRESS|AVAHI_LOOKUP_NO_TXT*/);\n\n if (reply.isValid()) {\n resolver=new OrgFreedesktopAvahiServiceResolverInterface(\"org.freedesktop.Avahi\", reply.value().path(), QDBusConnection::systemBus());\n connect(resolver, SIGNAL(Found(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort,const QList&, uint)),\n this, SLOT(resolved(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort, const QList&, uint)));\n connect(resolver, SIGNAL(Failure(QString)), this, SLOT(error(QString)));\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {\n if (tuple[index].has_value()) {\n return Status(errors::InvalidArgument(\n \"The tensor for index '\", index, \"' for key '\", key.scalar()(),\n \"' was already initialized '\", dtypes_.size(), \"'.\"));\n }\n\n return Status::OK();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "window.parent;q=\"json\"==urlParams.proto?JSON.stringify({event:\"init\"}):urlParams.ready||\"ready\";v.postMessage(q,\"*\");if(\"json\"==urlParams.proto){var x=this.editor.graph.openLink;this.editor.graph.openLink=function(A,z,L){x.apply(this,arguments);v.postMessage(JSON.stringify({event:\"openLink\",href:A,target:z,allowOpener:L}),\"*\")}}};EditorUi.prototype.addEmbedButtons=function(){if(null!=this.menubar&&\"1\"!=urlParams.embedInline){var c=document.createElement(\"div\");c.style.display=\"inline-block\";c.style.position=", "label": 0, "label_name": "vulnerable"} -{"code": "static void Rp_test(js_State *J)\n{\n\tjs_Regexp *re;\n\tconst char *text;\n\tint result;\n\tint opts;\n\tResub m;\n\n\tre = js_toregexp(J, 0);\n\ttext = js_tostring(J, 1);\n\n\topts = 0;\n\tif (re->flags & JS_REGEXP_G) {\n\t\tif (re->last > strlen(text)) {\n\t\t\tre->last = 0;\n\t\t\tjs_pushboolean(J, 0);\n\t\t\treturn;\n\t\t}\n\t\tif (re->last > 0) {\n\t\t\ttext += re->last;\n\t\t\topts |= REG_NOTBOL;\n\t\t}\n\t}\n\n\tresult = js_regexec(re->prog, text, &m, opts);\n\tif (result < 0)\n\t\tjs_error(J, \"regexec failed\");\n\tif (result == 0) {\n\t\tif (re->flags & JS_REGEXP_G)\n\t\t\tre->last = re->last + (m.sub[0].ep - text);\n\t\tjs_pushboolean(J, 1);\n\t\treturn;\n\t}\n\n\tif (re->flags & JS_REGEXP_G)\n\t\tre->last = 0;\n\n\tjs_pushboolean(J, 0);\n}", "label": 1, "label_name": "safe"} -{"code": " public static function parseModelName($model) {\n \n\n\n $customModule = Modules::model()->findByAttributes(array(\n 'custom' => 1,\n 'name' => $model,\n ));\n if ($customModule) {\n //$model = $customModule->title;\n $model = Modules::itemDisplayName($customModule->name);\n $model = strtolower($model);\n } else {\n switch ($model) {\n case 'Product':\n $model .= 's'; break;\n case 'Quote':\n $model .= 's'; break;\n case 'Opportunity':\n $model = str_replace('y', 'ies', $model); break;\n }\n $requestedModel = $model;\n $model = Modules::displayName(false, ucfirst($model));\n $model = strtolower($model);\n if (empty($model)) {\n // If the model type couldn't be resolved, check for special cases\n // of models without a dedicated module\n if ($requestedModel === 'AnonContact')\n $model = 'anonymous contact';\n else if ($requestedModel === 'Campaign')\n $model = 'campaign';\n }\n }\n return Yii::t('app', $model);\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public function __construct() {\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "function isBase64URLDot(s) {\n if (s.match(/^[0-9A-Za-z-_.]+$/)) return true;\n return false;\n}", "label": 1, "label_name": "safe"} -{"code": "parse_range(char *str, size_t file_sz, int *nranges)\n{\n\tstatic struct range\t ranges[MAX_RANGES];\n\tint\t\t\t i = 0;\n\tchar\t\t\t*p, *q;\n\n\t/* Extract range unit */\n\tif ((p = strchr(str, '=')) == NULL)\n\t\treturn (NULL);\n\n\t*p++ = '\\0';\n\t/* Check if it's a bytes range spec */\n\tif (strcmp(str, \"bytes\") != 0)\n\t\treturn (NULL);\n\n\twhile ((q = strchr(p, ',')) != NULL) {\n\t\t*q++ = '\\0';\n\n\t\t/* Extract start and end positions */\n\t\tif (parse_range_spec(p, file_sz, &ranges[i]) == 0)\n\t\t\tcontinue;\n\n\t\ti++;\n\t\tif (i == MAX_RANGES)\n\t\t\treturn (NULL);\n\n\t\tp = q;\n\t}\n\n\tif (parse_range_spec(p, file_sz, &ranges[i]) != 0)\n\t\ti++;\n\n\t*nranges = i;\n\treturn (i ? ranges : NULL);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " wsHandler: (conn, req) => {\n conn.write(req.url)\n conn.end()\n }", "label": 1, "label_name": "safe"} -{"code": " default boolean isActive() {\n return true;\n }", "label": 1, "label_name": "safe"} -{"code": "static int get_gate_page(struct mm_struct *mm, unsigned long address,\n\t\tunsigned int gup_flags, struct vm_area_struct **vma,\n\t\tstruct page **page)\n{\n\tpgd_t *pgd;\n\tp4d_t *p4d;\n\tpud_t *pud;\n\tpmd_t *pmd;\n\tpte_t *pte;\n\tint ret = -EFAULT;\n\n\t/* user gate pages are read-only */\n\tif (gup_flags & FOLL_WRITE)\n\t\treturn -EFAULT;\n\tif (address > TASK_SIZE)\n\t\tpgd = pgd_offset_k(address);\n\telse\n\t\tpgd = pgd_offset_gate(mm, address);\n\tBUG_ON(pgd_none(*pgd));\n\tp4d = p4d_offset(pgd, address);\n\tBUG_ON(p4d_none(*p4d));\n\tpud = pud_offset(p4d, address);\n\tBUG_ON(pud_none(*pud));\n\tpmd = pmd_offset(pud, address);\n\tif (!pmd_present(*pmd))\n\t\treturn -EFAULT;\n\tVM_BUG_ON(pmd_trans_huge(*pmd));\n\tpte = pte_offset_map(pmd, address);\n\tif (pte_none(*pte))\n\t\tgoto unmap;\n\t*vma = get_gate_vma(mm);\n\tif (!page)\n\t\tgoto out;\n\t*page = vm_normal_page(*vma, address, *pte);\n\tif (!*page) {\n\t\tif ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))\n\t\t\tgoto unmap;\n\t\t*page = pte_page(*pte);\n\n\t\t/*\n\t\t * This should never happen (a device public page in the gate\n\t\t * area).\n\t\t */\n\t\tif (is_device_public_page(*page))\n\t\t\tgoto unmap;\n\t}\n\tget_page(*page);\nout:\n\tret = 0;\nunmap:\n\tpte_unmap(pte);\n\treturn ret;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "d};return function(c,d){return b(c,d,a)}}return function(b,d){b[a]=d}}function Ma(a){return D(a.aoData,\"_aData\")}function na(a){a.aoData.length=0;a.aiDisplayMaster.length=0;a.aiDisplay.length=0;a.aIds={}}function oa(a,b,c){for(var d=-1,e=0,f=a.length;eb&&a[e]--; -1!=d&&c===k&&a.splice(d,1)}function ea(a,b,c,d){var e=a.aoData[b],f,g=function(c,d){for(;c.childNodes.length;)c.removeChild(c.firstChild);c.innerHTML=B(a,b,d,\"display\")};if(\"dom\"===c||(!c||\"auto\"===c)&&\"dom\"===e.src)e._aData=", "label": 0, "label_name": "vulnerable"} -{"code": "proc_lambda(mrb_state *mrb, mrb_value self)\n{\n mrb_value blk;\n struct RProc *p;\n\n mrb_get_args(mrb, \"&\", &blk);\n if (mrb_nil_p(blk)) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"tried to create Proc object without a block\");\n }\n if (!mrb_proc_p(blk)) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"not a proc\");\n }\n p = mrb_proc_ptr(blk);\n if (!MRB_PROC_STRICT_P(p)) {\n struct RProc *p2 = MRB_OBJ_ALLOC(mrb, MRB_TT_PROC, p->c);\n mrb_proc_copy(p2, p);\n p2->flags |= MRB_PROC_STRICT;\n return mrb_obj_value(p2);\n }\n return blk;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=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, "label_name": "safe"} -{"code": "Editor.commonVertexProperties=[{name:\"colspan\",dispName:\"Colspan\",type:\"int\",min:1,defVal:1,isVisible:function(u,D){D=D.editorUi.editor.graph;return 1==u.vertices.length&&0==u.edges.length&&D.isTableCell(u.vertices[0])}},{name:\"rowspan\",dispName:\"Rowspan\",type:\"int\",min:1,defVal:1,isVisible:function(u,D){D=D.editorUi.editor.graph;return 1==u.vertices.length&&0==u.edges.length&&D.isTableCell(u.vertices[0])}},{type:\"separator\"},{name:\"resizeLastRow\",dispName:\"Resize Last Row\",type:\"bool\",getDefaultValue:function(u,\nD){u=D.editorUi.editor.graph.getCellStyle(1==u.vertices.length&&0==u.edges.length?u.vertices[0]:null);return\"1\"==mxUtils.getValue(u,\"resizeLastRow\",\"0\")},isVisible:function(u,D){D=D.editorUi.editor.graph;return 1==u.vertices.length&&0==u.edges.length&&D.isTable(u.vertices[0])}},{name:\"resizeLast\",dispName:\"Resize Last Column\",type:\"bool\",getDefaultValue:function(u,D){u=D.editorUi.editor.graph.getCellStyle(1==u.vertices.length&&0==u.edges.length?u.vertices[0]:null);return\"1\"==mxUtils.getValue(u,\"resizeLast\",", "label": 1, "label_name": "safe"} -{"code": " public function testRemoveOnlyScriptTagsLegacy()\n {\n $this->config->set('Core.RemoveScriptContents', false);\n $this->assertResult(\n '',\n 'alert();'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "size_t TLSOutStream::length()\n{\n return offset + ptr - start;\n}", "label": 1, "label_name": "safe"} -{"code": "dumpstate(labellist *ll, nfa *nf, int istate)\n{\n nfastate *st;\n int i;\n nfaarc *ar;\n\n printf(\"%c%2d%c\",\n istate == nf->nf_start ? '*' : ' ',\n istate,\n istate == nf->nf_finish ? '.' : ' ');\n st = &nf->nf_state[istate];\n ar = st->st_arc;\n for (i = 0; i < st->st_narcs; i++) {\n if (i > 0)\n printf(\"\\n \");\n printf(\"-> %2d %s\", ar->ar_arrow,\n Ta3Grammar_LabelRepr(&ll->ll_label[ar->ar_label]));\n ar++;\n }\n printf(\"\\n\");\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def execute(op)\n mode = options[:consistency] == :eventual ? :read : :write\n socket = socket_for(mode)\n\n if safe?\n last_error = Protocol::Command.new(\n \"admin\", { getlasterror: 1 }.merge(safety)\n )\n\n socket.execute(op, last_error).documents.first.tap do |result|\n raise Errors::OperationFailure.new(\n op, result\n ) if result[\"err\"] || result[\"errmsg\"]\n end\n else\n socket.execute(op)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it(`builds ${input instanceof Object ? JSON.stringify(input) : input} to \"${output}\"`, () => {\n expect(buildQueryString(input, traditional)).toBe(output);\n });\n });", "label": 1, "label_name": "safe"} -{"code": "function phpAds_clearSession()\n{\n $GLOBALS['session'] = array(\n '__authentic__' => true,\n );\n}", "label": 1, "label_name": "safe"} -{"code": " function display($text, $inline_images=true, $balance=true) {\n // Make showing offsite images optional\n $text = preg_replace_callback('/]*)(src=\"http[^\"]+\")([^>]*)\\/>/',\n function($match) {\n // Drop embedded classes -- they don't refer to ours\n $match = preg_replace('/class=\"[^\"]*\"/', '', $match);\n return sprintf('',\n $match[1], $match[2], $match[3]);\n },\n $text);\n\n if ($balance)\n $text = self::html_balance($text, false);\n\n // make urls clickable.\n $text = Format::clickableurls($text);\n\n if ($inline_images)\n return self::viewableImages($text);\n\n return $text;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it 'adds epel' do\n pp = \"class { 'epel': }\"\n apply_manifest(pp, :catch_failures => true)\n end", "label": 0, "label_name": "vulnerable"} -{"code": "inflect.underscore = function (camel_cased_word) {\n var self;\n self = util.string.gsub(camel_cased_word, /\\./, '/');\n self = util.string.gsub(self, /([A-Z]+)([A-Z][a-z])/, '$1_$2');\n self = util.string.gsub(self, /([a-z\\d])([A-Z])/, '$1_$2');\n self = util.string.gsub(self, /-/, '_');\n return self.toLowerCase();\n};", "label": 0, "label_name": "vulnerable"} -{"code": "this.window.setLocation=function(q,v){var x=window.innerHeight||document.body.clientHeight||document.documentElement.clientHeight;q=Math.max(0,Math.min(q,(window.innerWidth||document.body.clientWidth||document.documentElement.clientWidth)-this.table.clientWidth));v=Math.max(0,Math.min(v,x-this.table.clientHeight-(\"1\"==urlParams.sketch?3:48)));this.getX()==q&&this.getY()==v||mxWindow.prototype.setLocation.apply(this,arguments)};var m=mxUtils.bind(this,function(){var q=this.window.getX(),v=this.window.getY();", "label": 0, "label_name": "vulnerable"} -{"code": "static const char *cache_id(const char *id)\n{\n static char clean[SHORT_STRING];\n mutt_str_strfcpy(clean, id, sizeof(clean));\n mutt_file_sanitize_filename(clean, true);\n return clean;\n}", "label": 1, "label_name": "safe"} -{"code": " def __init__(\n self,\n reactor: IReactorPluggableNameResolver,\n ip_whitelist: Optional[IPSet],\n ip_blacklist: IPSet,", "label": 1, "label_name": "safe"} -{"code": " def max_updates_per_hour=(int)\n merged_name = self.class.cmd_user(@resource[:name])\n mysql([defaults_file, '-e', \"GRANT USAGE ON *.* TO #{merged_name} WITH MAX_UPDATES_PER_HOUR #{int}\"].compact).chomp\n\n max_updates_per_hour == int ? (return true) : (return false)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function approve_submit() {\n global $history;\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for comment to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n $simplenote = new expSimpleNote($this->params['id']);\n //FIXME here is where we might sanitize the note before approving it\n $simplenote->body = $this->params['body'];\n $simplenote->approved = $this->params['approved'];\n $simplenote->save();\n \n $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testEmptyInput()\n {\n $this->assertResult(array());\n }", "label": 1, "label_name": "safe"} -{"code": " private function userCanSeeUserGroups($project_id)\n {\n $project = $this->project_manager->getProject($project_id);\n $user = $this->user_manager->getCurrentUser();\n ProjectAuthorization::userCanAccessProject($user, $project, new URLVerification());\n\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testPsr4CaseMismatch()\n {\n class_exists(__NAMESPACE__.'\\Fixtures\\Psr4CaseMismatch', true);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_create_objectLexerImpl()\n {\n $this->config->set('Core.LexerImpl', new HTMLPurifier_Lexer_DirectLex());\n $lexer = HTMLPurifier_Lexer::create($this->config);\n $this->assertIsA($lexer, 'HTMLPurifier_Lexer_DirectLex');\n }", "label": 1, "label_name": "safe"} -{"code": "static int discovery_stop(struct discovery_client *client)\n{\n\tstruct btd_adapter *adapter = client->adapter;\n\tstruct mgmt_cp_stop_discovery cp;\n\n\t/* Check if there are more client discovering */\n\tif (g_slist_next(adapter->discovery_list)) {\n\t\tdiscovery_remove(client);\n\t\tupdate_discovery_filter(adapter);\n\t\treturn 0;\n\t}\n\n\tset_discovery_discoverable(adapter, false);\n\n\t/*\n\t * In the idle phase of a discovery, there is no need to stop it\n\t * and so it is enough to send out the signal and just return.\n\t */\n\tif (adapter->discovery_enable == 0x00) {\n\t\tdiscovery_remove(client);\n\t\tadapter->discovering = false;\n\t\tg_dbus_emit_property_changed(dbus_conn, adapter->path,\n\t\t\t\t\tADAPTER_INTERFACE, \"Discovering\");\n\n\t\ttrigger_passive_scanning(adapter);\n\n\t\treturn 0;\n\t}\n\n\tcp.type = adapter->discovery_type;\n\tadapter->client = client;\n\n\tmgmt_send(adapter->mgmt, MGMT_OP_STOP_DISCOVERY,\n\t\t\tadapter->dev_id, sizeof(cp), &cp,\n\t\t\tstop_discovery_complete, adapter, NULL);\n\n\treturn -EINPROGRESS;\n}", "label": 1, "label_name": "safe"} -{"code": "\tpublic static function evaluate_search_tree($tree, $join = 'AND', $callback)\n\t{\n\t\t$matches = false;\n\n\t\tforeach($tree as $i => $el)\n\t\t{\n\t\t\t$b = false;\n\t\t\tif($i === 'AND' || $i === 'OR')\n\t\t\t{\n\t\t\t\t$b = self::evaluate_search_tree($el, $i, $callback);\n\t\t\t}\n\t\t\telse if(isset($el['query']))\n\t\t\t{\n\t\t\t\t$b = call_user_func($callback, $el['query']);\n\t\t\t\tif($el['not'])\n\t\t\t\t{\n\t\t\t\t\t$b = !$b;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(is_array($el))\n\t\t\t{\n\t\t\t\t$b = self::evaluate_search_tree($el, $join, $callback);\n\t\t\t}\n\n\t\t\tif($join == 'AND')\n\t\t\t{\n\t\t\t\tif(!$b)\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t$matches = true;\n\t\t\t}\n\t\t\telse if($join == 'OR')\n\t\t\t{\n\t\t\t\tif($b)\n\t\t\t\t{\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\t$matches = $matches || $b;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn $matches;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " fetch: function () {\n var data = Dep.prototype.fetch.call(this);\n data.translatedOptions = {};\n (data[this.name] || []).forEach(function (value) {\n data.translatedOptions[value] = this.$el.find('input[data-name=\"translatedValue\"][data-value=\"'+value+'\"]').val() || value;\n }, this);\n\n return data;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getQueryGroupby()\n {\n return \"a.per_tracker_artifact_id\";\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def destroy\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n workflow = Workflow.find(params[:id])\n\n begin\n workflow.item.destroy\n rescue => evar\n Log.add_error(nil, evar)\n end\n\n my_wf_folder = WorkflowsHelper.get_my_wf_folder(@login_user.id)\n\n sql = WorkflowsHelper.get_list_sql(@login_user.id, my_wf_folder.id)\n @workflows = Workflow.find_by_sql(sql)\n\n render(:partial => 'ajax_workflow', :layout => false)\n end", "label": 1, "label_name": "safe"} -{"code": " public static boolean isValidCallback(String pCallback) {\n Pattern validJavaScriptFunctionNamePattern =\n Pattern.compile(\"^[$A-Z_][0-9A-Z_$]*$\", Pattern.CASE_INSENSITIVE);\n return validJavaScriptFunctionNamePattern.matcher(pCallback).matches();\n }", "label": 1, "label_name": "safe"} -{"code": "Suite.prototype.clone = function() {\n var suite = new Suite(this.title);\n debug('clone');\n suite.ctx = this.ctx;\n suite.timeout(this.timeout());\n suite.slow(this.slow());\n suite.bail(this.bail());\n return suite;\n};", "label": 1, "label_name": "safe"} -{"code": " def find(request)\n get_terminus(request).find(request)\n end", "label": 1, "label_name": "safe"} -{"code": " public function testNoErrors()\n {\n $this->language->returns('getMessage', 'No errors', array('ErrorCollector: No errors'));\n\n $formatted_result = '

No errors

';\n $this->assertIdentical(\n $this->collector->getHTMLFormatted($this->config),\n $formatted_result\n );\n }", "label": 1, "label_name": "safe"} -{"code": " final void addObject(CharSequence name, Iterable values) {\n final AsciiString normalizedName = normalizeName(name);\n requireNonNull(values, \"values\");\n for (Object v : values) {\n requireNonNullElement(values, v);\n addObject(normalizedName, v);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def validate_request(self, request):\n \"\"\"If configured for webhook basic auth, validate request has correct auth.\"\"\"\n if self.basic_auth:\n basic_auth = get_request_basic_auth(request)\n if basic_auth is None or basic_auth not in self.basic_auth:\n # noinspection PyUnresolvedReferences\n raise AnymailWebhookValidationFailure(\n \"Missing or invalid basic auth in Anymail %s webhook\" % self.esp_name)", "label": 0, "label_name": "vulnerable"} -{"code": "Aa.style.padding=\"0px\";Aa.style.boxShadow=\"none\";Aa.className=\"geMenuItem\";Aa.style.display=\"inline-block\";Aa.style.width=\"40px\";Aa.style.height=\"12px\";Aa.style.marginBottom=\"-2px\";Aa.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\";Aa.style.backgroundPosition=\"top center\";Aa.style.backgroundRepeat=\"no-repeat\";Aa.setAttribute(\"title\",\"Minimize\");var za=!1,Ca=mxUtils.bind(this,function(){W.innerHTML=\"\";if(!za){var ua=function(Fa,Ra,db){Fa=X(\"\",Fa.funct,null,Ra,Fa,db);Fa.style.width=\n\"40px\";Fa.style.opacity=\"0.7\";return ya(Fa,null,\"pointer\")},ya=function(Fa,Ra,db){null!=Ra&&Fa.setAttribute(\"title\",Ra);Fa.style.cursor=null!=db?db:\"default\";Fa.style.margin=\"2px 0px\";W.appendChild(Fa);mxUtils.br(W);return Fa};ya(U.sidebar.createVertexTemplate(\"text;strokeColor=none;fillColor=none;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\",60,30,\"Text\",mxResources.get(\"text\"),!0,!1,null,!0,!0),mxResources.get(\"text\")+\" (\"+Editor.ctrlKey+\"+Shift+X)\");ya(U.sidebar.createVertexTemplate(\"shape=note;whiteSpace=wrap;html=1;backgroundOutline=1;fontColor=#000000;darkOpacity=0.05;fillColor=#FFF9B2;strokeColor=none;fillStyle=solid;direction=west;gradientDirection=north;gradientColor=#FFF2A1;shadow=1;size=20;pointerEvents=1;\",", "label": 0, "label_name": "vulnerable"} -{"code": "static int rds_loop_xmit(struct rds_connection *conn, struct rds_message *rm,\n\t\t\t unsigned int hdr_off, unsigned int sg,\n\t\t\t unsigned int off)\n{\n\t/* Do not send cong updates to loopback */\n\tif (rm->m_inc.i_hdr.h_flags & RDS_FLAG_CONG_BITMAP) {\n\t\trds_cong_map_updated(conn->c_fcong, ~(u64) 0);\n\t\treturn sizeof(struct rds_header) + RDS_CONG_MAP_BYTES;\n\t}\n\n\tBUG_ON(hdr_off || sg || off);\n\n\trds_inc_init(&rm->m_inc, conn, conn->c_laddr);\n\t/* For the embedded inc. Matching put is in loop_inc_free() */\n\trds_message_addref(rm);\n\n\trds_recv_incoming(conn, conn->c_laddr, conn->c_faddr, &rm->m_inc,\n\t\t\t GFP_KERNEL, KM_USER0);\n\n\trds_send_drop_acked(conn, be64_to_cpu(rm->m_inc.i_hdr.h_sequence),\n\t\t\t NULL);\n\n\trds_inc_put(&rm->m_inc);\n\n\treturn sizeof(struct rds_header) + be32_to_cpu(rm->m_inc.i_hdr.h_len);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "focus:function(){k.focus()}}};EditorUi.prototype.createUrlParameters=function(c,e,g,k,m,q,v){v=null!=v?v:[];k&&(\"https://viewer.diagrams.net\"==EditorUi.lightboxHost&&\"1\"!=urlParams.dev||v.push(\"lightbox=1\"),\"auto\"!=c&&v.push(\"target=\"+c),null!=e&&e!=mxConstants.NONE&&v.push(\"highlight=\"+(\"#\"==e.charAt(0)?e.substring(1):e)),null!=m&&0& dirs) {\n int i = 0;\n for (const auto& d : dirs) {\n if (IsGlobbingPattern(d)) {\n break;\n }\n i++;\n }\n return i;\n}", "label": 1, "label_name": "safe"} -{"code": " foreach ($attributes as $name) {\n if (!isset($def->info[$element]->attr[$name])) {\n return \"$element.$name\";\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public static function getHelpVersion($version_id) {\n global $db;\n\n return $db->selectValue('help_version', 'version', 'id=\"'.$version_id.'\"');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function pending() {\n// global $db;\n \n // make sure we have what we need.\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('Your subscriber ID was not supplied.'));\n\n // find the subscriber and their pending subscriptions\n $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);\n $subscriber = new subscribers($this->params['id']);\n \n // render the template\n assign_to_template(array(\n 'subscriber'=>$subscriber,\n 'ealerts'=>$ealerts\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def test_proxy_headers(self):\n to_send = (\n \"GET / HTTP/1.0\\n\"\n \"Content-Length: 0\\n\"\n \"Host: www.google.com:8080\\n\"\n \"X-Forwarded-For: 192.168.1.1\\n\"\n \"X-Forwarded-Proto: https\\n\"\n \"X-Forwarded-Port: 5000\\n\\n\"\n )\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(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))\n self.assertIsNone(echo.headers.get(\"X_FORWARDED_PORT\"))\n self.assertEqual(echo.headers[\"HOST\"], \"www.google.com:8080\")\n self.assertEqual(echo.scheme, \"https\")\n self.assertEqual(echo.remote_addr, \"192.168.1.1\")\n self.assertEqual(echo.remote_host, \"192.168.1.1\")", "label": 0, "label_name": "vulnerable"} -{"code": "v8::Local CreateNativeEvent(\n v8::Isolate* isolate,\n v8::Local sender,\n content::RenderFrameHost* frame,\n electron::mojom::ElectronBrowser::MessageSyncCallback callback) {\n v8::Local event;\n if (frame && callback) {\n gin::Handle native_event = Event::Create(isolate);\n native_event->SetCallback(std::move(callback));\n event = v8::Local::Cast(native_event.ToV8());\n } else {\n // No need to create native event if we do not need to send reply.\n event = CreateEvent(isolate);\n }\n\n Dictionary dict(isolate, event);\n dict.Set(\"sender\", sender);\n // Should always set frameId even when callback is null.\n if (frame)\n dict.Set(\"frameId\", frame->GetRoutingID());\n return event;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_AllowedAttributes_local_invalidAttributeDueToMissingElement()\n {\n $this->config->set('HTML.AllowedElements', array('p', 'br'));\n $this->config->set('HTML.AllowedAttributes', 'p.style,foo.style');\n $this->expectError(new PatternExpectation(\"/Cannot allow attribute 'style' if element 'foo' is not allowed\\/supported/\"));\n $this->assertPurification_AllowedAttributes_local_p_style();\n }", "label": 1, "label_name": "safe"} -{"code": " public function testAllRightBrackets()\n {\n $this->assertProduces(']]]]]', ']]]]]');\n }", "label": 1, "label_name": "safe"} -{"code": "X){null!=X.shortcut&&900>n&&!mxClient.IS_IOS?O.firstChild.nextSibling.setAttribute(\"title\",X.shortcut):m.apply(this,arguments)};var q=App.prototype.updateUserElement;App.prototype.updateUserElement=function(){q.apply(this,arguments);if(null!=this.userElement){var O=this.userElement;O.style.cssText=\"position:relative;margin-right:4px;cursor:pointer;display:\"+O.style.display;O.className=\"geToolbarButton\";O.innerHTML=\"\";O.style.backgroundImage=\"url(\"+Editor.userImage+\")\";O.style.backgroundPosition=\"center center\";\nO.style.backgroundRepeat=\"no-repeat\";O.style.backgroundSize=\"24px 24px\";O.style.height=\"24px\";O.style.width=\"24px\";O.style.cssFloat=\"right\";O.setAttribute(\"title\",mxResources.get(\"changeUser\"));if(\"none\"!=O.style.display){O.style.display=\"inline-block\";var X=this.getCurrentFile();if(null!=X&&X.isRealtimeEnabled()&&X.isRealtimeSupported()){var ea=document.createElement(\"img\");ea.setAttribute(\"border\",\"0\");ea.style.position=\"absolute\";ea.style.left=\"18px\";ea.style.top=\"2px\";ea.style.width=\"12px\";ea.style.height=\n\"12px\";var ka=X.getRealtimeError();X=X.getRealtimeState();var ja=mxResources.get(\"realtimeCollaboration\");1==X?(ea.src=Editor.syncImage,ja+=\" (\"+mxResources.get(\"online\")+\")\"):(ea.src=Editor.syncProblemImage,ja=null!=ka&&null!=ka.message?ja+(\" (\"+ka.message+\")\"):ja+(\" (\"+mxResources.get(\"disconnected\")+\")\"));ea.setAttribute(\"title\",ja);O.style.paddingRight=\"4px\";O.appendChild(ea)}}}};var y=App.prototype.updateButtonContainer;App.prototype.updateButtonContainer=function(){y.apply(this,arguments);if(null!=", "label": 1, "label_name": "safe"} -{"code": " function isValidTagChar(str) {\n return str.match(/[a-z?\\\\\\/!]/i);\n }", "label": 1, "label_name": "safe"} -{"code": " public function testSendFailure()\n {\n $this->setMockHttpResponse('CreateCardFailure.txt');\n $response = $this->request->send();\n\n $this->assertFalse($response->isSuccessful());\n $this->assertFalse($response->isRedirect());\n $this->assertNull($response->getTransactionReference());\n $this->assertNull($response->getCardReference());\n $this->assertSame('You must provide an integer value for \\'exp_year\\'.', $response->getMessage());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $nodes[$level]->push($childNode);\n }\n }\n }\n $level--;\n if ($level && isset($closingTokens[$level])) {\n while ($token = array_pop($closingTokens[$level])) {\n $tokens[] = $token;\n }\n }\n } while ($level > 0);\n return $tokens;\n }", "label": 1, "label_name": "safe"} -{"code": " public function testWithAddedHeaderAsArray()\n {\n $r = new Response(200, ['Foo' => 'Bar']);\n $r2 = $r->withAddedHeader('foO', ['Baz', 'Bam']);\n $this->assertSame(['Foo' => ['Bar']], $r->getHeaders());\n $this->assertSame(['Foo' => ['Bar', 'Baz', 'Bam']], $r2->getHeaders());\n $this->assertSame('Bar, Baz, Bam', $r2->getHeaderLine('foo'));\n $this->assertSame(['Bar', 'Baz', 'Bam'], $r2->getHeader('foo'));\n }", "label": 1, "label_name": "safe"} -{"code": "\t\t\t\t\tslug: $( this ).data( 'slug' )\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttarget.postMessage( JSON.stringify( update ), window.location.origin );\n\t\t} );", "label": 1, "label_name": "safe"} -{"code": " $emails[$u->email] = trim(user::getUserAttribution($u->id));\n }", "label": 1, "label_name": "safe"} -{"code": " it 'should convert icmp string to number' do\n @resource[:provider] = provider\n @resource[:provider].should == provider\n @resource[:icmp] = v\n @resource[:icmp].should == k\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public static function recent($vars, $type = 'post') {\n $sql = \"SELECT * FROM `posts` WHERE `type` = '{$type}' AND `status` = '1' ORDER BY `date` DESC LIMIT {$vars}\";\n $posts = Db::result($sql);\n if(isset($posts['error'])){\n $posts['error'] = \"No Posts found.\";\n }else{\n $posts = $posts;\n }\n return $posts;\n }", "label": 1, "label_name": "safe"} -{"code": " it \"inherits the query's collection\" do\n cursor.get_more_op.collection.should eq query_operation.collection\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def is_node(cls, path):\n filesystem_path = pathutils.path_to_filesystem(path,\n filesystem.FOLDER)\n return (os.path.isdir(filesystem_path) and\n not os.path.exists(filesystem_path + \".props\"))", "label": 1, "label_name": "safe"} -{"code": " public function upload() {\n\n // upload the file, but don't save the record yet...\n if ($this->params['resize'] != 'false') {\n $maxwidth = $this->params['max_width'];\n } else {\n $maxwidth = null;\n }\n $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);\n // since most likely this function will only get hit via flash in YUI Uploader\n // and since Flash can't pass cookies, we lose the knowledge of our $user\n // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,\n // and then assign $user->id to $file->poster so we have an audit trail for the upload\n\n if (is_object($file)) {\n $resized = !empty($file->resized) ? true : false;\n $user = new user($this->params['usrid']);\n $file->poster = $user->id;\n $file->posted = $file->last_accessed = time();\n $file->save();\n if (!empty($this->params['cat'])) {\n $expcat = new expCat($this->params['cat']);\n $params['expCat'][0] = $expcat->id;\n $file->update($params);\n }\n\n // a echo so YUI Uploader is notified of the function's completion\n if ($resized) {\n echo gt('File resized and then saved');\n } else {\n echo gt('File saved');\n }\n } else {\n echo gt('File was NOT uploaded!');\n// flash('error',gt('File was not uploaded!'));\n }\n }", "label": 1, "label_name": "safe"} -{"code": " def init(): Unit = {\n BdLib.logInfo(\"Initialized network channel '%s' for mod '%s'\", name, modId)\n }\n\n def regServerHandler[M <: Message](id: Int, cls: Class[M])(handler: (M, NetworkEvent.Context) => Unit): Unit = {", "label": 0, "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, "label_name": "vulnerable"} -{"code": "set_umask(const char *optarg)\n{\n\tlong umask_long;\n\tmode_t umask_val;\n\tchar *endptr;\n\n\tumask_long = strtoll(optarg, &endptr, 0);\n\n\tif (*endptr || umask_long < 0 || umask_long & ~0777L) {\n\t\tfprintf(stderr, \"Invalid --umask option %s\", optarg);\n\t\treturn;\n\t}\n\n\tumask_val = umask_long & 0777;\n\tumask(umask_val);\n\n\tumask_cmdline = true;\n\n\treturn umask_val;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " function edit_externalalias() {\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\n if ($section->parent == -1) {\n notfoundController::handle_not_found();\n exit;\n } // doesn't work for standalone pages\n if (empty($section->id)) {\n $section->public = 1;\n if (!isset($section->parent)) {\n // This is another precaution. The parent attribute\n // should ALWAYS be set by the caller.\n //FJD - if that's the case, then we should die.\n notfoundController::handle_not_authorized();\n exit;\n //$section->parent = 0;\n }\n }\n assign_to_template(array(\n 'section' => $section,\n 'glyphs' => self::get_glyphs(),\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function __construct( Parameters $parameters, Parser $parser ) {\n\t\tparent::__construct( $parameters, $parser );\n\n\t\t$this->textSeparator = $parameters->getParameter( 'inlinetext' );\n\t}", "label": 1, "label_name": "safe"} -{"code": "oa=F.actions.get(\"resetView\");Q=F.actions.get(\"fullscreen\");var Ba=F.actions.get(\"undo\"),Ea=F.actions.get(\"redo\"),Ka=C(\"\",Ba.funct,null,mxResources.get(\"undo\")+\" (\"+Ba.shortcut+\")\",Ba,Editor.undoImage),Fa=C(\"\",Ea.funct,null,mxResources.get(\"redo\")+\" (\"+Ea.shortcut+\")\",Ea,Editor.redoImage),Ha=C(\"\",Q.funct,null,mxResources.get(\"fullscreen\"),Q,Editor.fullscreenImage);if(null!=K){oa=function(){pa.style.display=null!=F.pages&&(\"0\"!=urlParams.pages||1loadFiles($dir, 'foo\\\\', $callback);\n\n $expect = array(\n 'test' => 'foo\\\\test',\n 'Some234Foo234Bar98Name' => 'foo\\\\Some234Foo234Bar98Name'\n );\n\n $this->assertEquals($expect, $result);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " private static string BillingInfoUrl(string accountCode)\r\n {\r\n return UrlPrefix + Uri.EscapeUriString(accountCode) + UrlPostfix;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "fn should_fix_absolute_requests_based_on_referer() {\n\t// given\n\tlet (server, fetch) = serve_with_fetch(\"token\", \"https://parity.io\");\n\n\t// when\n\tlet response = request(server,\n\t\t\"\\\n\t\t\tGET /styles.css HTTP/1.1\\r\\n\\\n\t\t\tHost: localhost:8080\\r\\n\\\n\t\t\tConnection: close\\r\\n\\\n\t\t\tReferer: http://localhost:8080/web/EHQPPSBE5DM78X3GECX2YBVGC5S6JX3S5SMPY/\\r\\n\\\n\t\t\t\\r\\n\\\n\t\t\"\n\t);\n\n\t// then\n\tresponse.assert_status(\"HTTP/1.1 302 Found\");\n\tresponse.assert_header(\"Location\", \"/web/EHQPPSBE5DM78X3GECX2YBVGC5S6JX3S5SMPY/styles.css\");\n\n\tfetch.assert_no_more_requests();\n}", "label": 1, "label_name": "safe"} -{"code": " it { should contain_apt__conf('norecommends').with({\n 'priority' => '00',\n 'content' => \"Apt::Install-Recommends 0;\\nApt::AutoRemove::InstallRecommends 1;\\n\"\n })\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def check_username(username):\n username = username.strip()\n if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar():\n log.error(u\"This username is already taken\")\n raise Exception(_(u\"This username is already taken\"))\n return username", "label": 1, "label_name": "safe"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var $a=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){$a.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label": 1, "label_name": "safe"} -{"code": "function mso_segment_array()\r\n{\r\n\t$CI = &get_instance();\r\n\r\n\tif (isset($_SERVER['REQUEST_URI']) and $_SERVER['REQUEST_URI']) {\r\n\t\t// http://localhost/page/privet?get=hello\r\n\t\t$url = getinfo('site_protocol');\r\n\t\t$url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\r\n\t\t$url = str_replace($CI->config->config['base_url'], '', $url); // page/privet?get=hello\r\n\r\n\t\tif (strpos($url, '?') !== FALSE) {\r\n\t\t\t// \u0435\u0441\u0442\u044c \u00ab?\u00bb\r\n\t\t\t$url = explode('?', $url); // \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u043c \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\r\n\t\t\t$url = $url[0]; // \u0441\u0435\u0433\u043c\u0435\u043d\u0442\u044b - \u044d\u0442\u043e \u0442\u043e\u043b\u044c\u043a\u043e \u043f\u0435\u0440\u0432\u0430\u044f \u0447\u0430\u0441\u0442\u044c\r\n\t\t\t$url = explode('/', $url); // \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u043c \u0432 \u043c\u0430\u0441\u0441\u0438\u0432 \u043f\u043e /\r\n\r\n\t\t\t// \u043d\u0443\u0436\u043d\u043e \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u044c \u043d\u0443\u043c\u0435\u0440\u0430\u0446\u0438\u044e - \u043d\u0430\u0447\u0430\u043b\u043e \u0441 1\r\n\t\t\t$out = [];\r\n\t\t\t$i = 1;\r\n\t\t\t\r\n\t\t\tforeach ($url as $val) {\r\n\t\t\t\tif ($val) {\r\n\t\t\t\t\t$out[$i] = $val;\r\n\t\t\t\t\t$i++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn $out;\r\n\t\t} else {\r\n\t\t\treturn $CI->uri->segment_array();\r\n\t\t}\r\n\t} else {\r\n\t\treturn $CI->uri->segment_array();\r\n\t}\r\n}\r", "label": 0, "label_name": "vulnerable"} -{"code": " $digits = $integer = substr($integer, 1); // rm unnecessary plus\n } else {\n $digits = $integer;\n }\n\n // test if it's numeric\n if (!ctype_digit($digits)) return false;\n\n // perform scope tests\n if (!$this->zero && $integer == 0) return false;\n if (!$this->positive && $integer > 0) return false;\n if (!$this->negative && $integer < 0) return false;\n\n return $integer;\n\n }", "label": 1, "label_name": "safe"} -{"code": "func (cf *clientsFactory) UpdateNamespaces(ctx context.Context) error {\n\tclients, err := clientsForClusters(cf.clusters.Get())\n\tif err != nil {\n\t\tcf.log.Error(err, \"failed to create client\")\n\t\treturn err\n\t}\n\n\tcf.syncCaches()\n\n\twg := sync.WaitGroup{}\n\n\tfor clusterName, c := range clients {\n\t\twg.Add(1)\n\n\t\tgo func(clusterName string, c client.Client) {\n\t\t\tdefer wg.Done()\n\n\t\t\tnsList := &v1.NamespaceList{}\n\n\t\t\tif err := c.List(ctx, nsList); err != nil {\n\t\t\t\tcf.log.Error(err, \"failed listing namespaces\", \"cluster\", clusterName)\n\t\t\t}\n\n\t\t\tcf.clustersNamespaces.Set(clusterName, nsList.Items)\n\t\t}(clusterName, c)\n\t}\n\n\twg.Wait()\n\n\treturn nil\n}", "label": 1, "label_name": "safe"} -{"code": " data: my_dialog.find(\"#login_form\").serialize(),\n complete: function() {\n $(ok_button_selector).button(\"option\", \"disabled\", false);\n },\n success: function() {\n my_dialog.find(\"#login_form_username\").val(\"\");\n my_dialog.find(\"#login_form_password\").val(\"\");\n me.dialog(\"destroy\");\n login_dialog_opened = false;\n on_success();\n },\n error: function(xhr, status, error) {\n if (xhr.status == 401) {\n my_dialog.find(\"#login_form_denied\").show();\n my_dialog.find(\"#login_form_password\").val(\"\");\n }\n else {\n alert(\"Login error \" + ajax_simple_error(xhr, status, error));\n }\n },\n });\n },", "label": 1, "label_name": "safe"} -{"code": " protected function lookup(Request $request, $catch = false)\n {\n // if allow_reload and no-cache Cache-Control, allow a cache reload\n if ($this->options['allow_reload'] && $request->isNoCache()) {\n $this->record($request, 'reload');\n\n return $this->fetch($request, $catch);\n }\n\n try {\n $entry = $this->store->lookup($request);\n } catch (\\Exception $e) {\n $this->record($request, 'lookup-failed');\n\n if ($this->options['debug']) {\n throw $e;\n }\n\n return $this->pass($request, $catch);\n }\n\n if (null === $entry) {\n $this->record($request, 'miss');\n\n return $this->fetch($request, $catch);\n }\n\n if (!$this->isFreshEnough($request, $entry)) {\n $this->record($request, 'stale');\n\n return $this->validate($request, $entry, $catch);\n }\n\n $this->record($request, 'fresh');\n\n $entry->headers->set('Age', $entry->getAge());\n\n return $entry;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getRedirectData()\n {\n return null;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\t\t\t\t\t\tleft : (left+10)+'px'\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});", "label": 0, "label_name": "vulnerable"} -{"code": "ca,la,ia){function ma(Ma,Ta){null==Ka?(Ia=Ma,Ia=/^https?:\\/\\//.test(Ia)&&!b.editor.isCorsEnabledForUrl(Ia)?PROXY_URL+\"?url=\"+encodeURIComponent(Ia):TEMPLATE_PATH+\"/\"+Ia,mxUtils.get(Ia,mxUtils.bind(this,function(Ua){200<=Ua.getStatus()&&299>=Ua.getStatus()&&(Ka=Ua.getText());Ta(Ka,Ia)}))):Ta(Ka,Ia)}function ra(Ma,Ta,Ua){if(null!=Ma&&mxUtils.isAncestorNode(document.body,na)){Ma=mxUtils.parseXml(Ma);Ma=Editor.parseDiagramNode(Ma.documentElement);var Za=new mxCodec(Ma.ownerDocument),Wa=new mxGraphModel;", "label": 1, "label_name": "safe"} -{"code": "Graph.sanitizeHtml=function(b,e){return Graph.domPurify(b,!1)};Graph.sanitizeLink=function(b){var e=document.createElement(\"a\");e.setAttribute(\"href\",b);Graph.sanitizeNode(e);return e.getAttribute(\"href\")};Graph.sanitizeNode=function(b){return Graph.domPurify(b,!0)};Graph.domPurify=function(b,e){return DOMPurify.sanitize(b,{IN_PLACE:e,ADD_ATTR:[\"target\"],FORBID_TAGS:[\"form\"],ALLOWED_URI_REGEXP:/^(?:(?:https?|mailto|tel|callto|data):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i})};", "label": 1, "label_name": "safe"} -{"code": "ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n const char **elem_rtrn, const char **field_rtrn,\n ExprDef **index_rtrn)\n{\n switch (expr->expr.op) {\n case EXPR_IDENT:\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n return true;\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);\n *index_rtrn = NULL;\n return true;\n case EXPR_ARRAY_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);\n *index_rtrn = expr->array_ref.entry;\n return true;\n default:\n break;\n }\n log_wsgo(ctx, \"Unexpected operator %d in ResolveLhs\\n\", expr->expr.op);\n return false;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function XMLRPCaddNode($nodeName, $parentNode){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n if(in_array(\"nodeAdmin\", $user['privileges'])){\n if(!$parentNode){\n $topNodes = getChildNodes();\n $keys = array_keys($topNodes);\n $parentNode = array_shift($keys);\n }\n\n if(!preg_match(\"/^[-A-Za-z0-9_\\. ]+$/\", $nodeName)){\n return array('status' => 'error',\n 'errorcode' => 48,\n 'errormsg' => 'Invalid node name');\n }\n\n if(checkUserHasPriv(\"nodeAdmin\", $user['id'], $parentNode)){\n $nodeInfo = getNodeInfo($parentNode);\n $query = \"SELECT id \"\n . \"FROM privnode \"\n . \"WHERE name = '$nodeName' AND parent = $parentNode\";\n $qh = doQuery($query, 335);\n if(mysql_num_rows($qh)){\n return array('status' => 'error',\n 'errorcode' => 50,\n 'errormsg' => 'A node of that name already exists under ' . $nodeInfo['name']);\n }\n $query = \"INSERT IGNORE INTO privnode \"\n . \"(parent, name) \"\n . \"VALUES \"\n . \"($parentNode, '$nodeName')\";\n doQuery($query, 337);\n $qh = doQuery(\"SELECT LAST_INSERT_ID() FROM privnode\", 101);\n if(!$row = mysql_fetch_row($qh)){\n return array('status' => 'error',\n 'errorcode' => 51,\n 'errormsg' => 'Could not add node to database');\n }\n $nodeid = $row[0];\n return array('status' => 'success',\n 'nodeid' => $nodeid);\n } else {\n return array('status' => 'error',\n 'errorcode' => 49,\n 'errormsg' => 'Unable to add node at this location');\n }\n } else {\n return array(\n 'status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'User cannot access node content');\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "process_secondary_order(STREAM s)\n{\n\t/* The length isn't calculated correctly by the server.\n\t * For very compact orders the length becomes negative\n\t * so a signed integer must be used. */\n\tuint16 length;\n\tuint16 flags;\n\tuint8 type;\n\tuint8 *next_order;\n\tstruct stream packet = *s;\n\n\tin_uint16_le(s, length);\n\tin_uint16_le(s, flags);\t/* used by bmpcache2 */\n\tin_uint8(s, type);\n\n\tif (!s_check_rem(s, length + 7))\n\t{\n\t\trdp_protocol_error(\"process_secondary_order(), next order pointer would overrun stream\", &packet);\n\t}\n\n\tnext_order = s->p + (sint16) length + 7;\n\n\tswitch (type)\n\t{\n\t\tcase RDP_ORDER_RAW_BMPCACHE:\n\t\t\tprocess_raw_bmpcache(s);\n\t\t\tbreak;\n\n\t\tcase RDP_ORDER_COLCACHE:\n\t\t\tprocess_colcache(s);\n\t\t\tbreak;\n\n\t\tcase RDP_ORDER_BMPCACHE:\n\t\t\tprocess_bmpcache(s);\n\t\t\tbreak;\n\n\t\tcase RDP_ORDER_FONTCACHE:\n\t\t\tprocess_fontcache(s);\n\t\t\tbreak;\n\n\t\tcase RDP_ORDER_RAW_BMPCACHE2:\n\t\t\tprocess_bmpcache2(s, flags, False);\t/* uncompressed */\n\t\t\tbreak;\n\n\t\tcase RDP_ORDER_BMPCACHE2:\n\t\t\tprocess_bmpcache2(s, flags, True);\t/* compressed */\n\t\t\tbreak;\n\n\t\tcase RDP_ORDER_BRUSHCACHE:\n\t\t\tprocess_brushcache(s, flags);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tlogger(Graphics, Warning,\n\t\t\t \"process_secondary_order(), unhandled secondary order %d\", type);\n\t}\n\n\ts->p = next_order;\n}", "label": 1, "label_name": "safe"} -{"code": "e.removeClass(\"cke_btn_unlocked\"):e.addClass(\"cke_btn_unlocked\");e.setAttribute(\"aria-checked\",a.lockRatio);CKEDITOR.env.hc&&e.getChild(0).setHtml(a.lockRatio?CKEDITOR.env.ie?\"\u25a0\":\"\u25a3\":CKEDITOR.env.ie?\"\u25a1\":\"\u25a2\");return a.lockRatio},x=function(a){var b=a.originalElement;if(\"true\"==b.getCustomData(\"isReady\")){var d=a.getContentElement(\"info\",\"txtWidth\"),e=a.getContentElement(\"info\",\"txtHeight\");d&&d.setValue(b.$.width);e&&e.setValue(b.$.height)}g(a)},y=function(a,b){function d(a,b){var d=a.match(k);return d?\n(\"%\"==d[2]&&(d[1]+=\"%\",l(e,!1)),d[1]):b}if(a==f){var e=this.getDialog(),c=\"\",g=\"txtWidth\"==this.id?\"width\":\"height\",h=b.getAttribute(g);h&&(c=d(h,c));c=d(b.getStyle(g),c);this.setValue(c)}},t,q=function(){var a=this.originalElement;a.setCustomData(\"isReady\",\"true\");a.removeListener(\"load\",q);a.removeListener(\"error\",h);a.removeListener(\"abort\",h);CKEDITOR.document.getById(m).setStyle(\"display\",\"none\");this.dontResetSize||x(this);this.firstLoad&&CKEDITOR.tools.setTimeout(function(){l(this,\"check\")},", "label": 1, "label_name": "safe"} -{"code": " public function __construct($message = null, \\Exception $previous = null, $code = 0)\n {\n parent::__construct(409, $message, $previous, array(), $code);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it 'correctly exports the CategoryUser table, excluding deleted categories' do\n data, _csv_out = make_component_csv\n\n expect(data.find { |r| r['category_id'] == category.id.to_s }).to be_nil\n expect(data.find { |r| r['category_id'] == deleted_category.id.to_s }).to be_nil\n expect(data.length).to eq(3)\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 end", "label": 1, "label_name": "safe"} -{"code": " function edit_externalalias() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " private function _verify($public_key_or_secret, $expected_alg = null) {\n $segments = explode('.', $this->raw);\n $signature_base_string = implode('.', array($segments[0], $segments[1]));\n if (!$expected_alg) {\n # NOTE: might better to warn here\n $expected_alg = $this->header['alg'];\n }\n switch ($expected_alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return $this->signature === hash_hmac($this->digest(), $signature_base_string, $public_key_or_secret, true);\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return $this->rsa($public_key_or_secret, RSA::SIGNATURE_PKCS1)->verify($signature_base_string, $this->signature);\n case 'ES256':\n case 'ES384':\n case 'ES512':\n throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return $this->rsa($public_key_or_secret, RSA::SIGNATURE_PSS)->verify($signature_base_string, $this->signature);\n default:\n throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "func (*Leaderboard) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{23}\n}", "label": 0, "label_name": "vulnerable"} -{"code": "_PyBytes_DecodeEscape(const char *s,\n Py_ssize_t len,\n const char *errors,\n Py_ssize_t unicode,\n const char *recode_encoding,\n const char **first_invalid_escape)\n{\n *first_invalid_escape = NULL;\n return PyBytes_DecodeEscape(s, len, errors, unicode, recode_encoding);\n}", "label": 1, "label_name": "safe"} -{"code": " function checkNodeJsVersions(hosts, index) {\n index = index || 0;\n if (hosts && index < hosts.length) {\n main.socket.emit('sendToHost', hosts[index].name, 'getHostInfo', null, function (result) {\n if (result && result['Node.js']) {\n var major = parseInt(result['Node.js'].split('.').shift().replace('v', ''), 10);\n if (major < 6 || major === 7 || major === 9 || major === 11 ) { // we allow 6, 8, 10 and 12+\n main.showMessage(_('This version of node.js \"%s\" on \"%s\" is deprecated. Please install node.js 6, 8 or newer', result['Node.js'], hosts[index].name), _('Suggestion'), 'error_outline');\n }\n }\n setTimeout(function () {\n checkNodeJsVersions(hosts, index + 1);\n }, 100);\n });\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtask['id'], $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label": 1, "label_name": "safe"} -{"code": "static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf)\n{\n\tint ret;\n\n\t/* MBIM backwards compatible function? */\n\tif (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM)\n\t\treturn -ENODEV;\n\n\t/* The NCM data altsetting is fixed, so we hard-coded it.\n\t * Additionally, generic NCM devices are assumed to accept arbitrarily\n\t * placed NDP.\n\t */\n\tret = cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0);\n\n\t/*\n\t * We should get an event when network connection is \"connected\" or\n\t * \"disconnected\". Set network connection in \"disconnected\" state\n\t * (carrier is OFF) during attach, so the IP network stack does not\n\t * start IPv6 negotiation and more.\n\t */\n\tusbnet_link_change(dev, 0, 0);\n\treturn ret;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function detach()\n {\n global $zdb, $hist;\n\n try {\n $update = $zdb->update(self::TABLE);\n $update->set(\n array('parent_group' => new Expression('NULL'))\n )->where(\n [self::PK => $this->id]\n );\n\n $edit = $zdb->execute($update);\n\n //edit == 0 does not mean there were an error, but that there\n //were nothing to change\n if ($edit->count() > 0) {\n $this->parent_group = null;\n $hist->add(\n _T(\"Group has been detached from its parent\"),\n $this->group_name\n );\n }\n\n return true;\n } catch (Throwable $e) {\n Analog::log(\n 'Something went wrong detaching group `' . $this->group_name .\n '` (' . $this->id . ') from its parent:\\'( | ' .\n $e->getMessage() . \"\\n\" .\n $e->getTraceAsString(),\n Analog::ERROR\n );\n throw $e;\n }\n }", "label": 1, "label_name": "safe"} -{"code": " it 'should return correct filedir' do\n should run.with_params('https://my_user:my_pass@www.example.com:8080/path/to/file.php?id=1&ret=0','filedir').and_return('file') \n end", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\tover = function(e) {\n\t\t\t\tif (isin(e)) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\te.dataTransfer.dropEffect = 'none';\n\t\t\t\t}\n\t\t\t},", "label": 1, "label_name": "safe"} -{"code": "a.$.nextSibling);return a},insertBefore:function(a){a.$.parentNode.insertBefore(this.$,a.$);return a},insertBeforeMe:function(a){this.$.parentNode.insertBefore(a.$,this.$);return a},getAddress:function(a){for(var e=[],b=this.getDocument().$.documentElement,c=this.$;c&&c!=b;){var d=c.parentNode;d&&e.unshift(this.getIndex.call({$:c},a));c=d}return e},getDocument:function(){return new CKEDITOR.dom.document(this.$.ownerDocument||this.$.parentNode.ownerDocument)},getIndex:function(a){var e=this.$,b=-1,", "label": 1, "label_name": "safe"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask($task);\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label": 1, "label_name": "safe"} -{"code": "snmp_ber_encode_string_len(unsigned char *out, uint32_t *out_len, const char *str, uint32_t length)\n{\n uint32_t i;\n\n str += length - 1;\n for(i = 0; i < length; ++i) {\n (*out_len)++;\n *out-- = (uint8_t)*str--;\n }\n\n out = snmp_ber_encode_length(out, out_len, length);\n out = snmp_ber_encode_type(out, out_len, BER_DATA_TYPE_OCTET_STRING);\n\n return out;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "(b=c.reset(this.getSnapshot()),c=c.reset(this._.previousValue),b=b!==c):b=a.apply(this);return b}});b.document&&(b.elementMode!=CKEDITOR.ELEMENT_MODE_INLINE||b.focusManager.hasFocus)&&g()};CKEDITOR.plugins.scayt={engineLoaded:!1,instances:{},controlInfo:{},setControlInfo:function(a,c){a&&(a.name&&\"object\"!=typeof this.controlInfo[a.name])&&(this.controlInfo[a.name]={});for(var b in c)this.controlInfo[a.name][b]=c[b]},isControlRestored:function(a){return a&&a.name&&this.controlInfo[a.name]?this.controlInfo[a.name].restored:", "label": 1, "label_name": "safe"} -{"code": "b.apply(d)},a||0)},trim:function(){var b=/(?:^[ \\t\\n\\r]+)|(?:[ \\t\\n\\r]+$)/g;return function(a){return a.replace(b,\"\")}}(),ltrim:function(){var b=/^[ \\t\\n\\r]+/g;return function(a){return a.replace(b,\"\")}}(),rtrim:function(){var b=/[ \\t\\n\\r]+$/g;return function(a){return a.replace(b,\"\")}}(),indexOf:function(b,a){if(typeof a==\"function\")for(var d=0,g=b.length;dfactory = new HTMLPurifier_DefinitionCacheFactory();\n $this->oldFactory = HTMLPurifier_DefinitionCacheFactory::instance();\n HTMLPurifier_DefinitionCacheFactory::instance($this->factory);\n }", "label": 1, "label_name": "safe"} -{"code": " public function testAssertAlnumFailIsString()\n {\n $this->expectValidationException(\"Property in context must be a string\");\n $this->makeAtom(3)->assertAlnum();\n }", "label": 1, "label_name": "safe"} -{"code": " public static function exist($tag) {\r\n\r\n $sql = \"SELECT `name` FROM `cat` WHERE `name` = '{$tag}'\";\r\n $q = Db::result($sql);\r\n if (Db::$num_rows > 0) {\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "static int add_ast_fields(void)\n{\n PyObject *empty_tuple, *d;\n if (PyType_Ready(&AST_type) < 0)\n return -1;\n d = AST_type.tp_dict;\n empty_tuple = PyTuple_New(0);\n if (!empty_tuple ||\n _PyDict_SetItemId(d, &PyId__fields, empty_tuple) < 0 ||\n _PyDict_SetItemId(d, &PyId__attributes, empty_tuple) < 0) {\n Py_XDECREF(empty_tuple);\n return -1;\n }\n Py_DECREF(empty_tuple);\n return 0;\n}", "label": 1, "label_name": "safe"} -{"code": "\thtml: function( value ) {\n\t\treturn value === undefined ?\n\t\t\t(this[0] ?\n\t\t\t\tthis[0].innerHTML :\n\t\t\t\tnull) :\n\t\t\tthis.empty().append( value );\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": " function skipWhitespace() {\n while (\n idx < formula.length &&\n whitespace.has(formula.charCodeAt(idx))\n ) {\n idx++;\n }\n }", "label": 1, "label_name": "safe"} -{"code": " it \"should convert PB to B\" do\n result = scope.function_to_bytes([\"4 PB\"])\n expect(result).to(eq(4503599627370496))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function testRenderWithUnknownRenderer()\n {\n $handler = $this->getHandler($this->returnValue(new Response('foo')));\n\n $handler->render('/', 'bar');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public void translate(ServerUnloadChunkPacket packet, GeyserSession session) {\n session.getChunkCache().removeChunk(packet.getX(), packet.getZ());\n\n //Checks if a skull is in an unloaded chunk then removes it\n Iterator iterator = session.getSkullCache().keySet().iterator();\n while (iterator.hasNext()) {\n Vector3i position = iterator.next();\n if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) {\n session.getSkullCache().get(position).despawnEntity(session);\n iterator.remove();\n }\n }\n\n // Do the same thing with lecterns\n iterator = session.getLecternCache().iterator();\n while (iterator.hasNext()) {\n Vector3i position = iterator.next();\n if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) {\n iterator.remove();\n }\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function AnsiUp() {\n this.VERSION = \"4.0.3\";\n this.setup_palettes();\n this._use_classes = false;\n this._escape_for_html = true;\n this.bold = false;\n this.fg = this.bg = null;\n this._buffer = '';\n this._url_whitelist = { 'http': 1, 'https': 1 };\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $rst[$key] = self::parseAndTrim($st, $unescape);\n }\n return $rst;\n }\n\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"\\r\\n\",\" \",$str);\n $str = str_replace('\"',\""\",$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"\u2019\",\"’\",$str);\n $str = str_replace(\"\u2018\",\"‘\",$str);\n $str = str_replace(\"\u00ae\",\"®\",$str);\n $str = str_replace(\"\u2013\",\"-\", $str);\n $str = str_replace(\"\u2014\",\"—\", $str);\n $str = str_replace(\"\u201d\",\"”\", $str);\n $str = str_replace(\"\u201c\",\"“\", $str);\n $str = str_replace(\"\u00bc\",\"¼\",$str);\n $str = str_replace(\"\u00bd\",\"½\",$str);\n $str = str_replace(\"\u00be\",\"¾\",$str);\n\t\t$str = str_replace(\"\u2122\",\"™\", $str);\n\t\t$str = trim($str);\n\t\t\n if ($unescape) {\n\t\t\t$str = stripcslashes($str); \n\t\t} else {\n\t $str = addslashes($str);\n }\n\n return $str;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " readData(handle, buf, off, len, position, cb) {\n // Backwards compatibility\n this.read(handle, buf, off, len, position, cb);\n }", "label": 1, "label_name": "safe"} -{"code": "func (m *MockAccessRequester) GetGrantedAudience() fosite.Arguments {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetGrantedAudience\")\n\tret0, _ := ret[0].(fosite.Arguments)\n\treturn ret0\n}", "label": 1, "label_name": "safe"} -{"code": "\"startWidth\",this.defaultArrowWidth)};Ca.prototype.getEndArrowWidth=function(){return this.getEdgeWidth()+mxUtils.getNumber(this.style,\"endWidth\",this.defaultArrowWidth)};Ca.prototype.getEdgeWidth=function(){return mxUtils.getNumber(this.style,\"width\",this.defaultWidth)+Math.max(0,this.strokewidth-1)};mxCellRenderer.registerShape(\"flexArrow\",Ca);mxUtils.extend(Ra,mxActor);Ra.prototype.size=30;Ra.prototype.isRoundable=function(){return!0};Ra.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(v,parseFloat(mxUtils.getValue(this.style,", "label": 0, "label_name": "vulnerable"} -{"code": " function categoryBreadcrumb() {\n// global $db, $router;\n\n //eDebug($this->category);\n\n /*if(isset($router->params['action']))\n {\n $ancestors = $this->category->pathToNode(); \n }else if(isset($router->params['section']))\n {\n $current = $db->selectObject('section',' id= '.$router->params['section']);\n $ancestors[] = $current;\n if( $current->parent != -1 || $current->parent != 0 )\n { \n while ($db->selectObject('section',' id= '.$router->params['section']);)\n if ($section->id == $id) {\n $current = $section;\n break;\n }\n }\n }\n eDebug($sections);\n $ancestors = $this->category->pathToNode(); \n }*/\n\n $ancestors = $this->category->pathToNode();\n // eDebug($ancestors);\n assign_to_template(array(\n 'ancestors' => $ancestors\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "func TestCORSFilter_AllowedDomains(t *testing.T) {\n\tfor _, each := range allowedDomainInput {\n\t\ttearDown()\n\t\tws := new(WebService)\n\t\tws.Route(ws.PUT(\"/cors\").To(dummy))\n\t\tAdd(ws)\n\n\t\tcors := CrossOriginResourceSharing{\n\t\t\tAllowedDomains: each.domains,\n\t\t\tCookiesAllowed: true,\n\t\t\tContainer: DefaultContainer}\n\t\tFilter(cors.Filter)\n\n\t\thttpRequest, _ := http.NewRequest(\"PUT\", \"http://api.his.com/cors\", nil)\n\t\thttpRequest.Header.Set(HEADER_Origin, each.origin)\n\t\thttpWriter := httptest.NewRecorder()\n\t\tDefaultContainer.Dispatch(httpWriter, httpRequest)\n\t\tactual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin)\n\t\tif actual != each.origin && each.allowed {\n\t\t\tt.Error(\"expected to be accepted\", each)\n\t\t}\n\t\tif actual == each.origin && !each.allowed {\n\t\t\tt.Error(\"did not expect to be accepted\")\n\t\t}\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": " private static void setFactoryProperties(Object factory) {\n setFeatureQuietly(factory, XMLConstants.FEATURE_SECURE_PROCESSING, true);\n setFeatureQuietly(factory, \"http://apache.org/xml/features/disallow-doctype-decl\", true);\n setFeatureQuietly(factory, \"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n setFeatureQuietly(factory, \"http://xml.org/sax/features/external-general-entities\", false);\n setFeatureQuietly(factory, \"http://xml.org/sax/features/external-parameter-entities\", false);\n // Values from XMLConstants inlined for JDK 1.6 compatibility\n setAttributeQuietly(factory, \"http://javax.xml.XMLConstants/property/accessExternalDTD\", \"\");\n setAttributeQuietly(factory, \"http://javax.xml.XMLConstants/property/accessExternalSchema\", \"\");\n setAttributeQuietly(factory, \"http://javax.xml.XMLConstants/property/accessExternalStylesheet\", \"\");\n }", "label": 1, "label_name": "safe"} -{"code": "\"plantUmlData\",JSON.stringify({data:F,format:K.format}))}finally{g.getModel().endUpdate()}},function(H){d.handleError(H)})},null,null,400,220);d.showDialog(G.container,420,300,!0,!0);G.init()};g.cellEditor.editMermaidData=function(D,G,P){var K=JSON.parse(P);G=new TextareaDialog(d,mxResources.get(\"mermaid\")+\":\",K.data,function(F){null!=F&&d.spinner.spin(document.body,mxResources.get(\"inserting\"))&&d.generateMermaidImage(F,K.config,function(H,S,V){d.spinner.stop();g.getModel().beginUpdate();try{g.setCellStyles(\"image\",", "label": 0, "label_name": "vulnerable"} -{"code": " function changePassword($username, $password)\n {\n $this->log('Auth_Container_MDB::changePassword() called.', AUTH_LOG_DEBUG);\n $err = $this->_prepare();\n if ($err !== true) {\n return PEAR::raiseError($err->getMessage(), $err->getCode(),\n null, null, $err->getUserInfo());\n }\n\n if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') {\n $cryptFunction = 'strval';\n } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) {\n $cryptFunction = $this->options['cryptType'];\n } else {\n $cryptFunction = 'md5';\n }\n\n $password = $cryptFunction($password);\n\n $query = sprintf(\"UPDATE %s SET %s = %s WHERE %s = %s\",\n $this->options['final_table'],\n $this->options['final_passwordcol'],\n $this->db->getTextValue($password),\n $this->options['final_usernamecol'],\n $this->db->getTextValue($username)\n );\n\n // check if there is an optional parameter db_where\n if ($this->options['db_where'] != '') {\n // there is one, so add it to the query\n $query .= \" AND \".$this->options['db_where'];\n }\n\n $this->log('Running SQL against MDB: '.$query, AUTH_LOG_DEBUG);\n\n $res = $this->query($query);\n\n if (MDB::isError($res)) {\n return PEAR::raiseError($res->getMessage(), $res->getCode(),\n null, null, $res->getUserInfo());\n }\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public OldIESwithDESede()\n {\n super(new DESedeEngine());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testExtractBody()\n {\n $this->expectErrorCollection(E_WARNING, 'Lexer: Extracted body');\n $this->invoke('foo');\n }", "label": 1, "label_name": "safe"} -{"code": " def update_config\n Log.add_info(request, params.inspect)\n\n yaml = ApplicationHelper.get_config_yaml\n\n unless params[:timecard].nil? or params[:timecard].empty?\n yaml[:timecard] = Hash.new if yaml[:timecard].nil?\n \n params[:timecard].each do |key, val|\n yaml[:timecard][key] = val\n end\n ApplicationHelper.save_config_yaml(yaml)\n end\n\n @yaml_timecard = yaml[:timecard]\n @yaml_timecard = Hash.new if @yaml_timecard.nil?\n\n flash[:notice] = t('msg.update_success')\n render(:action => 'configure')\n end", "label": 0, "label_name": "vulnerable"} -{"code": "usm_free_usmStateReference(void *old)\n{\n struct usmStateReference *old_ref = (struct usmStateReference *) old;\n\n if (old_ref) {\n\n if (old_ref->usr_name_length)\n SNMP_FREE(old_ref->usr_name);\n if (old_ref->usr_engine_id_length)\n SNMP_FREE(old_ref->usr_engine_id);\n if (old_ref->usr_auth_protocol_length)\n SNMP_FREE(old_ref->usr_auth_protocol);\n if (old_ref->usr_priv_protocol_length)\n SNMP_FREE(old_ref->usr_priv_protocol);\n\n if (old_ref->usr_auth_key_length && old_ref->usr_auth_key) {\n SNMP_ZERO(old_ref->usr_auth_key, old_ref->usr_auth_key_length);\n SNMP_FREE(old_ref->usr_auth_key);\n }\n if (old_ref->usr_priv_key_length && old_ref->usr_priv_key) {\n SNMP_ZERO(old_ref->usr_priv_key, old_ref->usr_priv_key_length);\n SNMP_FREE(old_ref->usr_priv_key);\n }\n\n SNMP_ZERO(old_ref, sizeof(*old_ref));\n SNMP_FREE(old_ref);\n\n }\n\n} /* end usm_free_usmStateReference() */", "label": 0, "label_name": "vulnerable"} -{"code": " def apply(operations)\n operations.inject(self) do |builder, (name, argument)|\n if argument == true || argument == nil\n builder.public_send(name)\n elsif argument.is_a?(Array)\n builder.public_send(name, *argument)\n elsif argument.is_a?(Hash)\n builder.public_send(name, **argument)\n else\n builder.public_send(name, argument)\n end\n end\n end", "label": 1, "label_name": "safe"} -{"code": " $contents[] = ['class' => 'text-center', 'text' => '
' . tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, 'primary', null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('languages.php', 'page=' . (int)$_GET['page'] . '&lID=' . $lInfo->languages_id), null, null, 'btn-light')];", "label": 1, "label_name": "safe"} -{"code": " def primary?\n !!@primary\n end", "label": 0, "label_name": "vulnerable"} -{"code": "void AnnotateBarrierWaitAfter(const char *file, int line,\n const volatile void *barrier) {}", "label": 0, "label_name": "vulnerable"} -{"code": " def test_reset_student_attempts_delete(self):\n \"\"\" Test delete single student state. \"\"\"\n url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': self.problem_urlname,\n 'unique_student_identifier': self.student.email,\n 'delete_module': True,\n })\n self.assertEqual(response.status_code, 200)\n # make sure the module has been deleted\n self.assertEqual(\n StudentModule.objects.filter(\n student=self.module_to_reset.student,\n course_id=self.module_to_reset.course_id,\n # module_id=self.module_to_reset.module_id,\n ).count(),\n 0\n )", "label": 0, "label_name": "vulnerable"} -{"code": "func (x *GetWalletLedgerRequest) Reset() {\n\t*x = GetWalletLedgerRequest{}\n\tif protoimpl.UnsafeEnabled {\n\t\tmi := &file_console_proto_msgTypes[45]\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tms.StoreMessageInfo(mi)\n\t}\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tprotected function parse()\n\t{\n\t\tparent::parse();\n\n\t\t// grab the error-type from the parameters\n\t\t$errorType = $this->getParameter('type');\n\n\t\t// set correct headers\n\t\tswitch($errorType)\n\t\t{\n\t\t\tcase 'module-not-allowed':\n\t\t\tcase 'action-not-allowed':\n\t\t\t\tSpoonHTTP::setHeadersByCode(403);\n\t\t\t\tbreak;\n\n\t\t\tcase 'not-found':\n\t\t\t\tSpoonHTTP::setHeadersByCode(404);\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// querystring provided?\n\t\tif($this->getParameter('querystring') !== null)\n\t\t{\n\t\t\t// split into file and parameters\n\t\t\t$chunks = explode('?', $this->getParameter('querystring'));\n\n\t\t\t// get extension\n\t\t\t$extension = SpoonFile::getExtension($chunks[0]);\n\n\t\t\t// if the file has an extension it is a non-existing-file\n\t\t\tif($extension != '' && $extension != $chunks[0])\n\t\t\t{\n\t\t\t\t// set correct headers\n\t\t\t\tSpoonHTTP::setHeadersByCode(404);\n\n\t\t\t\t// give a nice error, so we can detect which file is missing\n\t\t\t\techo 'Requested file (' . implode('?', $chunks) . ') not found.';\n\n\t\t\t\t// stop script execution\n\t\t\t\texit;\n\t\t\t}\n\t\t}\n\n\t\t// assign the correct message into the template\n\t\t$this->tpl->assign('message', BL::err(SpoonFilter::toCamelCase(htmlspecialchars($errorType), '-')));\n\t}", "label": 0, "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, "label_name": "vulnerable"} -{"code": " public function testIntegrationWithPercentEncoder()\n {\n $this->assertDef(\n 'http://www.example.com/%56%fc%GJ%5%FC',\n 'http://www.example.com/V%FC%25GJ%255%FC'\n );\n }", "label": 1, "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 = 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, "label_name": "vulnerable"} -{"code": " public static C3P0Config extractXmlConfigFromInputStream(InputStream is) throws Exception\n {\n DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();\n\tfact.setExpandEntityReferences(false);\n DocumentBuilder db = fact.newDocumentBuilder();\n Document doc = db.parse( is );\n\n return extractConfigFromXmlDoc(doc);\n }", "label": 1, "label_name": "safe"} -{"code": " def test_project_quotas_overrides_withclass(self):\n self._stub_class()\n self._stub_project(True)\n self.context.quota_class = 'test_class'\n result = quota.get_project_quotas(self.context, 'admin')\n self.assertEqual(result, dict(\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 ))", "label": 1, "label_name": "safe"} -{"code": " private void populateAuthCacheInAllPeers(AuthorizationContext authContext) throws Throwable {\n\n // send a GET request to the ExampleService factory to populate auth cache on each peer.\n // since factory is not OWNER_SELECTION service, request goes to the specified node.\n for (VerificationHost peer : this.host.getInProcessHostMap().values()) {\n peer.setAuthorizationContext(authContext);\n\n // based on the role created in test, all users have access to ExampleService\n this.host.sendAndWaitExpectSuccess(\n Operation.createGet(UriUtils.buildStatsUri(peer, ExampleService.FACTORY_LINK)));\n }\n\n this.host.waitFor(\"Timeout waiting for correct auth cache state\",\n () -> checkCacheInAllPeers(authContext.getToken(), true));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " private function prepareValues(array $project, array $values)\n {\n $values['id'] = $project['id'];\n\n if (isset($values['is_private'])) {\n if (! $this->helper->user->hasProjectAccess('ProjectCreationController', 'create', $project['id'])) {\n unset($values['is_private']);\n }\n } elseif ($project['is_private'] == 1 && ! isset($values['is_private'])) {\n if ($this->helper->user->hasProjectAccess('ProjectCreationController', 'create', $project['id'])) {\n $values += array('is_private' => 0);\n }\n }\n\n return $values;\n }", "label": 1, "label_name": "safe"} -{"code": "(function(){var a=/([\\w\\-:.]+)(?:(?:\\s*=\\s*(?:(?:\"([^\"]*)\")|(?:'([^']*)')|([^\\s>]+)))|(?=\\s|$))/g,e={checked:1,compact:1,declare:1,defer:1,disabled:1,ismap:1,multiple:1,nohref:1,noresize:1,noshade:1,nowrap:1,readonly:1,selected:1};CKEDITOR.htmlParser.prototype={onTagOpen:function(){},onTagClose:function(){},onText:function(){},onCDATA:function(){},onComment:function(){},parse:function(b){for(var c,d,g=0,h;c=this._.htmlPartsRegex.exec(b);){d=c.index;if(d>g){g=b.substring(g,d);if(h)h.push(g);else this.onText(g)}g=", "label": 1, "label_name": "safe"} -{"code": " public T setResult(Class resultClass) throws SQLException {\n try {\n if (isDebugEnabled()) {\n debugCode(\n \"setResult(\" + (resultClass != null ? resultClass.getSimpleName() + \".class\" : \"null\") + ')');\n }\n checkEditable();\n if (resultClass == null || resultClass == DOMResult.class) {\n domResult = new DOMResult();\n state = State.SET_CALLED;\n return (T) domResult;\n } else if (resultClass == SAXResult.class) {\n SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance();\n TransformerHandler transformerHandler = transformerFactory.newTransformerHandler();\n Writer writer = setCharacterStreamImpl();\n transformerHandler.setResult(new StreamResult(writer));\n SAXResult saxResult = new SAXResult(transformerHandler);\n closable = writer;\n state = State.SET_CALLED;\n return (T) saxResult;\n } else if (resultClass == StAXResult.class) {\n XMLOutputFactory xof = XMLOutputFactory.newInstance();\n Writer writer = setCharacterStreamImpl();\n StAXResult staxResult = new StAXResult(xof.createXMLStreamWriter(writer));\n closable = writer;\n state = State.SET_CALLED;\n return (T) staxResult;\n } else if (StreamResult.class.equals(resultClass)) {\n Writer writer = setCharacterStreamImpl();\n StreamResult streamResult = new StreamResult(writer);\n closable = writer;\n state = State.SET_CALLED;\n return (T) streamResult;\n }\n throw unsupported(resultClass.getName());\n } catch (Exception e) {\n throw logAndConvert(e);\n }\n }", "label": 1, "label_name": "safe"} -{"code": "this.editor.embedExtFonts(mxUtils.bind(this,function(g){try{null!=g&&this.editor.addFontCss(c,g),e(c)}catch(k){e(c)}}))}catch(g){e(c)}}))};EditorUi.prototype.exportImage=function(c,e,g,k,m,q,v,y,A,z,L,M,n){A=null!=A?A:\"png\";if(this.spinner.spin(document.body,mxResources.get(\"exporting\"))){var x=this.editor.graph.isSelectionEmpty();g=null!=g?g:x;null==this.thumbImageCache&&(this.thumbImageCache={});try{this.editor.exportToCanvas(mxUtils.bind(this,function(K){this.spinner.stop();try{this.saveCanvas(K,\nm?this.getFileData(!0,null,null,null,g,y):null,A,null==this.pages||0==this.pages.length,L)}catch(B){this.handleError(B)}}),null,this.thumbImageCache,null,mxUtils.bind(this,function(K){this.spinner.stop();this.handleError(K)}),null,g,c||1,e,k,null,null,q,v,z,M,n)}catch(K){this.spinner.stop(),this.handleError(K)}}};EditorUi.prototype.isCorsEnabledForUrl=function(c){return this.editor.isCorsEnabledForUrl(c)};EditorUi.prototype.importXml=function(c,e,g,k,m,q,v){e=null!=e?e:0;g=null!=g?g:0;var y=[];try{var A=", "label": 1, "label_name": "safe"} -{"code": " it 'should match user permissions from list' do\n @provider.class.expects(:rabbitmqctl).with('list_user_permissions', 'foo').returns <<-EOT\nListing users ...\nbar 1 2 3\n...done.\nEOT\n @provider.exists?.should == {:configure=>\"1\", :write=>\"2\", :read=>\"3\"}\n end", "label": 0, "label_name": "vulnerable"} -{"code": "function isValidKey(key) {\n return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';\n}", "label": 1, "label_name": "safe"} -{"code": " def __init__(self, pidfile=None):\n if not pidfile:\n # PID file moved out of /tmp to avoid security vulnerability\n # changed by Debian maintainer per Debian bug #631912\n self.pidfile = \"/var/run/pyro-%s.pid\" % self.__class__.__name__.lower()\n else:\n self.pidfile = pidfile", "label": 1, "label_name": "safe"} -{"code": " public function getTransactionReference()\n {\n if (isset($this->data['object']) && 'charge' === $this->data['object']) {\n return $this->data['id'];\n }\n if (isset($this->data['error']) && isset($this->data['error']['charge'])) {\n return $this->data['error']['charge'];\n }\n\n return;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable {\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\n sb.childHandler(new SimpleChannelInboundHandler() {\n @Override\n protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {\n // Just drop the message.\n }\n });\n cb.handler(new ChannelInboundHandlerAdapter());\n\n Channel sc = sb.bind().sync().channel();\n Channel cc = cb.connect(sc.localAddress()).sync().channel();\n\n // Request file region which is bigger then the underlying file.\n FileRegion region = new DefaultFileRegion(\n new RandomAccessFile(file, \"r\").getChannel(), 0, data.length + 1024);\n\n assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.instanceOf(IOException.class));\n cc.close().sync();\n sc.close().sync();\n }", "label": 1, "label_name": "safe"} -{"code": "private static byte[] init__puma_parser_single_lengths_0()\n{\n\treturn new byte [] {\n\t 0, 2, 3, 4, 2, 1, 1, 1, 1, 1, 0, 1,\n\t 0, 1, 1, 4, 1, 4, 2, 1, 4, 4, 2, 6,\n\t 7, 6, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n\t 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0\n\t};\n}", "label": 0, "label_name": "vulnerable"} -{"code": "e[g].parentNode));return c};EditorUi.prototype.synchronizeCurrentFile=function(c){var e=this.getCurrentFile();null!=e&&(e.savingFile?this.handleError({message:mxResources.get(\"busy\")}):!c&&e.invalidChecksum?e.handleFileError(null,!0):this.spinner.spin(document.body,mxResources.get(\"updatingDocument\"))&&(e.clearAutosave(),this.editor.setStatus(\"\"),c?e.reloadFile(mxUtils.bind(this,function(){e.handleFileSuccess(\"manual\"==DrawioFile.SYNC)}),mxUtils.bind(this,function(g){e.handleFileError(g,!0)})):e.synchronizeFile(mxUtils.bind(this,\nfunction(){e.handleFileSuccess(\"manual\"==DrawioFile.SYNC)}),mxUtils.bind(this,function(g){e.handleFileError(g,!0)}))))};EditorUi.prototype.getFileData=function(c,e,g,k,m,q,v,x,A,z,L){m=null!=m?m:!0;q=null!=q?q:!1;var M=this.editor.graph;if(e||!c&&null!=A&&/(\\.svg)$/i.test(A.getTitle())){var n=null!=M.themes&&\"darkTheme\"==M.defaultThemeName;z=!1;if(n||null!=this.pages&&this.currentPage!=this.pages[0]){var y=M.getGlobalVariable;M=this.createTemporaryGraph(n?M.getDefaultStylesheet():M.getStylesheet());", "label": 0, "label_name": "vulnerable"} -{"code": "func TestClean(t *testing.T) {\n\ttests := []struct {\n\t\tpath string\n\t\twantVal string\n\t}{\n\t\t{\n\t\t\tpath: \"../../../readme.txt\",\n\t\t\twantVal: \"readme.txt\",\n\t\t},\n\t\t{\n\t\t\tpath: \"a/../../../readme.txt\",\n\t\t\twantVal: \"readme.txt\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/../a/b/../c/../readme.txt\",\n\t\t\twantVal: \"a/readme.txt\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/a/readme.txt\",\n\t\t\twantVal: \"a/readme.txt\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/\",\n\t\t\twantVal: \"\",\n\t\t},\n\n\t\t{\n\t\t\tpath: \"/a/b/c/readme.txt\",\n\t\t\twantVal: \"a/b/c/readme.txt\",\n\t\t},\n\n\t\t// Windows-specific\n\t\t{\n\t\t\tpath: `..\\..\\..\\readme.txt`,\n\t\t\twantVal: \"readme.txt\",\n\t\t},\n\t\t{\n\t\t\tpath: `a\\..\\..\\..\\readme.txt`,\n\t\t\twantVal: \"readme.txt\",\n\t\t},\n\t\t{\n\t\t\tpath: `\\..\\a\\b\\..\\c\\..\\readme.txt`,\n\t\t\twantVal: \"a/readme.txt\",\n\t\t},\n\t\t{\n\t\t\tpath: `\\a\\readme.txt`,\n\t\t\twantVal: \"a/readme.txt\",\n\t\t},\n\t\t{\n\t\t\tpath: `..\\..\\..\\../README.md`,\n\t\t\twantVal: \"README.md\",\n\t\t},\n\t\t{\n\t\t\tpath: `\\`,\n\t\t\twantVal: \"\",\n\t\t},\n\n\t\t{\n\t\t\tpath: `\\a\\b\\c\\readme.txt`,\n\t\t\twantVal: `a/b/c/readme.txt`,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.path, func(t *testing.T) {\n\t\t\tassert.Equal(t, test.wantVal, Clean(test.path))\n\t\t})\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": "fn _make_process_from_less_path(\n less_path: PathBuf,\n args: &[String],\n replace_arguments_to_less: bool,\n quit_if_one_screen: bool,\n config: &config::Config,\n) -> Option {\n if let Ok(less_path) = grep_cli::resolve_binary(less_path) {\n let mut p = Command::new(&less_path);\n if args.is_empty() || replace_arguments_to_less {\n p.args(vec![\"--RAW-CONTROL-CHARS\"]);\n\n // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older\n // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.\n //\n // See: http://www.greenwoodsoftware.com/less/news.530.html\n //\n // For newer versions (530 or 558 on Windows), we omit '--no-init' as it\n // is not needed anymore.\n match retrieve_less_version() {\n None => {\n p.arg(\"--no-init\");\n }\n Some(version) if (version < 530 || (cfg!(windows) && version < 558)) => {\n p.arg(\"--no-init\");\n }\n _ => {}\n }\n\n if quit_if_one_screen {\n p.arg(\"--quit-if-one-screen\");\n }\n } else {\n p.args(args);\n }\n p.env(\"LESSCHARSET\", \"UTF-8\");\n p.env(\"LESSANSIENDCHARS\", \"mK\");\n if config.navigate {\n if let Ok(hist_file) = navigate::copy_less_hist_file_and_append_navigate_regexp(config)\n {\n p.env(\"LESSHISTFILE\", hist_file);\n if config.show_themes {\n p.arg(\"+n\");\n }\n }\n }\n Some(p)\n } else {\n None\n }\n}", "label": 1, "label_name": "safe"} -{"code": " public function __construct($escapeChar = \"'\", array $startingChars = ['=', '-', '+', '@'])\n {\n $this->escapeChar = $escapeChar;\n $this->startingChars = $startingChars;\n }", "label": 1, "label_name": "safe"} -{"code": " def get_by_name(self, name, project):\n return (\n Person.query.filter(Person.name == name)\n .filter(Person.project_id == project.id)\n .one()\n )", "label": 1, "label_name": "safe"} -{"code": " public function handleElement(&$token)\n {\n if (!$token instanceof HTMLPurifier_Token_Start) {\n return;\n }\n $next = false;\n $deleted = 1; // the current tag\n for ($i = count($this->inputZipper->back) - 1; $i >= 0; $i--, $deleted++) {\n $next = $this->inputZipper->back[$i];\n if ($next instanceof HTMLPurifier_Token_Text) {\n if ($next->is_whitespace) {\n continue;\n }\n if ($this->removeNbsp && !isset($this->removeNbspExceptions[$token->name])) {\n $plain = str_replace(\"\\xC2\\xA0\", \"\", $next->data);\n $isWsOrNbsp = $plain === '' || ctype_space($plain);\n if ($isWsOrNbsp) {\n continue;\n }\n }\n }\n break;\n }\n if (!$next || ($next instanceof HTMLPurifier_Token_End && $next->name == $token->name)) {\n $this->attrValidator->validateToken($token, $this->config, $this->context);\n $token->armor['ValidateAttributes'] = true;\n if (isset($this->exclude[$token->name])) {\n $r = true;\n foreach ($this->exclude[$token->name] as $elem) {\n if (!isset($token->attr[$elem])) $r = false;\n }\n if ($r) return;\n }\n if (isset($token->attr['id']) || isset($token->attr['name'])) {\n return;\n }\n $token = $deleted + 1;\n for ($b = 0, $c = count($this->inputZipper->front); $b < $c; $b++) {\n $prev = $this->inputZipper->front[$b];\n if ($prev instanceof HTMLPurifier_Token_Text && $prev->is_whitespace) {\n continue;\n }\n break;\n }\n // This is safe because we removed the token that triggered this.\n $this->rewindOffset($b+$deleted);\n return;\n }\n }", "label": 1, "label_name": "safe"} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);\n const TfLiteTensor* segment_ids =\n GetInput(context, node, kInputSegmentIdsTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context,\n ResizeOutputTensor(context, data, segment_ids, output));\n }\n\n#define TF_LITE_SEGMENT_SUM(dtype) \\\n reference_ops::SegmentSum( \\\n GetTensorShape(data), GetTensorData(data), \\\n GetTensorShape(segment_ids), GetTensorData(segment_ids), \\\n GetTensorShape(output), GetTensorData(output));\n switch (data->type) {\n case kTfLiteInt32:\n TF_LITE_SEGMENT_SUM(int32_t);\n break;\n case kTfLiteFloat32:\n TF_LITE_SEGMENT_SUM(float);\n break;\n default:\n context->ReportError(context,\n \"Currently SegmentSum doesn't support type: %s\",\n TfLiteTypeGetName(data->type));\n return kTfLiteError;\n }\n#undef TF_LITE_SEGMENT_SUM\n return kTfLiteOk;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " private function addFrozenCompile()\n {\n return <<params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the comment you would like to delete'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n // delete the note\n $simplenote = new expSimpleNote($this->params['id']);\n $rows = $simplenote->delete();\n \n // delete the assocication too\n $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']); \n \n // send the user back where they came from.\n $lastUrl = expHistory::getLast('editable');\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testImgRemoveInvalidAlign()\n {\n $this->assertResult(\n '\"foobar\"',\n '\"foobar\"'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " public Secret getDefaultValueAsSecret() {\n return defaultValue;\n }", "label": 1, "label_name": "safe"} -{"code": " function wrapped(...args) {\n ++context.actual;\n return fn.call(this, ...args);\n }", "label": 1, "label_name": "safe"} -{"code": " public function testClear()\n {\n $bag = new ParameterBag($parameters = array(\n 'foo' => 'foo',\n 'bar' => 'bar',\n ));\n $bag->clear();\n $this->assertEquals(array(), $bag->all(), '->clear() removes all parameters');\n }", "label": 0, "label_name": "vulnerable"} -{"code": "id3_skip (SF_PRIVATE * psf)\n{\tunsigned char\tbuf [10] ;\n\n\tmemset (buf, 0, sizeof (buf)) ;\n\tpsf_binheader_readf (psf, \"pb\", 0, buf, 10) ;\n\n\tif (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3')\n\t{\tint\toffset = buf [6] & 0x7f ;\n\t\toffset = (offset << 7) | (buf [7] & 0x7f) ;\n\t\toffset = (offset << 7) | (buf [8] & 0x7f) ;\n\t\toffset = (offset << 7) | (buf [9] & 0x7f) ;\n\n\t\tpsf_log_printf (psf, \"ID3 length : %d\\n--------------------\\n\", offset) ;\n\n\t\t/* Never want to jump backwards in a file. */\n\t\tif (offset < 0)\n\t\t\treturn 0 ;\n\n\t\t/* Calculate new file offset and position ourselves there. */\n\t\tpsf->fileoffset += offset + 10 ;\n\n\t\tif (psf->fileoffset < psf->filelength)\n\t\t{\tpsf_binheader_readf (psf, \"p\", psf->fileoffset) ;\n\t\t\treturn 1 ;\n\t\t\t} ;\n\t\t} ;\n\n\treturn 0 ;\n} /* id3_skip */", "label": 1, "label_name": "safe"} -{"code": " def generation_time\n Time.at(@data.pack(\"C4\").unpack(\"N\")[0]).utc\n end", "label": 0, "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\" + \"/lxc/lock/$lxcpath/$lxcname + '\\0' if root\n\t * or\n\t * $XDG_RUNTIME_DIR + \"/lxc/lock/$lxcpath/$lxcname + '\\0' if non-root\n\t */\n\n\t/* length of \"/lxc/lock/\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0' */\n\tlen = strlen(\"/lxc/lock/\") + 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/lxc/lock/%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\tfree(dest);\n\t\tfree(rundir);\n\t\treturn NULL;\n\t}\n\n\tret = snprintf(dest, len, \"%s/lxc/lock/%s/.%s\", rundir, p, n);\n\tfree(rundir);\n\tif (ret < 0 || ret >= len) {\n\t\tfree(dest);\n\t\treturn NULL;\n\t}\n\treturn dest;\n}", "label": 1, "label_name": "safe"} -{"code": " public function testStoresACacheEntry()\n {\n $cacheKey = $this->storeSimpleEntry();\n\n $this->assertNotEmpty($this->getStoreMetadata($cacheKey));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {\n const channel = this._chanMgr.get(recipient);\n if (typeof channel !== 'object' || channel === null)\n return;\n\n // The other side is allowing us to send `amount` more bytes of data\n channel.outgoing.window += amount;\n\n if (channel._waitWindow) {\n channel._waitWindow = false;\n\n if (channel._chunk) {\n channel._write(channel._chunk, null, channel._chunkcb);\n } else if (channel._chunkcb) {\n channel._chunkcb();\n } else if (channel._chunkErr) {\n channel.stderr._write(channel._chunkErr,\n null,\n channel._chunkcbErr);\n } else if (channel._chunkcbErr) {\n channel._chunkcbErr();\n }\n }\n },", "label": 1, "label_name": "safe"} -{"code": " def test_chunking_request_without_content(self):\n header = tobytes(\"GET / HTTP/1.1\\n\" \"Transfer-Encoding: chunked\\n\\n\")\n self.connect()\n self.sock.send(header)\n self.sock.send(b\"0\\r\\n\\r\\n\")\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(echo.body, b\"\")\n self.assertEqual(echo.content_length, \"0\")\n self.assertFalse(\"transfer-encoding\" in headers)", "label": 0, "label_name": "vulnerable"} -{"code": " public function testOneTagWithSurroundingText()\n {\n $this->assertTextOutput('buffer text [b]this is bold[/b] buffer text',\n 'buffer text this is bold buffer text');\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def __init__(self,\n table,\n record=None,\n readonly=False,\n deletable=True,\n formstyle=FormStyleDefault,\n dbio=True,\n keepvalues=False,\n formname=False,\n hidden=None,\n csrf=True):", "label": 1, "label_name": "safe"} -{"code": " public List search(final String filter, final String[] filterArgs, final Mapper mapper, final int maxResultCount) {\n final List searchResults = new ArrayList<>();\n for (String searchBase : ldapConfiguration.getSearchBases()) {\n int resultsToFetch = resultsToFetch(maxResultCount, searchResults.size());\n\n if (resultsToFetch == -1) {\n break;\n }\n\n try {\n final SearchRequest searchRequest = new SearchRequestImpl()\n .setScope(SearchScope.SUBTREE)\n .addAttributes(\"*\")\n .setSizeLimit(resultsToFetch)\n .setFilter(FilterEncoder.format(filter, filterArgs))\n .setTimeLimit(ldapConfiguration.getSearchTimeout())\n .setBase(new Dn(searchBase));\n\n searchResults.addAll(ldapConnectionTemplate.search(searchRequest, mapper));\n } catch (LdapException e) {\n LOG.error(e.getMessage(), e);\n }\n }\n\n return searchResults;\n }", "label": 1, "label_name": "safe"} -{"code": " def reinit(self):\n \"\"\"Initialize the random number generator and seed it with entropy from\n the operating system.\n \"\"\"\n\n # Save the pid (helps ensure that Crypto.Random.atfork() gets called)\n self._pid = os.getpid()\n\n # Collect entropy from the operating system and feed it to\n # FortunaAccumulator\n self._ec.reinit()\n\n # Override FortunaAccumulator's 100ms minimum re-seed interval. This\n # is necessary to avoid a race condition between this function and\n # self.read(), which that can otherwise cause forked child processes to\n # produce identical output. (e.g. CVE-2013-1445)\n #\n # Note that if this function can be called frequently by an attacker,\n # (and if the bits from OSRNG are insufficiently random) it will weaken\n # Fortuna's ability to resist a state compromise extension attack.\n self._fa._forget_last_reseed()", "label": 1, "label_name": "safe"} -{"code": "this.unitListener=function(n,x){g.setUnit(x.getProperty(\"unit\"))};y.addListener(mxEvent.SIZE,f);y.container.addEventListener(\"scroll\",d);y.view.addListener(\"unitChanged\",this.unitListener);b.addListener(\"pageViewChanged\",this.pageListener);b.addListener(\"pageScaleChanged\",this.pageListener);b.addListener(\"pageFormatChanged\",this.pageListener);this.setStyle=function(n){k=n;m.style.background=k.bkgClr;z()};this.origGuideMove=mxGuide.prototype.move;mxGuide.prototype.move=function(n,x,K,B){if(l&&4collectors[$name]);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " void percent() {\n final PathAndQuery res = parse(\"/%25\");\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(\"/%25\");\n assertThat(res.query()).isNull();\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct () {\n self::$opt = json_decode(Options::v('mdo_theme_options'), true);\n if (self::$opt['mdo_adsense'] != '') {\n Hooks::attach('footer_load_lib', array('MdoTheme', 'loadAdsenseJs'));\n }\n }", "label": 1, "label_name": "safe"} -{"code": "check_entry_size_and_hooks(struct ip6t_entry *e,\n\t\t\t struct xt_table_info *newinfo,\n\t\t\t const unsigned char *base,\n\t\t\t const unsigned char *limit,\n\t\t\t const unsigned int *hook_entries,\n\t\t\t const unsigned int *underflows,\n\t\t\t unsigned int valid_hooks)\n{\n\tunsigned int h;\n\tint err;\n\n\tif ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||\n\t (unsigned char *)e + sizeof(struct ip6t_entry) >= limit) {\n\t\tduprintf(\"Bad offset %p\\n\", e);\n\t\treturn -EINVAL;\n\t}\n\n\tif (e->next_offset\n\t < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {\n\t\tduprintf(\"checking: element %p size %u\\n\",\n\t\t\t e, e->next_offset);\n\t\treturn -EINVAL;\n\t}\n\n\terr = check_entry(e);\n\tif (err)\n\t\treturn err;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_INET_NUMHOOKS; h++) {\n\t\tif (!(valid_hooks & (1 << h)))\n\t\t\tcontinue;\n\t\tif ((unsigned char *)e - base == hook_entries[h])\n\t\t\tnewinfo->hook_entry[h] = hook_entries[h];\n\t\tif ((unsigned char *)e - base == underflows[h]) {\n\t\t\tif (!check_underflow(e)) {\n\t\t\t\tpr_err(\"Underflows must be unconditional and \"\n\t\t\t\t \"use the STANDARD target with \"\n\t\t\t\t \"ACCEPT/DROP\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\tnewinfo->underflow[h] = underflows[h];\n\t\t}\n\t}\n\n\t/* Clear counters and comefrom */\n\te->counters = ((struct xt_counters) { 0, 0 });\n\te->comefrom = 0;\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tfunction testCommandCategorieExistence ($name = NULL)\t{\n\t\tglobal $pearDB, $form;\n\t\t$id = NULL;\n\t\t\n\t\tif (isset($form))\n\t\t\t$id = $form->getSubmitValue('cmd_category_id');\n\t\t\n\t\t$DBRESULT = $pearDB->query(\"SELECT `category_name`, `cmd_category_id` FROM `command_categories` WHERE `category_name` = '\".htmlentities($name, ENT_QUOTES, \"UTF-8\").\"'\");\n\t\t$cat = $DBRESULT->fetchRow();\n\t\t\n\t\tif ($DBRESULT->numRows() >= 1 && $cat[\"cmd_category_id\"] == $id)\n\t\t\treturn true;\n\t\telse if ($DBRESULT->numRows() >= 1 && $cat[\"cmd_category_id\"] != $id)\n\t\t\treturn false;\n\t\telse\n\t\t\treturn true;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function StartTLS() {\n $this->error = null; # to avoid confusion\n\n if(!$this->connected()) {\n $this->error = array(\"error\" => \"Called StartTLS() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"STARTTLS\" . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $rply . $this->CRLF . '
');\n }\n\n if($code != 220) {\n $this->error =\n array(\"error\" => \"STARTTLS not accepted from server\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
');\n }\n return false;\n }\n\n // Begin encrypted connection\n if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {\n return false;\n }\n\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian,\n const unsigned char *buffer)\n{\n unsigned short\n value;\n\n if (endian == LSBEndian)\n {\n value=(unsigned short) buffer[1] << 8;\n value|=(unsigned short) buffer[0];\n return(value & 0xffff);\n }\n value=(unsigned short) buffer[0] << 8;\n value|=(unsigned short) buffer[1];\n return(value & 0xffff);\n}", "label": 1, "label_name": "safe"} -{"code": "SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,\n\t\tunsigned int, flags, struct sockaddr __user *, addr,\n\t\tint __user *, addr_len)\n{\n\tstruct socket *sock;\n\tstruct iovec iov;\n\tstruct msghdr msg;\n\tstruct sockaddr_storage address;\n\tint err, err2;\n\tint fput_needed;\n\n\tif (size > INT_MAX)\n\t\tsize = INT_MAX;\n\tsock = sockfd_lookup_light(fd, &err, &fput_needed);\n\tif (!sock)\n\t\tgoto out;\n\n\tmsg.msg_control = NULL;\n\tmsg.msg_controllen = 0;\n\tmsg.msg_iovlen = 1;\n\tmsg.msg_iov = &iov;\n\tiov.iov_len = size;\n\tiov.iov_base = ubuf;\n\t/* Save some cycles and don't copy the address if not needed */\n\tmsg.msg_name = addr ? (struct sockaddr *)&address : NULL;\n\t/* We assume all kernel code knows the size of sockaddr_storage */\n\tmsg.msg_namelen = 0;\n\tif (sock->file->f_flags & O_NONBLOCK)\n\t\tflags |= MSG_DONTWAIT;\n\terr = sock_recvmsg(sock, &msg, size, flags);\n\n\tif (err >= 0 && addr != NULL) {\n\t\terr2 = move_addr_to_user(&address,\n\t\t\t\t\t msg.msg_namelen, addr, addr_len);\n\t\tif (err2 < 0)\n\t\t\terr = err2;\n\t}\n\n\tfput_light(sock->file, fput_needed);\nout:\n\treturn err;\n}", "label": 1, "label_name": "safe"} -{"code": " public static function detectByFilename($filename)\n {\n $extension = pathinfo($filename, PATHINFO_EXTENSION);\n\n return empty($extension) ? 'text/plain' : static::detectByFileExtension($extension);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static void do_free_upto(BIO *f, BIO *upto)\n\t{\n\tif (upto)\n\t\t{\n\t\tBIO *tbio;\n\t\tdo \n\t\t\t{\n\t\t\ttbio = BIO_pop(f);\n\t\t\tBIO_free(f);\n\t\t\tf = tbio;\n\t\t\t}\n\t\twhile (f != upto);\n\t\t}\n\telse\n\t\tBIO_free_all(f);\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " private function setMasterRequest($request)\n {\n $this->requestStack\n ->expects($this->any())\n ->method('getParentRequest')\n ->will($this->returnValue($request));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " [ISREUSABLE] (entry, st) {\n return entry.type === 'File' &&\n !this.unlink &&\n st.isFile() &&\n st.nlink <= 1 &&\n process.platform !== 'win32'\n }", "label": 1, "label_name": "safe"} -{"code": "func IsLocalHostname(hostname string, allowlist []string) bool {\n\tfor _, allow := range allowlist {\n\t\tif hostname == allow {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tips, err := net.LookupIP(hostname)\n\tif err != nil {\n\t\treturn true\n\t}\n\tfor _, ip := range ips {\n\t\tfor _, cidr := range localCIDRs {\n\t\t\tif cidr.Contains(ip) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "label": 0, "label_name": "vulnerable"} -{"code": "def _get_mw(settings_dict=None):\n crawler = _get_crawler(settings_dict or {})\n return SplashMiddleware.from_crawler(crawler)", "label": 1, "label_name": "safe"} -{"code": " def test_request_body_too_large_with_wrong_cl_http10_keepalive(self):\n body = \"a\" * self.toobig\n to_send = \"GET / HTTP/1.0\\n\" \"Content-Length: 5\\n\" \"Connection: Keep-Alive\\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 # first request succeeds (content-length 5)\n line, headers, response_body = read_http(fp)\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 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, "label_name": "vulnerable"} -{"code": " public function editAlt() {\n global $user; \n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->alt = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);\n } else {\n $ar = new expAjaxReply(300, gt(\"You didn't create this file, so you can't edit it.\"));\n }\n $ar->send();\n echo json_encode($file); //FIXME we exit before hitting this\n } ", "label": 0, "label_name": "vulnerable"} -{"code": "function(){};var E=l.getSelectionModel().changeSelection;l.getSelectionModel().changeSelection=function(){E.call(this,[x],[x])}};g.onerror=function(){g.onload=null;g.src=Editor.errorImage};g.setAttribute(\"src\",e);g.style.maxWidth=\"300px\";g.style.maxHeight=\"300px\";d.appendChild(g);v.appendChild(d);var k=document.createElement(\"div\");k.style.width=\"300px\";k.style.height=\"300px\";k.style.overflow=\"hidden\";k.style.backgroundColor=\"#fff9\";v.appendChild(k);var l=null,p=new mxGeometry(100,100,100,100),q=", "label": 0, "label_name": "vulnerable"} -{"code": " def login(username, password)\n session.context.login(name, username, password)\n end", "label": 1, "label_name": "safe"} -{"code": " it 'should be able to backup events table' do\n verify_contents(subject, 'mysqlbackup.sh', [\n 'EVENTS=\"--events\"',\n ])\n end", "label": 0, "label_name": "vulnerable"} -{"code": "ca,ca,!1)[0];ia.push(Fa);if(L)T.add(ya,ua[M]);else{var Ma=ya.getIndex(z[M]);T.add(ya,ua[M],Ma+1)}if(this.isTable(ya)){var Oa=this.getCellGeometry(ua[M]),Qa=this.getCellGeometry(ya);null!=Oa&&null!=Qa&&(Qa=Qa.clone(),Qa.height+=Oa.height,T.setGeometry(ya,Qa))}}else ia.push(ua[M])}this.updateCustomLinks(this.createCellMapping(ma,pa),ua,this);this.fireEvent(new mxEventObject(mxEvent.CELLS_ADDED,\"cells\",ua))}finally{T.endUpdate()}return ia};Graph.prototype.insertImage=function(z,L,M){if(null!=z&&null!=\nthis.cellEditor.textarea){for(var T=this.cellEditor.textarea.getElementsByTagName(\"img\"),ca=[],ia=0;ia:(\",angel:\"o:)\",cool:\"8-)\",devil:\">:-)\",crying:\";(\",kiss:\":-*\"},y={},p=[],q;for(q in o)y[o[q]]=q,p.push(o[q].replace(/\\(|\\)|\\:|\\/|\\*|\\-|\\|/g,function(a){return\"\\\\\"+a}));var p=RegExp(p.join(\"|\"),\"g\"),A=function(){var a=[],b={nbsp:\"\u00a0\",shy:\"\u00ad\",gt:\">\",lt:\"<\"},c;for(c in b)a.push(c);a=RegExp(\"&(\"+a.join(\"|\")+\");\",\"g\");return function(c){return c.replace(a,function(e,a){return b[a]})}}();CKEDITOR.BBCodeParser=function(){this._={bbcPartsRegex:/(?:\\[([^\\/\\]=]*?)(?:=([^\\]]*?))?\\])|(?:\\[\\/([a-z]{1,16})\\])/ig}};", "label": 1, "label_name": "safe"} -{"code": " public HtmlElement content(String body) {\n return content(new TextElement(body));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "I.height,Y.y+Y.height)-Math.max(I.y,Y.y))/C))}}P?X=0:Q=0;for(O=0;Opayload[offset+4], is_printable = 1;\n char *str;\n u_int len, j;\n\n if (*rdnSeqBuf_offset >= rdnSeqBuf_len) {\n#ifdef DEBUG_TLS\n printf(\"[TLS] %s() [buffer capacity reached][%u]\\n\",\n __FUNCTION__, rdnSeqBuf_len);\n#endif\n return -1;\n }\n\n // packet is truncated... further inspection is not needed\n if((offset+4+str_len) >= packet->payload_packet_len)\n return(-1);\n\n str = (char*)&packet->payload[offset+5];\n\n len = (u_int)ndpi_min(str_len, buffer_len-1);\n strncpy(buffer, str, len);\n buffer[len] = '\\0';\n\n // check string is printable\n for(j = 0; j < len; j++) {\n if(!ndpi_isprint(buffer[j])) {\n is_printable = 0;\n break;\n }\n }\n\n if(is_printable) {\n int rc = snprintf(&rdnSeqBuf[*rdnSeqBuf_offset],\n\t\t rdnSeqBuf_len-(*rdnSeqBuf_offset),\n\t\t \"%s%s=%s\", (*rdnSeqBuf_offset > 0) ? \", \" : \"\",\n\t\t label, buffer);\n\n if(rc > 0)\n (*rdnSeqBuf_offset) += rc;\n }\n\n return(is_printable);\n}", "label": 1, "label_name": "safe"} -{"code": "function phorum_htmlpurifier_save_settings()\n{\n global $PHORUM;\n if (phorum_htmlpurifier_config_file_exists()) {\n echo \"Cannot update settings, mods/htmlpurifier/config.php already exists. To change\n settings, edit that file. To use the web form, delete that file.
\";\n } else {\n $config = phorum_htmlpurifier_get_config(true);\n if (!isset($_POST['reset'])) $config->mergeArrayFromForm($_POST, 'config', $PHORUM['mod_htmlpurifier']['directives']);\n $PHORUM['mod_htmlpurifier']['config'] = $config->getAll();\n }\n $PHORUM['mod_htmlpurifier']['wysiwyg'] = !empty($_POST['wysiwyg']);\n $PHORUM['mod_htmlpurifier']['suppress_message'] = !empty($_POST['suppress_message']);\n if(!phorum_htmlpurifier_commit_settings()){\n $error=\"Database error while updating settings.\";\n } else {\n echo \"Settings Updated
\";\n }\n}", "label": 1, "label_name": "safe"} -{"code": "e=0,d=c.length;eonRequestMetadata_) {\n return Http::FilterMetadataStatus::Continue;\n }\n if (wasm_->onRequestMetadata_(this, id_).u64_ == 0) {\n return Http::FilterMetadataStatus::Continue;\n }\n return Http::FilterMetadataStatus::Continue; // This is currently the only return code.\n}", "label": 1, "label_name": "safe"} -{"code": "fn should_correctly_handle_long_label_when_splitted() {\n\t// given\n\tlet (server, fetch) = serve_with_fetch(\"xolrg9fePeQyKLnL\", \"https://contribution.melonport.com\");\n\n\t// when\n\tlet response = request(server,\n\t\t\"\\\n\t\t\tGET /styles.css?test=123 HTTP/1.1\\r\\n\\\n\t\t\tHost: f1qprwk775k6am35a5wmpk3e9gnpgx3me1sk.mbsfcdqpwx3jd5h7ax39dxq2wvb5dhqpww3fe9t2wrvfdm.web.web3.site\\r\\n\\\n\t\t\tConnection: close\\r\\n\\\n\t\t\t\\r\\n\\\n\t\t\"\n\t);\n\n\t// then\n\tresponse.assert_status(\"HTTP/1.1 200 OK\");\n\tassert_security_headers_for_embed(&response.headers);\n\n\tfetch.assert_requested(\"https://contribution.melonport.com/styles.css?test=123\");\n\tfetch.assert_no_more_requests();\n}", "label": 1, "label_name": "safe"} -{"code": " def initialize(path)\n @path = path\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public RoutingResultBuilder rawParam(String name, String value) {\n pathParams().put(requireNonNull(name, \"name\"),\n ArmeriaHttpUtil.decodePathParam(requireNonNull(value, \"value\")));\n return this;\n }", "label": 1, "label_name": "safe"} -{"code": " def exists?\n @property_hash[:ensure] == :present\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct($config)\n {\n $def = $config->getCSSDefinition();\n $this->info['background-color'] = $def->info['background-color'];\n $this->info['background-image'] = $def->info['background-image'];\n $this->info['background-repeat'] = $def->info['background-repeat'];\n $this->info['background-attachment'] = $def->info['background-attachment'];\n $this->info['background-position'] = $def->info['background-position'];\n }", "label": 1, "label_name": "safe"} -{"code": "function setUser (cb) {\n var defaultConf = this.root\n assert(defaultConf !== Object.prototype)\n\n // If global, leave it as-is.\n // If not global, then set the user to the owner of the prefix folder.\n // Just set the default, so it can be overridden.\n if (this.get('global')) return cb()\n if (process.env.SUDO_UID) {\n defaultConf.user = +(process.env.SUDO_UID)\n return cb()\n }\n\n var prefix = path.resolve(this.get('prefix'))\n correctMkdir(prefix, function (er) {\n if (er) return cb(er)\n fs.stat(prefix, function (er, st) {\n defaultConf.user = st && st.uid\n return cb(er)\n })\n })\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function getModuleItemString() {\n\t\t$ret = $this->handler->_moduleName . '_' . $this->handler->_itemname;\n\t\treturn $ret;\n\t}", "label": 1, "label_name": "safe"} -{"code": " $scope.initialize = function() {\n growl.success('Retrieving definition for requisition ' + $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": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": "\tpublic static function onParserFirstCallInit( Parser &$parser ) {\n\t\tself::init();\n\n\t\t//DPL offers the same functionality as Intersection. So we register the tag in case LabeledSection Extension is not installed so that the section markers are removed.\n\t\tif ( \\DPL\\Config::getSetting( 'handleSectionTag' ) ) {\n\t\t\t$parser->setHook( 'section', [ __CLASS__, 'dplTag' ] );\n\t\t}\n\n\t\t$parser->setHook( 'DPL', [ __CLASS__, 'dplTag' ] );\n\t\t$parser->setHook( 'DynamicPageList', [ __CLASS__, 'intersectionTag' ] );\n\n\t\t$parser->setFunctionHook( 'dpl', [ __CLASS__, 'dplParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplnum', [ __CLASS__, 'dplNumParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplvar', [ __CLASS__, 'dplVarParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplreplace', [ __CLASS__, 'dplReplaceParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplchapter', [ __CLASS__, 'dplChapterParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplmatrix', [ __CLASS__, 'dplMatrixParserFunction' ] );\n\n\t\treturn true;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "\tprivate TextBlock getTitleBlock(IGroup g) {\n\t\tfinal Display label = g.getDisplay();\n\t\tif (label == null)\n\t\t\treturn TextBlockUtils.empty(0, 0);\n\n\t\tfinal ISkinParam skinParam = dotData.getSkinParam();\n\t\tfinal FontConfiguration fontConfiguration;\n\t\tif (UseStyle.useBetaStyle()) {\n\t\t\tfinal SName sname = dotData.getUmlDiagramType().getStyleName();\n\t\t\tfinal StyleSignatureBasic signature;\n\t\t\tfinal USymbol uSymbol = g.getUSymbol();\n\t\t\tif (uSymbol == USymbols.RECTANGLE)\n\t\t\t\tsignature = StyleSignatureBasic.of(SName.root, SName.element, sname, uSymbol.getSName(), SName.title);\n\t\t\telse\n\t\t\t\tsignature = StyleSignatureBasic.of(SName.root, SName.element, sname, SName.title);\n\n\t\t\tfinal Style style = signature //\n\t\t\t\t\t.withTOBECHANGED(g.getStereotype()) //\n\t\t\t\t\t.with(g.getStereostyles()) //\n\t\t\t\t\t.getMergedStyle(skinParam.getCurrentStyleBuilder());\n\n\t\t\tfontConfiguration = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());\n\t\t} else\n\t\t\tfontConfiguration = g.getFontConfigurationForTitle(skinParam);\n\t\tfinal HorizontalAlignment alignment = HorizontalAlignment.CENTER;\n\t\treturn label.create(fontConfiguration, alignment, dotData.getSkinParam());\n\t}", "label": 0, "label_name": "vulnerable"} -{"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 f=null!=b.view&&null!=b.view.canvas?b.view.canvas.ownerSVGElement:null;if(null!=b.container&&null!=f){b.addListener(mxEvent.ESCAPE,mxUtils.bind(this,function(){this.stopDrawing()}));var l=mxFreehand.prototype.NORMAL_SMOOTHING,d=null,u=[],t,D=[],c,e=!1,g=!0,k=!0,m=!0,q=!0,v=[],y=!1,A=!0,z=!1,L={size:12,thinning:.5,smoothing:.5,streamline:.5,start:{taper:0,cap:!0},end:{taper:0,cap:!0}},M=!1;this.setClosedPath=function(J){e=J};this.setAutoClose=function(J){g=J};this.setAutoInsert=", "label": 1, "label_name": "safe"} -{"code": " def should_deny_admin(self):\n return self.totp_status != TOTPStatus.ENABLED and config.get(\n \"enable_force_admin_2fa\"\n )", "label": 0, "label_name": "vulnerable"} -{"code": " it \"drops the index that matches the key\" do\n indexes[name: 1].should be_nil\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it 'prefixs array of values with undef' do\n pp = <<-EOS\n $o = prefix(['a','b','c'], undef)\n notice(inline_template('prefix is <%= @o.inspect %>'))\n EOS\n\n apply_manifest(pp, :catch_failures => true) do |r|\n expect(r.stdout).to match(/prefix is \\[\"a\", \"b\", \"c\"\\]/)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\t\tsetuprimg = function() {\n\t\t\t\t\t\tvar r_scale;\n\t\t\t\t\t\tr_scale = Math.min(pwidth, pheight) / Math.sqrt(Math.pow(owidth, 2) + Math.pow(oheight, 2));\n\t\t\t\t\t\trwidth = owidth * r_scale;\n\t\t\t\t\t\trheight = oheight * r_scale;\n\t\t\t\t\t\timgr.width(rwidth)\n\t\t\t\t\t\t\t.height(rheight)\n\t\t\t\t\t\t\t.css('margin-top', (pheight-rheight)/2 + 'px')\n\t\t\t\t\t\t\t.css('margin-left', (pwidth-rwidth)/2 + 'px');\n\t\t\t\t\t},", "label": 1, "label_name": "safe"} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=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": 0, "label_name": "vulnerable"} -{"code": " def clean_text(text)\n text.gsub(/[\\000-\\b\\v-\\f\\016-\\037\\177]/, \".\".freeze)\n end", "label": 1, "label_name": "safe"} -{"code": " def __setstate__(self, state):\n \"\"\"Restore from pickled state.\"\"\"\n self.__dict__ = state\n self._lock = threading.RLock()\n self._descriptor_cache = weakref.WeakKeyDictionary()\n self._key_for_call_stats = self._get_key_for_call_stats()", "label": 1, "label_name": "safe"} -{"code": "'\" y=\"'+p.y.toFixed(2)+'\"/>'):V+('')}V+=\"\";if(b.isEnabled()&&!b.isCellLocked(b.getDefaultParent())){E=this.createStyle(\"stencil(\"+Graph.compress(V)+\")\");V=b.view.scale;X=b.view.translate;E=new mxCell(\"\",new mxGeometry(H/V-X.x,U/V-X.y,J/V,S/V),E);E.vertex=1;b.model.beginUpdate();try{E=b.addCell(E),b.fireEvent(new mxEventObject(\"cellsInserted\",\"cells\",[E])),b.fireEvent(new mxEventObject(\"freehandInserted\",\"cell\",E))}finally{b.model.endUpdate()}z&&\nb.setSelectionCells([E])}}for(E=0;EEnvironOf()), m_pScan(scan), m_pFrame(frame)\n{\n m_ucCount = scan->ComponentsInScan();\n\n // The residual scan uses all components here, not just four, 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": 1, "label_name": "safe"} -{"code": "R=0;Rescape($value).'\" ';\n }\n return rtrim($html);\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function testCanLoadRegisteredAjaxView() {\n\t\t$request = $this->prepareHttpRequest('ajax/view/ajax_test/registered', 'GET', [], 1);\n\t\t\n\t\t$response = $this->executeRequest($request);\n\t\t$this->assertInstanceOf(\\Elgg\\Http\\OkResponse::class, $response);\n\t\t$this->assertEquals('registered', $response->getContent());\n\t}", "label": 1, "label_name": "safe"} -{"code": " parsePath (rawPath, opts = {}) {\n let pathObj = {\n locale: WIKI.config.lang.code,\n path: 'home',\n private: false,\n privateNS: '',\n explicitLocale: false\n }\n\n // Clean Path\n rawPath = _.trim(qs.unescape(rawPath))\n if (_.startsWith(rawPath, '/')) { rawPath = rawPath.substring(1) }\n rawPath = rawPath.replace(unsafeCharsRegex, '')\n if (rawPath === '') { rawPath = 'home' }\n\n rawPath = rawPath.replaceAll('\\\\', '').replaceAll('//', '').replaceAll(/\\.\\.+/ig, '')\n\n // Extract Info\n let pathParts = _.filter(_.split(rawPath, '/'), p => {\n p = _.trim(p)\n return !_.isEmpty(p) && p !== '..' && p !== '.'\n })\n if (pathParts[0].length === 1) {\n pathParts.shift()\n }\n if (localeSegmentRegex.test(pathParts[0])) {\n pathObj.locale = pathParts[0]\n pathObj.explicitLocale = true\n pathParts.shift()\n }\n\n // Strip extension\n if (opts.stripExt && pathParts.length > 0) {\n const lastPart = _.last(pathParts)\n if (lastPart.indexOf('.') > 0) {\n pathParts.pop()\n const lastPartMeta = path.parse(lastPart)\n pathParts.push(lastPartMeta.name)\n }\n }\n\n pathObj.path = _.join(pathParts, '/')\n return pathObj\n },", "label": 1, "label_name": "safe"} -{"code": "(function(){var b=new mxObjectCodec(new ChangeGridColor,[\"ui\"]);b.beforeDecode=function(e,f,c){c.ui=e.ui;return f};mxCodecRegistry.register(b)})();(function(){EditorUi.VERSION=\"18.0.7\";EditorUi.compactUi=\"atlas\"!=uiTheme;Editor.isDarkMode()&&(mxGraphView.prototype.gridColor=mxGraphView.prototype.defaultDarkGridColor);EditorUi.enableLogging=\"1\"!=urlParams.stealth&&\"1\"!=urlParams.lockdown&&(/.*\\.draw\\.io$/.test(window.location.hostname)||/.*\\.diagrams\\.net$/.test(window.location.hostname))&&\"support.draw.io\"!=window.location.hostname;EditorUi.drawHost=window.DRAWIO_BASE_URL;EditorUi.lightboxHost=window.DRAWIO_LIGHTBOX_URL;EditorUi.lastErrorMessage=", "label": 1, "label_name": "safe"} -{"code": "static int l2tp_ip_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n\t\t\t size_t len, int noblock, int flags, int *addr_len)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tsize_t copied = 0;\n\tint err = -EOPNOTSUPP;\n\tstruct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;\n\tstruct sk_buff *skb;\n\n\tif (flags & MSG_OOB)\n\t\tgoto out;\n\n\tif (addr_len)\n\t\t*addr_len = sizeof(*sin);\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\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto done;\n\n\tsock_recv_timestamp(msg, sk, skb);\n\n\t/* Copy the address. */\n\tif (sin) {\n\t\tsin->sin_family = AF_INET;\n\t\tsin->sin_addr.s_addr = ip_hdr(skb)->saddr;\n\t\tsin->sin_port = 0;\n\t\tmemset(&sin->sin_zero, 0, sizeof(sin->sin_zero));\n\t}\n\tif (inet->cmsg_flags)\n\t\tip_cmsg_recv(msg, skb);\n\tif (flags & MSG_TRUNC)\n\t\tcopied = skb->len;\ndone:\n\tskb_free_datagram(sk, skb);\nout:\n\treturn err ? err : copied;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function transform($attr, $config, $context)\n {\n if (!isset($attr['name'])) {\n return $attr;\n }\n $name = $attr['name'];\n if (isset($attr['id']) && $attr['id'] === $name) {\n return $attr;\n }\n $result = $this->idDef->validate($name, $config, $context);\n if ($result === false) {\n unset($attr['name']);\n } else {\n $attr['name'] = $result;\n }\n return $attr;\n }", "label": 1, "label_name": "safe"} -{"code": " function manage() {\r\n global $db, $router, $user;\r\n\r\n expHistory::set('manageable', $router->params);\r\n assign_to_template(array(\r\n 'canManageStandalones' => self::canManageStandalones(),\r\n 'sasections' => $db->selectObjects('section', 'parent=-1'),\r\n 'user' => $user,\r\n// 'canManagePagesets' => $user->isAdmin(),\r\n// 'templates' => $db->selectObjects('section_template', 'parent=0'),\r\n ));\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "cJSON *cJSON_CreateStringArray(const char **strings,int count)\t{int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;}", "label": 1, "label_name": "safe"} -{"code": " public synchronized T setResult(Class resultClass) throws SQLException {\n checkFreed();\n initialize();\n\n if (resultClass == null || DOMResult.class.equals(resultClass)) {\n domResult = new DOMResult();\n active = true;\n return (T) domResult;\n } else if (SAXResult.class.equals(resultClass)) {\n try {\n SAXTransformerFactory transformerFactory =\n (SAXTransformerFactory) SAXTransformerFactory.newInstance();\n TransformerHandler transformerHandler = transformerFactory.newTransformerHandler();\n stringWriter = new StringWriter();\n transformerHandler.setResult(new StreamResult(stringWriter));\n active = true;\n return (T) new SAXResult(transformerHandler);\n } catch (TransformerException te) {\n throw new PSQLException(GT.tr(\"Unable to create SAXResult for SQLXML.\"),\n PSQLState.UNEXPECTED_ERROR, te);\n }\n } else if (StreamResult.class.equals(resultClass)) {\n stringWriter = new StringWriter();\n active = true;\n return (T) new StreamResult(stringWriter);\n } else if (StAXResult.class.equals(resultClass)) {\n stringWriter = new StringWriter();\n try {\n XMLOutputFactory xof = XMLOutputFactory.newInstance();\n XMLStreamWriter xsw = xof.createXMLStreamWriter(stringWriter);\n active = true;\n return (T) new StAXResult(xsw);\n } catch (XMLStreamException xse) {\n throw new PSQLException(GT.tr(\"Unable to create StAXResult for SQLXML\"),\n PSQLState.UNEXPECTED_ERROR, xse);\n }\n }\n\n throw new PSQLException(GT.tr(\"Unknown XML Result class: {0}\", resultClass),\n PSQLState.INVALID_PARAMETER_TYPE);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static int may_create_in_sticky(struct dentry * const dir,\n\t\t\t\tstruct inode * const inode)\n{\n\tif ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||\n\t (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||\n\t likely(!(dir->d_inode->i_mode & S_ISVTX)) ||\n\t uid_eq(inode->i_uid, dir->d_inode->i_uid) ||\n\t uid_eq(current_fsuid(), inode->i_uid))\n\t\treturn 0;\n\n\tif (likely(dir->d_inode->i_mode & 0002) ||\n\t (dir->d_inode->i_mode & 0020 &&\n\t ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||\n\t (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {\n\t\tconst char *operation = S_ISFIFO(inode->i_mode) ?\n\t\t\t\t\t\"sticky_create_fifo\" :\n\t\t\t\t\t\"sticky_create_regular\";\n\t\taudit_log_path_denied(AUDIT_ANOM_CREAT, operation);\n\t\treturn -EACCES;\n\t}\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "if(jQuery)(function(jQuery){jQuery.extend(jQuery.fn,{uploadify:function(options){jQuery(this).each(function(){settings=jQuery.extend({id:jQuery(this).attr('id'),uploader:'uploadify.swf',script:'uploadify.php',expressInstall:null,folder:'',height:30,width:110,cancelImg:'cancel.png',wmode:'opaque',scriptAccess:'sameDomain',fileDataName:'Filedata',method:'POST',queueSizeLimit:999,simUploadLimit:1,queueID:false,displayData:'percentage',onInit:function(){},onSelect:function(){},onQueueFull:function(){},onCheck:function(){},onCancel:function(){},onError:function(){},onProgress:function(){},onComplete:function(){},onAllComplete:function(){}},options);var pagePath=location.pathname;pagePath=pagePath.split('/');pagePath.pop();pagePath=pagePath.join('/')+'/';var data={};data.uploadifyID=settings.id;data.pagepath=pagePath;if(settings.buttonImg)data.buttonImg=escape(settings.buttonImg);if(settings.buttonText)data.buttonText=escape(settings.buttonText);if(settings.rollover)data.rollover=true;data.script=settings.script;data.folder=escape(settings.folder);if(settings.scriptData){var scriptDataString='';for(var name in settings.scriptData){scriptDataString+='&'+name+'='+settings.scriptData[name];}", "label": 0, "label_name": "vulnerable"} -{"code": "var exists = (module.exports.exists = function exists(object, path) {\n if (typeof path === \"string\") {\n path = path.split(\".\");\n }\n\n if (!(path instanceof Array) || path.length === 0) {\n return false;\n }\n\n path = path.slice();\n\n var key = path.shift();\n\n if (typeof object !== \"object\" || object === null) {\n return false;\n }\n\n if (path.length === 0) {\n return Object.hasOwnProperty.apply(object, [key]);\n } else {\n return exists(object[key], path);\n }\n});", "label": 1, "label_name": "safe"} -{"code": "function(K){l=K};this.setAutoScroll=function(K){p=K};this.setOpenFill=function(K){q=K};this.setStopClickEnabled=function(K){A=K};this.setSelectInserted=function(K){B=K};this.setSmoothing=function(K){f=K};this.setPerfectFreehandMode=function(K){O=K};this.setBrushSize=function(K){I.size=K};this.getBrushSize=function(){return I.size};var t=function(K){y=K;b.getRubberband().setEnabled(!K);b.graphHandler.setSelectEnabled(!K);b.graphHandler.setMoveEnabled(!K);b.container.style.cursor=K?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label": 0, "label_name": "vulnerable"} -{"code": "\tstatic function validUTF($string) {\n\t\tif(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {\n\t\t\treturn false;\n\t\t}\t\t\n\t\treturn true;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function makeFixes()\n {\n }", "label": 1, "label_name": "safe"} -{"code": "static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, u32 delta,\n\t\t\t\tu32 curr, const bool probe_pass)\n{\n\tconst s32 off_min = S16_MIN, off_max = S16_MAX;\n\ts32 off = insn->off;\n\n\tif (curr < pos && curr + off + 1 > pos)\n\t\toff += delta;\n\telse if (curr > pos + delta && curr + off + 1 <= pos + delta)\n\t\toff -= delta;\n\tif (off < off_min || off > off_max)\n\t\treturn -ERANGE;\n\tif (!probe_pass)\n\t\tinsn->off = off;\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": " public function isStream()\n {\n if (!is_resource($this->data)) return false;\n if (get_resource_type($this->data) !== 'stream') return false;\n\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "dotraplinkage void do_stack_segment(struct pt_regs *regs, long error_code)\n{\n\tenum ctx_state prev_state;\n\n\tprev_state = exception_enter();\n\tif (notify_die(DIE_TRAP, \"stack segment\", regs, error_code,\n\t\t X86_TRAP_SS, SIGBUS) != NOTIFY_STOP) {\n\t\tpreempt_conditional_sti(regs);\n\t\tdo_trap(X86_TRAP_SS, SIGBUS, \"stack segment\", regs, error_code, NULL);\n\t\tpreempt_conditional_cli(regs);\n\t}\n\texception_exit(prev_state);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tpublic function push($remote = NULL, array $params = NULL)\n\t\t{\n\t\t\t$this->run('push', $remote, $params);\n\t\t\treturn $this;\n\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": " $value = str_replace($originalName, $cleanedName, $value);\n }\n unset($value);\n }\n $result = hash_equals(GeneralUtility::hmac(serialize($fieldChangeFunctions)), $this->parameters['fieldChangeFuncHash']);\n }\n return $result;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function getStringValue(name) {\n\t// Property names must be strings. This means that non-string objects cannot be used\n\t// as keys in an object. Any non-string object, including a number, is typecasted\n\t// into a string via the toString method.\n\t// -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names\n\t//\n\t// So, to ensure that we are checking the same `name` that JavaScript would use, we cast it\n\t// to a string. It's not always possible. If `name` is an object and its `toString` method is\n\t// 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:\n\t//\n\t// TypeError: Cannot convert object to primitive value\n\t//\n\t// For performance reasons, we don't catch this error here and allow it to propagate up the call\n\t// stack. Note that you'll get the same error in JavaScript if you try to access a property using\n\t// such a 'broken' object as a key.\n\treturn name + \"\";\n}", "label": 1, "label_name": "safe"} -{"code": " foreach ($module->info as $name => $v) {\n if (isset($elements[$name])) {\n continue;\n }\n $elements[$name] = $this->getElement($name);\n }", "label": 1, "label_name": "safe"} -{"code": " public function writeStream($path, $resource, Config $config)\n {\n $location = $this->applyPathPrefix($path);\n $this->ensureDirectory(dirname($location));\n $stream = fopen($location, 'w+');\n\n if ( ! $stream) {\n return false;\n }\n\n stream_copy_to_stream($resource, $stream);\n\n if ( ! fclose($stream)) {\n return false;\n }\n\n if ($visibility = $config->get('visibility')) {\n $this->setVisibility($path, $visibility);\n }\n\n return compact('path', 'visibility');\n }", "label": 0, "label_name": "vulnerable"} -{"code": "mxUtils.bind(this,function(){}),null,mxResources.get(\"ok\"),mxUtils.bind(this,function(){this.actions.get(\"import\").funct()}))):this.loadImage(E.target.result,mxUtils.bind(this,function(ba){this.resizeImage(ba,E.target.result,mxUtils.bind(this,function(ea,Z,fa){M(U,mxUtils.bind(this,function(){if(null!=ea&&ea.lengthsk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct hash_ctx *ctx = ask->private;\n\tunsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req));\n\tint err;\n\n\tif (len > ds)\n\t\tlen = ds;\n\telse if (len < ds)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\tmsg->msg_namelen = 0;\n\n\tlock_sock(sk);\n\tif (ctx->more) {\n\t\tctx->more = 0;\n\t\tahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);\n\t\terr = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),\n\t\t\t\t\t\t &ctx->completion);\n\t\tif (err)\n\t\t\tgoto unlock;\n\t}\n\n\terr = memcpy_toiovec(msg->msg_iov, ctx->result, len);\n\nunlock:\n\trelease_sock(sk);\n\n\treturn err ?: len;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def query(database, collection, selector, options = {})\n if consistency == :eventual\n options[:flags] ||= []\n options[:flags] |= [:slave_ok]\n end\n\n with_node do |node|\n node.query(database, collection, selector, options)\n end\n end", "label": 1, "label_name": "safe"} -{"code": " void rejectsObviouslyWrongURL() {\n assertTrue(validating(svn(\"-url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n assertTrue(validating(svn(\"_url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n assertTrue(validating(svn(\"@url-not-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n\n assertFalse(validating(svn(\"url-starting-with-an-alphanumeric-character\", false)).errors().containsKey(SvnMaterialConfig.URL));\n }", "label": 1, "label_name": "safe"} -{"code": "function random_bytes($bytes)\n{\n try {\n $bytes = RandomCompat_intval($bytes);\n } catch (TypeError $ex) {\n throw new TypeError(\n 'random_bytes(): $bytes must be an integer'\n );\n }\n\n if ($bytes < 1) {\n throw new Error(\n 'Length must be greater than 0'\n );\n }\n\n /**\n * \\Sodium\\randombytes_buf() doesn't allow more than 2147483647 bytes to be\n * generated in one invocation.\n */\n if ($bytes > 2147483647) {\n $buf = '';\n for ($i = 0; $i < $bytes; $i += 1073741824) {\n $n = ($bytes - $i) > 1073741824\n ? 1073741824\n : $bytes - $i;\n $buf .= Sodium::randombytes_buf($n);\n }\n } else {\n $buf = Sodium::randombytes_buf($bytes);\n }\n\n if ($buf !== false) {\n if (RandomCompat_strlen($buf) === $bytes) {\n return $buf;\n }\n }\n\n /**\n * If we reach here, PHP has failed us.\n */\n throw new Exception(\n 'Could not gather sufficient random data'\n );\n}", "label": 1, "label_name": "safe"} -{"code": "SSecurityTLS::~SSecurityTLS()\n{\n shutdown();\n\n if (fis)\n delete fis;\n if (fos)\n delete fos;\n\n delete[] keyfile;\n delete[] certfile;\n\n gnutls_global_deinit();\n}", "label": 1, "label_name": "safe"} -{"code": " $contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, 'primary', null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('zones.php', 'page=' . (int)$_GET['page']), null, null, 'btn-light')];", "label": 1, "label_name": "safe"} -{"code": " it \"should raise a ParseError if there are fewer than 2 arguments\" do\n expect { scope.function_delete_values([]) }.to( raise_error(Puppet::ParseError))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public static function type($id) {\r\n $id = sprintf('%d', $id);\r\n if(isset($id)){\r\n $cat = Db::result(\"SELECT `type` FROM `cat` \r\n WHERE `id` = '{$id}' LIMIT 1\");\r\n //print_r($cat);\r\n if(isset($cat['error'])){\r\n return '';\r\n }else{\r\n return $cat[0]->type;\r\n }\r\n \r\n }else{\r\n echo \"No ID Selected\";\r\n }\r\n \r\n //print_r($cat);\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "function _c(a,b,c){var d={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return a+\" \"+cd(d[c],a)}function ad(a){switch(bd(a)){case 1:case 3:case 4:case 5:case 9:return a+\" bloaz\";default:return a+\" vloaz\"}}function bd(a){return a>9?bd(a%10):a}function cd(a,b){return 2===b?dd(a):a}function dd(a){var b={m:\"v\",b:\"v\",d:\"z\"};return void 0===b[a.charAt(0)]?a:b[a.charAt(0)]+a.substring(1)}", "label": 0, "label_name": "vulnerable"} -{"code": "export const showWarningDialog = (message: string): void => {\n const options: MessageBoxSyncOptions = {\n buttons: ['OK'],\n message,\n title: 'Warning',\n type: 'warning',\n };\n dialog.showMessageBoxSync(options);\n};", "label": 1, "label_name": "safe"} -{"code": " public function enable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane = $this->getSwimlane($project);\n\n if ($this->swimlaneModel->enable($project['id'], $swimlane['id'])) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label": 1, "label_name": "safe"} -{"code": " protected function getCategory(array $project)\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n if ($category['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n return $category;\n }", "label": 1, "label_name": "safe"} -{"code": " $this->path = $segments_encoder->encode($this->path);\n } else {\n // path-noscheme (relative)\n // my/path\n // (once again, not checking nz)\n $segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@');\n $c = strpos($this->path, '/');\n if ($c !== false) {\n $this->path =\n $segment_nc_encoder->encode(substr($this->path, 0, $c)) .\n $segments_encoder->encode(substr($this->path, $c));\n } else {\n $this->path = $segment_nc_encoder->encode($this->path);\n }\n }\n } else {", "label": 1, "label_name": "safe"} -{"code": "[\"exportPdf\"],y):d.isOffline()||mxClient.IS_IOS&&navigator.standalone||this.addMenuItems(n,[\"exportPdf\"],y);mxClient.IS_IE||\"undefined\"===typeof VsdxExport&&d.isOffline()||this.addMenuItems(n,[\"exportVsdx\"],y);this.addMenuItems(n,[\"-\",\"exportHtml\",\"exportXml\",\"exportUrl\"],y);d.isOffline()||(n.addSeparator(y),this.addMenuItem(n,\"export\",y).firstChild.nextSibling.innerHTML=mxResources.get(\"advanced\")+\"...\")})));this.put(\"importFrom\",new Menu(mxUtils.bind(this,function(n,y){function K(G){G.pickFile(function(N){d.spinner.spin(document.body,\nmxResources.get(\"loading\"))&&G.getFile(N,function(J){var E=\"data:image/\"==J.getData().substring(0,11)?F(J.getTitle()):\"text/xml\";/\\.svg$/i.test(J.getTitle())&&!d.editor.isDataSvg(J.getData())&&(J.setData(Editor.createSvgDataUri(J.getData())),E=\"image/svg+xml\");B(J.getData(),E,J.getTitle())},function(J){d.handleError(J,null!=J?mxResources.get(\"errorLoadingFile\"):null)},G==d.drive)},!0)}var B=mxUtils.bind(this,function(G,N,J){var E=u.view,H=u.getGraphBounds(),S=u.snap(Math.ceil(Math.max(0,H.x/E.scale-", "label": 0, "label_name": "vulnerable"} -{"code": "void jas_matrix_asl(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 <<= n;\n\t\t\t\t*data = jas_seqent_asl(*data, n);\n\t\t\t}\n\t\t}\n\t}\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testParseHeaders()\n {\n $response = $this->readResponseFromFile('response_headers');\n $this->assertEquals(7, count($response->getHeader()));\n $this->assertEquals('PHP/6.2.2', $response->getHeader('X-POWERED-BY'));\n $this->assertEquals('text/html; charset=windows-1251', $response->getHeader('cOnTeNt-TyPe'));\n $this->assertEquals('accept-charset, user-agent', $response->getHeader('vary'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic boolean loginValidate(String userName, String password, String email) {\n\t\tString sql = \"select * from voter_table where voter_name=? and email=?\";\n\t\ttry {\n\t\t\tps = DbUtil.getConnection().prepareStatement(sql);\n\t\t\tps.setString(1, userName);\n\t\t\tps.setString(2, email);\n\t\t\tResultSet rs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tString cipherText = rs.getString(\"password\");\n\t\t\t\treturn SHA256.validatePassword(password, cipherText);\n\t\t\t}\n\t\t} catch (ClassNotFoundException | SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn false;\n\t}", "label": 1, "label_name": "safe"} -{"code": "function sc_configure($instance)\n{\n $instance->configure();\n}", "label": 0, "label_name": "vulnerable"} -{"code": " explicit GenericDecipher()\n : ctx_(nullptr),\n ctx_hmac_(nullptr),\n hmac_len_(0),\n is_etm_(0) {}", "label": 1, "label_name": "safe"} -{"code": "def update_fence_device(params, request, auth_user)\n if not allowed_for_local_cluster(auth_user, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n\n $logger.info \"Updating fence device\"\n $logger.info params\n param_line = getParamList(params)\n $logger.info param_line\n\n if not params[:resource_id]\n out, stderr, retval = run_cmd(\n auth_user,\n PCS, \"stonith\", \"create\", params[:name], params[:resource_type],\n *param_line\n )\n if retval != 0\n return JSON.generate({\"error\" => \"true\", \"stderr\" => stderr, \"stdout\" => out})\n end\n return \"{}\"\n end\n\n if param_line.length != 0\n out, stderr, retval = run_cmd(\n auth_user, PCS, \"stonith\", \"update\", params[:resource_id], *param_line\n )\n if retval != 0\n return JSON.generate({\"error\" => \"true\", \"stderr\" => stderr, \"stdout\" => out})\n end\n end\n return \"{}\"\nend", "label": 1, "label_name": "safe"} -{"code": " public function __construct($serviceId, array $path, \\Exception $previous = null)\n {\n parent::__construct(sprintf('Circular reference detected for service \"%s\", path: \"%s\".', $serviceId, implode(' -> ', $path)), 0, $previous);\n\n $this->serviceId = $serviceId;\n $this->path = $path;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function(){function O(za,wa,Ea){var Da=U.menus.get(za),La=R.addMenu(mxResources.get(za),mxUtils.bind(this,function(){Da.funct.apply(this,arguments)}),Q);La.className=\"1\"==urlParams.sketch?\"geToolbarButton\":\"geMenuItem\";La.style.display=\"inline-block\";La.style.boxSizing=\"border-box\";La.style.top=\"6px\";La.style.marginRight=\"6px\";La.style.height=\"30px\";La.style.paddingTop=\"6px\";La.style.paddingBottom=\"6px\";La.style.cursor=\"pointer\";La.setAttribute(\"title\",mxResources.get(za));U.menus.menuCreated(Da,\nLa,\"geMenuItem\");null!=Ea?(La.style.backgroundImage=\"url(\"+Ea+\")\",La.style.backgroundPosition=\"center center\",La.style.backgroundRepeat=\"no-repeat\",La.style.backgroundSize=\"24px 24px\",La.style.width=\"34px\",La.innerHTML=\"\"):wa||(La.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\",La.style.backgroundPosition=\"right 6px center\",La.style.backgroundRepeat=\"no-repeat\",La.style.paddingRight=\"22px\");return La}function X(za,wa,Ea,Da,La,Ya){var Ua=document.createElement(\"a\");Ua.className=", "label": 0, "label_name": "vulnerable"} -{"code": " it param[:title] do\n matches = Array(param[:match])\n\n if matches.all? { |m| m.is_a? Regexp }\n matches.each { |item| should contain_concat__fragment(\"#{title}-header\").with_content(item) }\n else\n lines = subject.resource('concat::fragment', \"#{title}-header\").send(:parameters)[:content].split(\"\\n\")\n (lines & Array(param[:match])).should == Array(param[:match])\n end\n Array(param[:notmatch]).each do |item|\n should contain_concat__fragment(\"#{title}-header\").without_content(item)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "def add_meta_attr_remote(params, request, auth_user)\n if not allowed_for_local_cluster(auth_user, Permissions::WRITE)\n return 403, 'Permission denied'\n end\n retval = add_meta_attr(\n auth_user, params[\"res_id\"], params[\"key\"],params[\"value\"]\n )\n if retval == 0\n return [200, \"Successfully added meta attribute\"]\n else\n return [400, \"Error adding meta attribute\"]\n end\nend", "label": 1, "label_name": "safe"} -{"code": " $section = new section($this->params);\n } else {\n notfoundController::handle_not_found();\n exit;\n }\n if (!empty($section->id)) {\n $check_id = $section->id;\n } else {\n $check_id = $section->parent;\n }\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {\n if (empty($section->id)) {\n $section->active = 1;\n $section->public = 1;\n if (!isset($section->parent)) {\n // This is another precaution. The parent attribute\n // should ALWAYS be set by the caller.\n //FJD - if that's the case, then we should die.\n notfoundController::handle_not_authorized();\n exit;\n //$section->parent = 0;\n }\n }\n assign_to_template(array(\n 'section' => $section,\n 'glyphs' => self::get_glyphs(),\n ));\n } else { // User does not have permission to manage sections. Throw a 403\n notfoundController::handle_not_authorized();\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public function prepare($config, $context)\n {\n $this->htmlDefinition = $config->getHTMLDefinition();\n // Even though this might fail, some unit tests ignore this and\n // still test checkNeeded, so be careful. Maybe get rid of that\n // dependency.\n $result = $this->checkNeeded($config);\n if ($result !== false) {\n return $result;\n }\n $this->currentNesting =& $context->get('CurrentNesting');\n $this->currentToken =& $context->get('CurrentToken');\n $this->inputZipper =& $context->get('InputZipper');\n return false;\n }", "label": 1, "label_name": "safe"} -{"code": "function print(s) {\n out.value += s + \"\\n\";\n}", "label": 1, "label_name": "safe"} -{"code": "func (*MatchState) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{32}\n}", "label": 1, "label_name": "safe"} -{"code": " def test_jail_classes_should_have_limited_methods\n expected = [\"new\", \"methods\", \"name\", \"inherited\", \"method_added\", \"inspect\",\n \"allow\", \"allowed?\", \"allowed_methods\", \"init_allowed_methods\",\n \"<\", # < needed in Rails Object#subclasses_of\n \"ancestors\", \"==\" # ancestors and == needed in Rails::Generator::Spec#lookup_class\n ]\n objects.each do |object|\n assert_equal expected.sort, reject_pretty_methods(object.to_jail.class.methods.map(&:to_s).sort)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tsize : function(file1, file2) { \n\t\t\tvar size1 = parseInt(file1.size) || 0,\n\t\t\t\tsize2 = parseInt(file2.size) || 0;\n\t\t\t\t\n\t\t\treturn size1 == size2 ? 0 : size1 > size2 ? 1 : -1;\n\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": "\tmap: function( callback ) {\n\t\treturn this.pushStack( jQuery.map(this, function(elem, i){\n\t\t\treturn callback.call( elem, i, elem );\n\t\t}));\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": "int snmp_helper(void *context, size_t hdrlen, unsigned char tag,\n\t\tconst void *data, size_t datalen)\n{\n\tstruct snmp_ctx *ctx = (struct snmp_ctx *)context;\n\t__be32 *pdata = (__be32 *)data;\n\n\tif (*pdata == ctx->from) {\n\t\tpr_debug(\"%s: %pI4 to %pI4\\n\", __func__,\n\t\t\t (void *)&ctx->from, (void *)&ctx->to);\n\n\t\tif (*ctx->check)\n\t\t\tfast_csum(ctx, (unsigned char *)data - ctx->begin);\n\t\t*pdata = ctx->to;\n\t}\n\n\treturn 1;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testShouldCatchExceptionsWhenReloadingAndNoCacheRequest()\n {\n $this->catchExceptions();\n\n $this->setNextResponse();\n $this->cacheConfig['allow_reload'] = true;\n $this->request('GET', '/', array(), array(), false, array('Pragma' => 'no-cache'));\n\n $this->assertExceptionsAreCaught();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function update_license_status() {\n $status = '';\n $license_key = $this->get_license_key();\n\n if (!empty($license_key) || defined('W3TC_LICENSE_CHECK')) {\n $license = edd_w3edge_w3tc_check_license($license_key, W3TC_VERSION);\n $version = '';\n\n if ($license) {\n $status = $license->license;\n if ('host_valid' == $status) {\n $version = 'pro';\n } elseif (in_array($status, array('site_inactive','valid')) && w3tc_is_pro_dev_mode()) {\n $status = 'valid';\n $version = 'pro_dev';\n }\n }\n\n $this->_config->set('plugin.type', $version);\n } else {\n $status = 'no_key';\n $this->_config->set('plugin.type', '');\n }\n try {\n $this->_config->save();\n } catch(Exception $ex) {}\n return $status;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)\n{\n\tswitch (mem->type) {\n\tcase RXE_MEM_TYPE_DMA:\n\t\treturn 0;\n\n\tcase RXE_MEM_TYPE_MR:\n\tcase RXE_MEM_TYPE_FMR:\n\t\treturn ((iova < mem->iova) ||\n\t\t\t((iova + length) > (mem->iova + mem->length))) ?\n\t\t\t-EFAULT : 0;\n\n\tdefault:\n\t\treturn -EFAULT;\n\t}\n}", "label": 0, "label_name": "vulnerable"} -{"code": "blkcpy(void * dest, void * src, size_t len)\n{\n __m128i * D = (__m128i *) dest;\n __m128i * S = (__m128i *) src;\n size_t L = len / 16;\n size_t i;\n\n for (i = 0; i < L; i++)\n D[i] = S[i];\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function(){if(null!=this.marker&&(bb.apply(this),null!=this.state&&null!=this.linkHint)){var z=this.state;null!=this.state.text&&null!=this.state.text.bounds&&(z=new mxRectangle(z.x,z.y,z.width,z.height),z.add(this.state.text.bounds));this.linkHint.style.left=Math.max(0,Math.round(z.x+(z.width-this.linkHint.clientWidth)/2))+\"px\";this.linkHint.style.top=Math.round(z.y+z.height+Editor.hintOffset)+\"px\"}};var Pa=mxEdgeHandler.prototype.reset;mxEdgeHandler.prototype.reset=function(){Pa.apply(this,arguments);\nnull!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label": 0, "label_name": "vulnerable"} -{"code": " function calculateType()\n {\n if ($this->data === true || $this->data === false) {\n return 'boolean';\n }\n if (is_integer($this->data)) {\n return 'int';\n }\n if (is_double($this->data)) {\n return 'double';\n }\n\n // Deal with IXR object types base64 and date\n if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {\n return 'date';\n }\n if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {\n return 'base64';\n }\n\n // If it is a normal PHP object convert it in to a struct\n if (is_object($this->data)) {\n $this->data = get_object_vars($this->data);\n return 'struct';\n }\n if (!is_array($this->data)) {\n return 'string';\n }\n\n // We have an array - is it an array or a struct?\n if ($this->isStruct($this->data)) {\n return 'struct';\n } else {\n return 'array';\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "this.addMenuItems(O,[\"-\",\"lockUnlock\"],null,ea)};var H=Menus.prototype.addPopupMenuEditItems;Menus.prototype.addPopupMenuEditItems=function(O,X,ea){H.apply(this,arguments);this.editorUi.editor.graph.isSelectionEmpty()&&this.addMenuItems(O,[\"copyAsImage\"],null,ea)};EditorUi.prototype.toggleFormatPanel=function(O){null!=this.formatWindow?this.formatWindow.window.setVisible(null!=O?O:!this.formatWindow.window.isVisible()):b(this)};DiagramFormatPanel.prototype.isMathOptionVisible=function(){return!0};", "label": 1, "label_name": "safe"} -{"code": "mcs_parse_domain_params(STREAM s)\n{\n\tuint32 length;\n\tstruct stream packet = *s;\n\n\tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n\n\tif (!s_check_rem(s, length))\n\t{\n\t\trdp_protocol_error(\"mcs_parse_domain_params(), consume domain params from stream would overrun\", &packet);\n\t}\n\n\tin_uint8s(s, length);\n\n\treturn s_check(s);\n}", "label": 1, "label_name": "safe"} -{"code": " public function testMalformedTag()\n {\n $this->assertParsing(\n 'http://www.example.com/>',\n 'http', null, 'www.example.com', null, '/', null, null\n );\n }", "label": 1, "label_name": "safe"} -{"code": " def get_group_users\n Log.add_info(request, params.inspect)\n\n @group_id = nil\n if !params[:thetisBoxSelKeeper].nil?\n @group_id = params[:thetisBoxSelKeeper].split(':').last\n elsif !params[:group_id].nil? and !params[:group_id].empty?\n @group_id = params[:group_id]\n end\n\n submit_url = url_for(:controller => 'desktop', :action => 'get_group_users')\n render(:partial => 'common/select_users', :layout => false, :locals => {:target_attr => :id, :submit_url => submit_url})\n end", "label": 0, "label_name": "vulnerable"} -{"code": "With(asdl_seq * items, asdl_seq * body, int lineno, int col_offset, int\n end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = With_kind;\n p->v.With.items = items;\n p->v.With.body = body;\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, "label_name": "vulnerable"} -{"code": "function db_properties($table)\n{\n global $DatabaseType, $DatabaseUsername;\n\n switch ($DatabaseType) {\n case 'mysqli':\n $result = DBQuery(\"SHOW COLUMNS FROM $table\");\n while ($row = db_fetch_row($result)) {\n $properties[strtoupper($row['FIELD'])]['TYPE'] = strtoupper($row['TYPE'], strpos($row['TYPE'], '('));\n if (!$pos = strpos($row['TYPE'], ','))\n $pos = strpos($row['TYPE'], ')');\n else\n $properties[strtoupper($row['FIELD'])]['SCALE'] = substr($row['TYPE'], $pos + 1);\n\n $properties[strtoupper($row['FIELD'])]['SIZE'] = substr($row['TYPE'], strpos($row['TYPE'], '(') + 1, $pos);\n\n if ($row['NULL'] != '')\n $properties[strtoupper($row['FIELD'])]['NULL'] = \"Y\";\n else\n $properties[strtoupper($row['FIELD'])]['NULL'] = \"N\";\n }\n break;\n }\n return $properties;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"stores the list of seeds\" do\n cluster.seeds.should eq [\"127.0.0.1:27017\", \"127.0.0.1:27018\"]\n end", "label": 0, "label_name": "vulnerable"} -{"code": "l,x,p,v){l=Math.min(p,v/2);c.moveTo(0,0);c.lineTo(p-l,0);c.quadTo(p,0,p,v/2);c.quadTo(p,v,p-l,v);c.lineTo(0,v);c.close();c.end()};mxCellRenderer.registerShape(\"delay\",Ta);mxUtils.extend(za,mxActor);za.prototype.size=.2;za.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(v,p);var A=Math.max(0,Math.min(l,l*parseFloat(mxUtils.getValue(this.style,\"size\",this.size))));l=(v-A)/2;x=l+A;var B=(p-A)/2;A=B+A;c.moveTo(0,l);c.lineTo(B,l);c.lineTo(B,0);c.lineTo(A,0);c.lineTo(A,l);c.lineTo(p,l);c.lineTo(p,x);\nc.lineTo(A,x);c.lineTo(A,v);c.lineTo(B,v);c.lineTo(B,x);c.lineTo(0,x);c.close();c.end()};mxCellRenderer.registerShape(\"cross\",za);mxUtils.extend(wa,mxActor);wa.prototype.size=.25;wa.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(p,v/2);x=Math.min(p-l,Math.max(0,parseFloat(mxUtils.getValue(this.style,\"size\",this.size)))*p);c.moveTo(0,v/2);c.lineTo(x,0);c.lineTo(p-l,0);c.quadTo(p,0,p,v/2);c.quadTo(p,v,p-l,v);c.lineTo(x,v);c.close();c.end()};mxCellRenderer.registerShape(\"display\",wa);mxUtils.extend(Ea,", "label": 0, "label_name": "vulnerable"} -{"code": " def file_containing(name, contents) PuppetSpec::Files.file_containing(name, contents) end", "label": 0, "label_name": "vulnerable"} -{"code": " on(eventName: \"chunk\", eventHandler: (messageChunk: Buffer) => void): this;", "label": 1, "label_name": "safe"} -{"code": "l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat)\n{\n\tconst uint32_t *ptr = (const uint32_t *)dat;\n\n\tif (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) {\n\t\tND_PRINT((ndo, \"A\"));\n\t}\n\tif (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) {\n\t\tND_PRINT((ndo, \"D\"));\n\t}\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public String readStringBody(int size) throws TException {\n ensureContainerHasEnough(size, TType.BYTE);\n checkReadLength(size);\n byte[] buf = new byte[size];\n trans_.readAll(buf, 0, size);\n return new String(buf, StandardCharsets.UTF_8);\n }", "label": 1, "label_name": "safe"} -{"code": " def _get_default_cache_dir(self):\n tmpdir = tempfile.gettempdir()\n\n # On windows the temporary directory is used specific unless\n # explicitly forced otherwise. We can just use that.\n if os.name == 'n':\n return tmpdir\n if not hasattr(os, 'getuid'):\n raise RuntimeError('Cannot determine safe temp directory. You '\n 'need to explicitly provide one.')\n\n dirname = '_jinja2-cache-%d' % os.getuid()\n actual_dir = os.path.join(tmpdir, dirname)\n try:\n os.mkdir(actual_dir, 0700)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n return actual_dir", "label": 1, "label_name": "safe"} -{"code": " it 'should not pass --defaults-extra-file if $root_home/.my.cnf is absent' do\n File.stubs(:file?).with(\"#{root_home}/.my.cnf\").returns(false)\n provider_class.expects(:mysql).with(['mysql', '-NBe', \"SELECT '1' FROM user WHERE user='user' AND host='host'\"]).returns \"1\\n\"\n provider_class.expects(:mysql).with(['mysql', '-Be', \"update user set Select_priv = 'Y', Insert_priv = 'N', Update_priv = 'Y' where user='user' and host='host'\"])\n provider_class.expects(:mysqladmin).with(%w(flush-privileges))\n @provider.privileges=(%w(Select_priv Update_priv))\n end", "label": 0, "label_name": "vulnerable"} -{"code": "TEST_F(HeaderTableTests, reduce_capacity) {\n HPACKHeader accept(\"accept-encoding\", \"gzip\");\n uint32_t max = 10;\n uint32_t capacity = accept.bytes() * max;\n HeaderTable table(capacity);\n EXPECT_GT(table.length(), max);\n\n // fill the table\n for (size_t i = 0; i < max; i++) {\n EXPECT_EQ(table.add(accept), true);\n }\n // change capacity\n table.setCapacity(capacity / 2);\n EXPECT_EQ(table.size(), max / 2);\n EXPECT_EQ(table.bytes(), capacity / 2);\n}", "label": 1, "label_name": "safe"} -{"code": "eb);this.updateSvgLinks(Da,ua,!0);this.addForeignObjectWarning(eb,Da);return Da}finally{Pa&&(this.useCssTransforms=!0,this.view.revalidate(),this.sizeDidChange())}};Graph.prototype.addForeignObjectWarning=function(z,L){if(\"0\"!=urlParams[\"svg-warning\"]&&0' + text + '';\n};", "label": 1, "label_name": "safe"} -{"code": "exports.escapeRegexp = function(str){\n return str.replace(/[-\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n};", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic static String compileMustache(Map context, String template) {\n\t\treturn compileMustache(context, template, false);\n\t}", "label": 1, "label_name": "safe"} -{"code": "\tthis.hide = function() {\n\t\tthis.disable().trigger('hide');\n\t\tnode.hide();\n\t};", "label": 1, "label_name": "safe"} -{"code": " public function testMake()\n {\n $l = HTMLPurifier_Length::make('+23.4in');\n $this->assertIdentical($l->getN(), '+23.4');\n $this->assertIdentical($l->getUnit(), 'in');\n }", "label": 1, "label_name": "safe"} -{"code": "static int netlbl_cipsov4_add_common(struct genl_info *info,\n\t\t\t\t struct cipso_v4_doi *doi_def)\n{\n\tstruct nlattr *nla;\n\tint nla_rem;\n\tu32 iter = 0;\n\n\tdoi_def->doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);\n\n\tif (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_TAGLST],\n\t\t\t\tNLBL_CIPSOV4_A_MAX,\n\t\t\t\tnetlbl_cipsov4_genl_policy) != 0)\n\t\treturn -EINVAL;\n\n\tnla_for_each_nested(nla, info->attrs[NLBL_CIPSOV4_A_TAGLST], nla_rem)\n\t\tif (nla->nla_type == NLBL_CIPSOV4_A_TAG) {\n\t\t\tif (iter >= CIPSO_V4_TAG_MAXCNT)\n\t\t\t\treturn -EINVAL;\n\t\t\tdoi_def->tags[iter++] = nla_get_u8(nla);\n\t\t}\n\twhile (iter < CIPSO_V4_TAG_MAXCNT)\n\t\tdoi_def->tags[iter++] = CIPSO_V4_TAG_INVALID;\n\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": "$.fn.elfinderpanel = function(fm) {\n\t\n\treturn this.each(function() {\n\t\tvar panel = $(this).addClass('elfinder-panel ui-state-default ui-corner-all'),\n\t\t\tmargin = 'margin-'+(fm.direction == 'ltr' ? 'left' : 'right');\n\t\t\n\t\tfm.one('load', function(e) {\n\t\t\tvar navbar = fm.getUI('navbar');\n\t\t\t\n\t\t\tpanel.css(margin, parseInt(navbar.outerWidth(true)));\n\t\t\tnavbar.bind('resize', function() {\n\t\t\t\tpanel.is(':visible') && panel.css(margin, parseInt(navbar.outerWidth(true)))\n\t\t\t})\n\t\t})\n\t})\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testCaptionConvertAlignRight()\n {\n $this->assertResult(\n '',\n ''\n );\n }", "label": 1, "label_name": "safe"} -{"code": " public function execute($image)\n {\n $angle = $this->argument(0)->type('numeric')->required()->value();\n $color = $this->argument(1)->value();\n $color = new Color($color);\n\n // rotate image\n $image->getCore()->rotateImage($color->getPixel(), ($angle * -1));\n\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " template({ labelInfo, labelHead, iconSync, iconAdd, pfx, ppfx }: any) {\n return `\n
\n
${labelHead}
\n
\n \n
\n \n \n \n
\n
\n
\n
\n
\n
\n
\n
\n
\n \n \n ${iconAdd}\n \n \n ${iconSync}\n \n
\n
\n
${labelInfo}:
\n
\n
`;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"includes the command that generated the error\" do\n error.message.should include command.inspect\n end", "label": 0, "label_name": "vulnerable"} -{"code": " protected function _findUnused($hash)\n {\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, "label_name": "safe"} -{"code": " public function testWarmupDoesCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsEnabled()\n {\n $warmer = $this->getCacheWarmerMock();\n $warmer\n ->expects($this->never())\n ->method('isOptional');\n $warmer\n ->expects($this->once())\n ->method('warmUp');\n\n $aggregate = new CacheWarmerAggregate(array($warmer));\n $aggregate->enableOptionalWarmers();\n $aggregate->warmUp(self::$cacheDir);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "var StorageDialog=function(b,f,l){function d(m,q,v,x,A,z){function L(){mxEvent.addListener(M,\"click\",null!=z?z:function(){v!=App.MODE_GOOGLE||b.isDriveDomain()?v==App.MODE_GOOGLE&&b.spinner.spin(document.body,mxResources.get(\"authorizing\"))?b.drive.checkToken(mxUtils.bind(this,function(){b.spinner.stop();b.setMode(v,!0);f()})):v==App.MODE_ONEDRIVE&&b.spinner.spin(document.body,mxResources.get(\"authorizing\"))?b.oneDrive.checkToken(mxUtils.bind(this,function(){b.spinner.stop();b.setMode(v,!0);f()})):\n(b.setMode(v,!0),f()):window.location.hostname=DriveClient.prototype.newAppHostname})}c++;++D>l&&(mxUtils.br(e),D=1);var M=document.createElement(\"a\");M.style.overflow=\"hidden\";M.style.display=\"inline-block\";M.className=\"geBaseButton\";M.style.boxSizing=\"border-box\";M.style.fontSize=\"11px\";M.style.position=\"relative\";M.style.margin=\"4px\";M.style.marginTop=\"8px\";M.style.marginBottom=\"0px\";M.style.padding=\"8px 10px 8px 10px\";M.style.width=\"88px\";M.style.height=\"100px\";M.style.whiteSpace=\"nowrap\";M.setAttribute(\"title\",", "label": 0, "label_name": "vulnerable"} -{"code": "DriveComment.prototype.deleteComment=function(b,e){this.file.ui.drive.executeRequest(this.pCommentId?{url:\"/files/\"+this.file.getId()+\"/comments/\"+this.pCommentId+\"/replies/\"+this.id,method:\"DELETE\"}:{url:\"/files/\"+this.file.getId()+\"/comments/\"+this.id,method:\"DELETE\"},b,e)};function mxODPicker(b,e,f,c,m,n,v,d,g,k,l,p,q,x){function y(N,Q){Q=Q||document;return Q.querySelector(N)}function A(N,Q,R){if(null==N[\"@microsoft.graph.downloadUrl\"])if(null==N.parentReference)R();else{c(N.id,N.parentReference.driveId,function(ea){A(ea,Q,R)},R);return}var Y=new XMLHttpRequest;Y.open(\"GET\",N[\"@microsoft.graph.downloadUrl\"]);var ba=N.file?\"image/png\"==N.file.mimeType:!1;Y.onreadystatechange=function(){if(4==this.readyState){if(200<=this.status&&299>=this.status)try{var ea=Y.responseText;\nba&&(ea=\"data:image/png;base64,\"+Editor.base64Encode(ea),ea=Editor.extractGraphModelFromPng(ea));var Z=mxUtils.parseXml(ea),fa=\"mxlibrary\"==Z.documentElement.nodeName?Z.documentElement:Editor.extractGraphModel(Z.documentElement);if(null!=fa){Q(fa.ownerDocument);return}}catch(aa){}R()}};ba&&Y.overrideMimeType&&Y.overrideMimeType(\"text/plain; charset=x-user-defined\");Y.send()}function B(){p&&null!=F?K.exportToCanvas(function(N){N=EditorUi.prototype.createImageDataUri(N,null,\"png\");v(H,N);n(H)},400,", "label": 0, "label_name": "vulnerable"} -{"code": " $cols .= '\\'' . Util::sqlAddSlashes($col_select) . '\\',';\n }\n $cols = trim($cols, ',');\n $has_list = PMA_findExistingColNames($db, $cols);\n foreach ($field_select as $column) {\n if (!in_array($column, $has_list)) {\n $colNotExist[] = \"'\" . $column . \"'\";\n }\n }\n }\n if (!empty($colNotExist)) {\n $colNotExist = implode(\",\", array_unique($colNotExist));\n $message = Message::notice(\n sprintf(\n __(\n 'Couldn\\'t remove Column(s) %1$s '\n . 'as they don\\'t exist in central columns list!'\n ), htmlspecialchars($colNotExist)\n )\n );\n }\n $GLOBALS['dbi']->selectDb($pmadb, $GLOBALS['controllink']);\n\n $query = 'DELETE FROM ' . Util::backquote($central_list_table) . ' '\n . 'WHERE db_name = \\'' . Util::sqlAddSlashes($db) . '\\' AND col_name IN (' . $cols . ');';\n\n if (!$GLOBALS['dbi']->tryQuery($query, $GLOBALS['controllink'])) {\n $message = Message::error(__('Could not remove columns!'));\n $message->addMessage('
' . htmlspecialchars($cols) . '
');\n $message->addMessage(\n Message::rawError(\n $GLOBALS['dbi']->getError($GLOBALS['controllink'])\n )\n );\n }\n return $message;\n}", "label": 1, "label_name": "safe"} -{"code": " public function testMoveToRaisesExceptionWhenErrorStatusPresent($status)\n {\n $uploadedFile = new UploadedFile('not ok', 0, $status);\n $this->setExpectedException('RuntimeException', 'upload error');\n $uploadedFile->moveTo(__DIR__ . '/' . uniqid());\n }", "label": 1, "label_name": "safe"} -{"code": " function RandomCompat_substr($binary_string, $start, $length = null)\n {\n if (!is_string($binary_string)) {\n throw new TypeError(\n 'RandomCompat_substr(): First argument should be a string'\n );\n }\n\n if (!is_int($start)) {\n throw new TypeError(\n 'RandomCompat_substr(): Second argument should be an integer'\n );\n }\n\n if ($length !== null) {\n if (!is_int($length)) {\n throw new TypeError(\n 'RandomCompat_substr(): Third argument should be an integer, or omitted'\n );\n }\n\n return substr($binary_string, $start, $length);\n }\n\n return substr($binary_string, $start);\n }", "label": 1, "label_name": "safe"} -{"code": " def simple_query(query)\n query = query.dup\n query.limit = -1\n\n execute(query).documents.first\n end", "label": 0, "label_name": "vulnerable"} -{"code": "TfLiteStatus Prepare(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;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* begin;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBeginTensor, &begin));\n const TfLiteTensor* size;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kSizeTensor, &size));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n // Ensure validity of input tensor and its dimension.\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n TF_LITE_ENSURE(context,\n begin->type == kTfLiteInt32 || begin->type == kTfLiteInt64);\n TF_LITE_ENSURE(context,\n size->type == kTfLiteInt32 || size->type == kTfLiteInt64);\n TF_LITE_ENSURE_EQ(context, NumDimensions(begin), 1);\n TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1);\n TF_LITE_ENSURE_EQ(context, NumElements(begin), NumElements(size));\n TF_LITE_ENSURE_MSG(context, NumDimensions(input) <= kMaxDim,\n \"Slice op only supports 1D-4D input arrays.\");\n\n // Postpone allocation of output if any of the indexing tensors is not\n // constant\n if (!(IsConstantTensor(begin) && IsConstantTensor(size))) {\n SetTensorToDynamic(output);\n return kTfLiteOk;\n }\n\n return ResizeOutputShape(context, input, begin, size, output);\n}", "label": 1, "label_name": "safe"} -{"code": "void RegKey::setBinary(const TCHAR* valname, const void* value, int length) const {\n LONG result = RegSetValueEx(key, valname, 0, REG_BINARY, (const BYTE*)value, length);\n if (result != ERROR_SUCCESS) throw rdr::SystemException(\"setBinary\", result);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {\n\n\t// Logic based on response type or status\n\tif noBodyExpected(requestMethod) {\n\t\treturn 0, nil\n\t}\n\tif status/100 == 1 {\n\t\treturn 0, nil\n\t}\n\tswitch status {\n\tcase 204, 304:\n\t\treturn 0, nil\n\t}\n\n\t// Logic based on Transfer-Encoding\n\tif chunked(te) {\n\t\treturn -1, nil\n\t}\n\n\t// Logic based on Content-Length\n\tcl := strings.TrimSpace(header.get(\"Content-Length\"))\n\tif cl != \"\" {\n\t\tn, err := parseContentLength(cl)\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t}\n\t\treturn n, nil\n\t} else {\n\t\theader.Del(\"Content-Length\")\n\t}\n\n\tif !isResponse && requestMethod == \"GET\" {\n\t\t// RFC 2616 doesn't explicitly permit nor forbid an\n\t\t// entity-body on a GET request so we permit one if\n\t\t// declared, but we default to 0 here (not -1 below)\n\t\t// if there's no mention of a body.\n\t\treturn 0, nil\n\t}\n\n\t// Body-EOF logic based on other methods (like closing, or chunked coding)\n\treturn -1, nil\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_AllowedAttributes_global_verboseSyntax()\n {\n $this->config->set('HTML.AllowedElements', array('p', 'br'));\n $this->config->set('HTML.AllowedAttributes', '*@style');\n $this->assertPurification_AllowedAttributes_global_style();\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "\tprotected function filter($files) {\n\t\t$exists = array();\n\t\tforeach ($files as $i => $file) {\n\t\t\tif (isset($exists[$file['hash']]) || !empty($file['hidden']) || !$this->default->mimeAccepted($file['mime'])) {\n\t\t\t\tunset($files[$i]);\n\t\t\t}\n\t\t\t$exists[$file['hash']] = true;\n\t\t}\n\t\treturn array_values($files);\n\t}", "label": 1, "label_name": "safe"} -{"code": " public static function returnChildrenAsJSON() {\n global $db;\n\n //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));\n $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;\n $nav = $db->selectObjects('section', 'parent=' . $id, 'rank');\n //FIXME $manage_all is moot w/ cascading perms now?\n $manage_all = false;\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {\n $manage_all = true;\n }\n //FIXME recode to use foreach $key=>$value\n $navcount = count($nav);\n for ($i = 0; $i < $navcount; $i++) {\n if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {\n $nav[$i]->manage = 1;\n $view = true;\n } else {\n $nav[$i]->manage = 0;\n $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));\n }\n $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);\n if (!$view) unset($nav[$i]);\n }\n $nav= array_values($nav);\n// $nav[$navcount - 1]->last = true;\n if (count($nav)) $nav[count($nav) - 1]->last = true;\n// echo expJavascript::ajaxReply(201, '', $nav);\n $ar = new expAjaxReply(201, '', $nav);\n $ar->send();\n }", "label": 1, "label_name": "safe"} -{"code": "export function getProfileFromDeeplink(args): string | undefined {\n // check if we are passed a profile in the SSO callback url\n const deeplinkUrl = args.find(arg => arg.startsWith(PROTOCOL + '//'));\n if (deeplinkUrl && deeplinkUrl.includes(SEARCH_PARAM)) {\n const parsedUrl = new URL(deeplinkUrl);\n if (parsedUrl.protocol === PROTOCOL) {\n const ssoID = parsedUrl.searchParams.get(SEARCH_PARAM);\n const store = readStore();\n console.log(\"Forwarding to profile: \", store[ssoID]);\n return store[ssoID];\n }\n }\n}", "label": 1, "label_name": "safe"} -{"code": " def read_config(self, config, **kwargs):\n self.recaptcha_private_key = config.get(\"recaptcha_private_key\")\n self.recaptcha_public_key = config.get(\"recaptcha_public_key\")\n self.enable_registration_captcha = config.get(\n \"enable_registration_captcha\", False\n )\n self.recaptcha_siteverify_api = config.get(\n \"recaptcha_siteverify_api\",\n \"https://www.recaptcha.net/recaptcha/api/siteverify\",\n )\n self.recaptcha_template = self.read_template(\"recaptcha.html\")", "label": 1, "label_name": "safe"} -{"code": " it \"runs the command on the current database\" do\n session.with(database: \"moped_test_2\") do |session|\n session.command(dbStats: 1)[\"db\"].should eq \"moped_test_2\"\n end\n end", "label": 1, "label_name": "safe"} -{"code": "function(){function O(ua,ya,Na){var Fa=U.menus.get(ua),Ra=R.addMenu(mxResources.get(ua),mxUtils.bind(this,function(){Fa.funct.apply(this,arguments)}),P);Ra.className=\"1\"==urlParams.sketch?\"geToolbarButton\":\"geMenuItem\";Ra.style.display=\"inline-block\";Ra.style.boxSizing=\"border-box\";Ra.style.top=\"6px\";Ra.style.marginRight=\"6px\";Ra.style.height=\"30px\";Ra.style.paddingTop=\"6px\";Ra.style.paddingBottom=\"6px\";Ra.style.cursor=\"pointer\";Ra.setAttribute(\"title\",mxResources.get(ua));U.menus.menuCreated(Fa,\nRa,\"geMenuItem\");null!=Na?(Ra.style.backgroundImage=\"url(\"+Na+\")\",Ra.style.backgroundPosition=\"center center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.backgroundSize=\"24px 24px\",Ra.style.width=\"34px\",Ra.innerText=\"\"):ya||(Ra.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\",Ra.style.backgroundPosition=\"right 6px center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.paddingRight=\"22px\");return Ra}function X(ua,ya,Na,Fa,Ra,db){var Va=document.createElement(\"a\");Va.className=", "label": 1, "label_name": "safe"} -{"code": "function generate(target, hierarchies, forceOverride) {\n let current = target;\n hierarchies.forEach(info => {\n const descriptor = normalizeDescriptor(info);\n const { value, type, create, override, created, skipped, got } = descriptor;\n const name = getNonEmptyPropName(current, descriptor);\n if (forceOverride ||\n override ||\n !current[name] ||\n typeof current[name] !== 'object' ||\n (name === propProto && current[name] === Object.prototype)) {\n const obj = value ? value :\n type ? new type() :\n create ? create.call(current, current, name) :\n {};\n current[name] = obj;\n if (created) {\n created.call(current, current, name, obj);\n }\n }\n else {\n if (skipped) {\n skipped.call(current, current, name, current[name]);\n }\n }\n const parent = current;\n current = current[name];\n if (got) {\n got.call(parent, parent, name, current);\n }\n });\n return current;\n}", "label": 1, "label_name": "safe"} -{"code": "_PyObject_Calloc(void *ctx, size_t nelem, size_t elsize)\n{\n return _PyObject_Alloc(1, ctx, nelem, elsize);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " function update() {\r\n parent::update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct() {\n global $GLOBALS, $data;\n self::$editors =& $GLOBALS;\n self::$data =& $data;\n self::$url = Options::get('siteurl');\n self::$domain = Options::get('sitedomain');\n self::$name = Options::get('sitename');\n self::$key = Options::get('sitekeywords');\n self::$desc = Options::get('sitedesc');\n }", "label": 1, "label_name": "safe"} -{"code": " def test_check_safe_path(self):\n ret = disk_api._join_and_check_path_within_fs('/foo', 'etc',\n 'something.conf')\n self.assertEquals(ret, '/foo/etc/something.conf')", "label": 1, "label_name": "safe"} -{"code": "mcs_parse_domain_params(STREAM s)\n{\n\tuint32 length;\n\tstruct stream packet = *s;\n\n\tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n\n\tif (!s_check_rem(s, length))\n\t{\n\t\trdp_protocol_error(\"mcs_parse_domain_params(), consume domain params from stream would overrun\", &packet);\n\t}\n\n\tin_uint8s(s, length);\n\n\treturn s_check(s);\n}", "label": 1, "label_name": "safe"} -{"code": "static inline int xsave_state_booting(struct xsave_struct *fx, u64 mask)\n{\n\tu32 lmask = mask;\n\tu32 hmask = mask >> 32;\n\tint err = 0;\n\n\tWARN_ON(system_state != SYSTEM_BOOTING);\n\n\tif (boot_cpu_has(X86_FEATURE_XSAVES))\n\t\tasm volatile(\"1:\"XSAVES\"\\n\\t\"\n\t\t\t\"2:\\n\\t\"\n\t\t\t: : \"D\" (fx), \"m\" (*fx), \"a\" (lmask), \"d\" (hmask)\n\t\t\t: \"memory\");\n\telse\n\t\tasm volatile(\"1:\"XSAVE\"\\n\\t\"\n\t\t\t\"2:\\n\\t\"\n\t\t\t: : \"D\" (fx), \"m\" (*fx), \"a\" (lmask), \"d\" (hmask)\n\t\t\t: \"memory\");\n\n\tasm volatile(xstate_fault\n\t\t : \"0\" (0)\n\t\t : \"memory\");\n\n\treturn err;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " constructor(connection, {root, cwd} = {}) {\n this.connection = connection;\n this.cwd = nodePath.normalize((cwd || '/').replace(WIN_SEP_REGEX, '/'));\n this._root = nodePath.resolve(root || process.cwd());\n }", "label": 1, "label_name": "safe"} -{"code": " $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important);\n }\n\n $this->setupConfigStuff($config);\n }", "label": 1, "label_name": "safe"} -{"code": " public function serialize()\n {\n $cookies = $this->getAll();\n if (!$this->serializeSession) {\n for ($i = count($cookies) - 1; $i >= 0; $i--) {\n if (empty($cookies[$i]['expires'])) {\n unset($cookies[$i]);\n }\n }\n }\n return serialize(array(\n 'cookies' => $cookies,\n 'serializeSession' => $this->serializeSession,\n 'useList' => $this->useList,\n 'ignoreInvalid' => $this->ignoreInvalid\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "SYSCALL_DEFINE3(osf_sysinfo, int, command, char __user *, buf, long, count)\n{\n\tconst char *sysinfo_table[] = {\n\t\tutsname()->sysname,\n\t\tutsname()->nodename,\n\t\tutsname()->release,\n\t\tutsname()->version,\n\t\tutsname()->machine,\n\t\t\"alpha\",\t/* instruction set architecture */\n\t\t\"dummy\",\t/* hardware serial number */\n\t\t\"dummy\",\t/* hardware manufacturer */\n\t\t\"dummy\",\t/* secure RPC domain */\n\t};\n\tunsigned long offset;\n\tconst char *res;\n\tlong len, err = -EINVAL;\n\n\toffset = command-1;\n\tif (offset >= ARRAY_SIZE(sysinfo_table)) {\n\t\t/* Digital UNIX has a few unpublished interfaces here */\n\t\tprintk(\"sysinfo(%d)\", command);\n\t\tgoto out;\n\t}\n\n\tdown_read(&uts_sem);\n\tres = sysinfo_table[offset];\n\tlen = strlen(res)+1;\n\tif (len > count)\n\t\tlen = count;\n\tif (copy_to_user(buf, res, len))\n\t\terr = -EFAULT;\n\telse\n\t\terr = 0;\n\tup_read(&uts_sem);\n out:\n\treturn err;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def delete_args\n # Split into arguments\n line = properties[:line].gsub(/\\-A/, '-D').split(/\\s(?=(?:[^\"]|\"[^\"]*\")*$)/).map{|v| v.gsub(/\"/, '')}\n line.unshift(\"-t\", properties[:table])\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def update(database, collection, selector, change, options = {})\n process Protocol::Update.new(database, collection, selector, change, options)\n end", "label": 1, "label_name": "safe"} -{"code": " where: this.sequelize.json(\"data.id')) AS DECIMAL) = 1 DELETE YOLO INJECTIONS; -- \", '1')\n });\n });", "label": 1, "label_name": "safe"} -{"code": " it \"raises a connection failure exception\" do\n cluster.sync_server(server).should be_empty\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def render_POST(self, request):\n \"\"\"\n Register with the Identity Server\n \"\"\"\n send_cors(request)\n\n args = get_args(request, ('matrix_server_name', 'access_token'))\n\n result = yield self.client.get_json(\n \"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s\" % (\n args['matrix_server_name'], urllib.parse.quote(args['access_token']),\n ),\n 1024 * 5,\n )\n if 'sub' not in result:\n raise Exception(\"Invalid response from homeserver\")\n\n user_id = result['sub']\n tok = yield issueToken(self.sydent, user_id)\n\n # XXX: `token` is correct for the spec, but we released with `access_token`\n # for a substantial amount of time. Serve both to make spec-compliant clients\n # happy.\n defer.returnValue({\n \"access_token\": tok,\n \"token\": tok,\n })", "label": 0, "label_name": "vulnerable"} -{"code": " def connectionLost(self, reason) -> None:\n self._maybe_fail()", "label": 1, "label_name": "safe"} -{"code": "void AnnotateExpectRace(const char *file, int line,\n const volatile void *mem,\n const char *description){}", "label": 0, "label_name": "vulnerable"} -{"code": "function securiser_redirect_action($redirect) {\n\t// cas d'un double urlencode : si un urldecode de l'url n'est pas secure, on retient ca comme redirect\n\tif (strpos($redirect, '%') !== false) {\n\t\t$r2 = urldecode($redirect);\n\t\tif (($r3 = securiser_redirect_action($r2)) !== $r2) {\n\t\t\treturn $r3;\n\t\t}\n\t}\n\tif ((tester_url_absolue($redirect) or preg_match(',^\\w+:,',trim($redirect)))\n\t\tand !defined('_AUTORISER_ACTION_ABS_REDIRECT')) {\n\t\t// si l'url est une url du site, on la laisse passer sans rien faire\n\t\t// c'est encore le plus simple\n\t\t$base = $GLOBALS['meta']['adresse_site'] . \"/\";\n\t\tif (strlen($base) and strncmp($redirect, $base, strlen($base)) == 0) {\n\t\t\treturn $redirect;\n\t\t}\n\t\t$base = url_de_base();\n\t\tif (strlen($base) and strncmp($redirect, $base, strlen($base)) == 0) {\n\t\t\treturn $redirect;\n\t\t}\n\n\t\treturn \"\";\n\t}\n\n\treturn $redirect;\n}", "label": 1, "label_name": "safe"} -{"code": "function PMA_headerJSON()\n{\n if (defined('TESTSUITE') && ! defined('PMA_TEST_HEADERS')) {\n return;\n }\n // No caching\n PMA_noCacheHeader();\n // MIME type\n header('Content-Type: application/json; charset=UTF-8');\n // Disable content sniffing in browser\n // This is needed in case we include HTML in JSON, browser might assume it's\n // html to display\n header('X-Content-Type-Options: nosniff');\n}", "label": 1, "label_name": "safe"} -{"code": " 'click .js-update-oidc': (event) => {\n event.preventDefault()\n\n const configuration = {\n service: 'oidc',\n loginStyle: 'popup',\n }\n\n // Fetch the value of each input field\n oidcFields.forEach((field) => {\n configuration[field.property] = document.getElementById(\n `configure-oidc-${field.property}`\n ).value.replace(/^\\s*|\\s*$/g, '') // trim() doesnt work on IE8\n })\n\n configuration.idTokenWhitelistFields = configuration.idTokenWhitelistFields.split(' ')\n\n // Configure this login service\n Meteor.call('updateOidcSettings', configuration, (error) => {\n if (error) {\n // eslint-disable-next-line no-underscore-dangle\n Meteor._debug('Error configuring login service oidc', error)\n } else {\n showToast(t('notifications.success'))\n }\n })\n },", "label": 1, "label_name": "safe"} -{"code": " set escape_for_html(arg:boolean)\n {\n this._escape_for_html = arg;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function uploadCustomLogoAction(Request $request)\n {\n $sourcePath = $_FILES['Filedata']['tmp_name'];\n $fileExt = File::getFileExtension($_FILES['Filedata']['name']);\n if (!in_array($fileExt, ['svg', 'png', 'jpg'])) {\n throw new \\Exception('Unsupported file format');\n }\n\n\n $storage = Tool\\Storage::get('admin');\n\n $fileMimeType = MimeTypes::getDefault()->guessMimeType($sourcePath);\n\n if ($fileMimeType === 'image/svg+xml') {\n $fileContent = file_get_contents($sourcePath);\n\n $sanitizer = new Sanitizer();\n $sanitizedFileContent = $sanitizer->sanitize($fileContent);\n if ($sanitizedFileContent) {\n $storage->write(self::CUSTOM_LOGO_PATH, $sanitizedFileContent);\n }else{\n throw new \\Exception('SVG Sanitization failed, probably due badly formatted XML. Filename:'.$sourcePath);\n }\n }else {\n $storage->writeStream(self::CUSTOM_LOGO_PATH, fopen($sourcePath, 'rb'));\n }\n\n // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in\n // Ext.form.Action.Submit and mark the submission as failed\n\n $response = $this->adminJson(['success' => true]);\n $response->headers->set('Content-Type', 'text/html');\n\n return $response;\n }", "label": 1, "label_name": "safe"} -{"code": " public function checkAuthorisation($id, $user, $write)\n {\n // fetch the bare template\n $template = $this->find('first', array(\n 'conditions' => array('id' => $id),\n 'recursive' => -1,\n ));\n\n // if not found return false\n if (empty($template)) {\n return false;\n }\n\n //if the user is a site admin, return the template without question\n if ($user['Role']['perm_site_admin']) {\n return $template;\n }\n\n if ($write) {\n // if write access is requested, check if template belongs to user's org and whether the user is authorised to edit templates\n if ($user['Organisation']['name'] == $template['Template']['org'] && $user['Role']['perm_template']) {\n return $template;\n }\n return false;\n } else {\n\n // if read access is requested, check if the template belongs to the user's org or alternatively whether the template is shareable\n if ($user['Organisation']['name'] == $template['Template']['org'] || $template['Template']['share']) {\n return $template;\n }\n return false;\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct($message = null, \\Exception $previous = null, $code = 0)\n {\n parent::__construct(406, $message, $previous, array(), $code);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def setup_db(cls, config_calibre_dir, app_db_path):\n cls.dispose()\n\n if not config_calibre_dir:\n cls.config.invalidate()\n return False\n\n dbpath = os.path.join(config_calibre_dir, \"metadata.db\")\n if not os.path.exists(dbpath):\n cls.config.invalidate()\n return False\n\n try:\n cls.engine = create_engine('sqlite://',\n echo=False,\n isolation_level=\"SERIALIZABLE\",\n connect_args={'check_same_thread': False},\n poolclass=StaticPool)\n with cls.engine.begin() as connection:\n connection.execute(text(\"attach database '{}' as calibre;\".format(dbpath)))\n connection.execute(text(\"attach database '{}' as app_settings;\".format(app_db_path)))\n\n conn = cls.engine.connect()\n # conn.text_factory = lambda b: b.decode(errors = 'ignore') possible fix for #1302\n except Exception as ex:\n cls.config.invalidate(ex)\n return False\n\n cls.config.db_configured = True\n\n if not cc_classes:\n try:\n cc = conn.execute(text(\"SELECT id, datatype FROM custom_columns\"))\n cls.setup_db_cc_classes(cc)\n except OperationalError as e:\n log.error_or_exception(e)\n\n cls.session_factory = scoped_session(sessionmaker(autocommit=False,\n autoflush=True,\n bind=cls.engine))\n for inst in cls.instances:\n inst.initSession()\n\n cls._init = True\n return True", "label": 0, "label_name": "vulnerable"} -{"code": " protected Optional> handleRequest(HttpRequest request) {\n HttpHeaders headers = request.getHeaders();\n Optional originHeader = headers.getOrigin();\n if (originHeader.isPresent()) {\n\n String requestOrigin = originHeader.get();\n boolean preflight = CorsUtil.isPreflightRequest(request);\n\n Optional optionalConfig = getConfiguration(requestOrigin);\n\n if (optionalConfig.isPresent()) {\n CorsOriginConfiguration config = optionalConfig.get();\n\n HttpMethod requestMethod = request.getMethod();\n\n List allowedMethods = config.getAllowedMethods();\n\n if (!isAnyMethod(allowedMethods)) {\n HttpMethod methodToMatch = preflight ? headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class).orElse(requestMethod) : requestMethod;\n if (allowedMethods.stream().noneMatch(method -> method.equals(methodToMatch))) {\n return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));\n }\n }\n\n if (preflight) {\n Optional> accessControlHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, Argument.listOf(String.class));\n\n List allowedHeaders = config.getAllowedHeaders();\n\n if (!isAny(allowedHeaders) && accessControlHeaders.isPresent()) {\n if (!accessControlHeaders.get().stream()\n .allMatch(header -> allowedHeaders.stream()\n .anyMatch(allowedHeader -> allowedHeader.equals(header.trim())))) {\n return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));\n }\n }\n\n MutableHttpResponse ok = HttpResponse.ok();\n handleResponse(request, ok);\n return Optional.of(ok);\n }\n }\n }\n\n return Optional.empty();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "inline TfLiteStatus EvalImpl(TfLiteContext* context, TfLiteNode* node,\n std::function func,\n TfLiteType expected_type) {\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, expected_type);\n const int64_t num_elements = NumElements(input);\n const T* in_data = GetTensorData(input);\n T* out_data = GetTensorData(output);\n for (int64_t i = 0; i < num_elements; ++i) {\n out_data[i] = func(in_data[i]);\n }\n return kTfLiteOk;\n}", "label": 1, "label_name": "safe"} -{"code": "func (*ListSubscriptionsRequest) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{29}\n}", "label": 0, "label_name": "vulnerable"} -{"code": "check_vim9_unlet(char_u *name)\n{\n if (*name == NUL)\n {\n\tsemsg(_(e_argument_required_for_str), \"unlet\");\n\treturn FAIL;\n }\n\n if (name[1] != ':' || vim_strchr((char_u *)\"gwtb\", *name) == NULL)\n {\n\t// \"unlet s:var\" is allowed in legacy script.\n\tif (*name == 's' && !script_is_vim9())\n\t return OK;\n\tsemsg(_(e_cannot_unlet_str), name);\n\treturn FAIL;\n }\n return OK;\n}", "label": 1, "label_name": "safe"} -{"code": "mxUtils.setOpacity(W,100),Q.style.visibility=\"\",V.stop(),S())}))}else S();B.appendChild(U);++F==m&&(mxUtils.br(B),F=0)}function M(N){var J=y.value;if(null==N||null!=J&&0refcnt > 0)\n return;\n\n SNMP_FREE(ref->usr_name);\n SNMP_FREE(ref->usr_engine_id);\n SNMP_FREE(ref->usr_auth_protocol);\n SNMP_FREE(ref->usr_priv_protocol);\n\n if (ref->usr_auth_key_length && ref->usr_auth_key) {\n SNMP_ZERO(ref->usr_auth_key, ref->usr_auth_key_length);\n SNMP_FREE(ref->usr_auth_key);\n }\n if (ref->usr_priv_key_length && ref->usr_priv_key) {\n SNMP_ZERO(ref->usr_priv_key, ref->usr_priv_key_length);\n SNMP_FREE(ref->usr_priv_key);\n }\n\n SNMP_FREE(ref);\n} /* end usm_free_usmStateReference() */", "label": 1, "label_name": "safe"} -{"code": " public static byte[] decodeAndInflate(String encodedRequest) throws SAMLException {\n byte[] bytes = Base64.getMimeDecoder().decode(encodedRequest);\n Inflater inflater = new Inflater(true);\n inflater.setInput(bytes);\n inflater.finished();\n\n try {\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n byte[] result = new byte[bytes.length];\n while (!inflater.finished()) {\n int length = inflater.inflate(result);\n if (length > 0) {\n os.write(result, 0, length);\n }\n }\n\n return os.toByteArray();\n } catch (DataFormatException e) {\n throw new SAMLException(\"Invalid AuthnRequest. Inflating the bytes failed.\", e);\n }\n }", "label": 1, "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 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": 1, "label_name": "safe"} -{"code": " public static function menuList($var = '')\n {\n $list = self::$listMenu;\n\n foreach ($list as $k => $v) {\n if (!empty($var) && $k == $var) {\n $selected = 'selected';\n }\n echo \"\";\n }\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public function clearTags() {\n $this->_tags = array(); // clear tag cache\n\n return (bool) CActiveRecord::model('Tags')->deleteAllByAttributes(array(\n 'type' => get_class($this->getOwner()),\n 'itemId' => $this->getOwner()->id)\n );\n }", "label": 1, "label_name": "safe"} -{"code": "static noinline void key_gc_unused_keys(struct list_head *keys)\n{\n\twhile (!list_empty(keys)) {\n\t\tstruct key *key =\n\t\t\tlist_entry(keys->next, struct key, graveyard_link);\n\t\tlist_del(&key->graveyard_link);\n\n\t\tkdebug(\"- %u\", key->serial);\n\t\tkey_check(key);\n\n\t\tsecurity_key_free(key);\n\n\t\t/* deal with the user's key tracking and quota */\n\t\tif (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {\n\t\t\tspin_lock(&key->user->lock);\n\t\t\tkey->user->qnkeys--;\n\t\t\tkey->user->qnbytes -= key->quotalen;\n\t\t\tspin_unlock(&key->user->lock);\n\t\t}\n\n\t\tatomic_dec(&key->user->nkeys);\n\t\tif (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))\n\t\t\tatomic_dec(&key->user->nikeys);\n\n\t\t/* now throw away the key memory */\n\t\tif (key->type->destroy)\n\t\t\tkey->type->destroy(key);\n\n\t\tkey_user_put(key->user);\n\n\t\tkfree(key->description);\n\n#ifdef KEY_DEBUGGING\n\t\tkey->magic = KEY_DEBUG_MAGIC_X;\n#endif\n\t\tkmem_cache_free(key_jar, key);\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": " public function set($width, $height)\n {\n $this->width = $width;\n $this->height = $height;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def seed\n # Authorisation is disabled usually when run from a rake db:* task\n User.current = FactoryGirl.build(:user, :admin => true)\n load File.expand_path('../../../../db/seeds.rb', __FILE__)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def make_homeserver(self, reactor, clock):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = self.setup_test_homeserver(\n http_client=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_federation,\n federation_registry=self.mock_registry,\n )\n\n self.handler = hs.get_directory_handler()\n\n self.store = hs.get_datastore()\n\n self.my_room = RoomAlias.from_string(\"#my-room:test\")\n self.your_room = RoomAlias.from_string(\"#your-room:test\")\n self.remote_room = RoomAlias.from_string(\"#another:remote\")\n\n return hs", "label": 0, "label_name": "vulnerable"} -{"code": "forbidden_name(struct compiling *c, identifier name, const node *n,\n int full_checks)\n{\n assert(PyUnicode_Check(name));\n if (_PyUnicode_EqualToASCIIString(name, \"__debug__\")) {\n ast_error(c, n, \"assignment to keyword\");\n return 1;\n }\n if (full_checks) {\n const char * const *p;\n for (p = FORBIDDEN; *p; p++) {\n if (_PyUnicode_EqualToASCIIString(name, *p)) {\n ast_error(c, n, \"assignment to keyword\");\n return 1;\n }\n }\n }\n return 0;\n}", "label": 1, "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, "label_name": "safe"} -{"code": "CKEDITOR.dom.nodeList.prototype={count:function(){return this.$.length},getItem:function(a){if(a<0||a>=this.$.length)return null;return(a=this.$[a])?new CKEDITOR.dom.node(a):null}};CKEDITOR.dom.element=function(a,e){typeof a==\"string\"&&(a=(e?e.$:document).createElement(a));CKEDITOR.dom.domObject.call(this,a)};CKEDITOR.dom.element.get=function(a){return(a=typeof a==\"string\"?document.getElementById(a)||document.getElementsByName(a)[0]:a)&&(a.$?a:new CKEDITOR.dom.element(a))};", "label": 1, "label_name": "safe"} -{"code": "void ZydisFormatterBufferInitTokenized(ZydisFormatterBuffer* buffer,\n ZydisFormatterToken** first_token, void* user_buffer, ZyanUSize length)\n{\n ZYAN_ASSERT(buffer);\n ZYAN_ASSERT(first_token);\n ZYAN_ASSERT(user_buffer);\n ZYAN_ASSERT(length);\n\n *first_token = user_buffer;\n (*first_token)->type = ZYDIS_TOKEN_INVALID;\n (*first_token)->next = 0;\n\n user_buffer = (ZyanU8*)user_buffer + sizeof(ZydisFormatterToken);\n length -= sizeof(ZydisFormatterToken);\n\n buffer->is_token_list = ZYAN_TRUE;\n buffer->capacity = length;\n buffer->string.flags = ZYAN_STRING_HAS_FIXED_CAPACITY;\n buffer->string.vector.allocator = ZYAN_NULL;\n buffer->string.vector.growth_factor = 1;\n buffer->string.vector.shrink_threshold = 0;\n buffer->string.vector.destructor = ZYAN_NULL;\n buffer->string.vector.element_size = sizeof(char);\n buffer->string.vector.size = 1;\n buffer->string.vector.capacity = length;\n buffer->string.vector.data = user_buffer;\n\n *(char*)user_buffer = '\\0';\n}", "label": 1, "label_name": "safe"} -{"code": "export declare function applyCommandArgs(configuration: any, argv: string[]): void;\nexport declare function setDeepProperty(obj: any, propertyPath: string, value: any): void;", "label": 0, "label_name": "vulnerable"} -{"code": "func (b *Builder) buildControlPlanePathRoute(path string, protected bool) (*envoy_config_route_v3.Route, error) {\n\tr := &envoy_config_route_v3.Route{\n\t\tName: \"pomerium-path-\" + path,\n\t\tMatch: &envoy_config_route_v3.RouteMatch{\n\t\t\tPathSpecifier: &envoy_config_route_v3.RouteMatch_Path{Path: path},\n\t\t},\n\t\tAction: &envoy_config_route_v3.Route_Route{\n\t\t\tRoute: &envoy_config_route_v3.RouteAction{\n\t\t\t\tClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{\n\t\t\t\t\tCluster: httpCluster,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif !protected {\n\t\tr.TypedPerFilterConfig = map[string]*any.Any{\n\t\t\t\"envoy.filters.http.ext_authz\": disableExtAuthz,\n\t\t}\n\t}\n\treturn r, nil\n}", "label": 0, "label_name": "vulnerable"} -{"code": " sanitizeHtmlLight: 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 = 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 return value;\n },", "label": 0, "label_name": "vulnerable"} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\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 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 TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type);\n TF_LITE_ENSURE_EQ(context, output->bytes, input->bytes);\n TF_LITE_ENSURE_EQ(context, output->dims->size, input->dims->size);\n for (int i = 0; i < output->dims->size; ++i) {\n TF_LITE_ENSURE_EQ(context, output->dims->data[i], input->dims->data[i]);\n }\n return kTfLiteOk;\n}", "label": 1, "label_name": "safe"} -{"code": "function formatMessage(msg, output) {\n var output = output;\n output.parseTags = true;\n msg = output._parseTags(msg);\n output.parseTags = false;\n return msg;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " void writeBytes(const void* data, int length) {\n const U8* dataPtr = (const U8*)data;\n const U8* dataEnd = dataPtr + length;\n while (dataPtr < dataEnd) {\n int n = check(1, dataEnd - dataPtr);\n memcpy(ptr, dataPtr, n);\n ptr += n;\n dataPtr += n;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tcache = function(data) {\n\t\t\tvar l = data.length, f;\n\n\t\t\twhile (l--) {\n\t\t\t\tf = data[l];\n\t\t\t\tif (f.name && f.hash && f.mime) {\n\t\t\t\t\tif (!f.phash) {\n\t\t\t\t\t\tvar name = 'volume_'+f.name,\n\t\t\t\t\t\t\ti18 = self.i18n(name);\n\n\t\t\t\t\t\tif (name != i18) {\n\t\t\t\t\t\t\tf.i18 = i18;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfiles[f.hash] = f;\n\t\t\t\t} \n\t\t\t}\n\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " def test_received_chunked_completed_sets_content_length(self):\n data = b\"\"\"\\\nGET /foobar HTTP/1.1\nTransfer-Encoding: chunked\nX-Foo: 1\n\n20;\\r\\n\nThis string has 32 characters\\r\\n\n0\\r\\n\\r\\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 58)\n data = data[result:]\n result = self.parser.received(data)\n self.assertTrue(self.parser.completed)\n self.assertTrue(self.parser.error is None)\n self.assertEqual(self.parser.headers[\"CONTENT_LENGTH\"], \"32\")", "label": 0, "label_name": "vulnerable"} -{"code": "SPL_METHOD(SplFileObject, ftruncate)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tlong size;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &size) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (!php_stream_truncate_supported(intern->u.file.stream)) {\n\t\tzend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, \"Can't truncate file %s\", intern->file_name);\n\t\tRETURN_FALSE;\n\t}\n\t\n\tRETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size));\n} /* }}} */", "label": 0, "label_name": "vulnerable"} -{"code": " public static string CreateMD5(this string input)\n {\n // Use input string to calculate MD5 hash\n using (var md5 = MD5.Create())\n {\n var inputBytes = Encoding.ASCII.GetBytes(input);\n var hashBytes = md5.ComputeHash(inputBytes);\n\n // Convert the byte array to hexadecimal string\n var sb = new StringBuilder();\n foreach (var t in hashBytes)\n {\n sb.Append(t.ToString(\"X2\"));\n }\n return sb.ToString();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "void * calloc(size_t n, size_t lb)\n{\n if ((lb | n) > GC_SQRT_SIZE_MAX /* fast initial test */\n && lb && n > GC_SIZE_MAX / lb)\n return NULL;\n# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */\n /* libpthread allocated some memory that is only pointed to by */\n /* mmapped thread stacks. Make sure it's not collectable. */\n {\n static GC_bool lib_bounds_set = FALSE;\n ptr_t caller = (ptr_t)__builtin_return_address(0);\n /* This test does not need to ensure memory visibility, since */\n /* the bounds will be set when/if we create another thread. */\n if (!EXPECT(lib_bounds_set, TRUE)) {\n GC_init_lib_bounds();\n lib_bounds_set = TRUE;\n }\n if (((word)caller >= (word)GC_libpthread_start\n && (word)caller < (word)GC_libpthread_end)\n || ((word)caller >= (word)GC_libld_start\n && (word)caller < (word)GC_libld_end))\n return GC_malloc_uncollectable(n*lb);\n /* The two ranges are actually usually adjacent, so there may */\n /* be a way to speed this up. */\n }\n# endif\n return((void *)REDIRECT_MALLOC(n*lb));\n}", "label": 1, "label_name": "safe"} -{"code": "def remote_add_node(params, request, session, all=false)\n if not allowed_for_local_cluster(session, Permissions::FULL)\n return 403, 'Permission denied'\n end\n auto_start = false\n if params[:auto_start] and params[:auto_start] == \"1\"\n auto_start = true\n end\n\n if params[:new_nodename] != nil\n node = params[:new_nodename]\n if params[:new_ring1addr] != nil\n node += ',' + params[:new_ring1addr]\n end\n retval, output = add_node(session, node, all, auto_start)\n end\n\n if retval == 0\n return [200, JSON.generate([retval, get_corosync_conf()])]\n end\n\n return [400,output]\nend", "label": 0, "label_name": "vulnerable"} -{"code": " private ServiceStat getRateLimitOpCountStat() throws Throwable {\n URI managementServiceUri = this.host.getManagementServiceUri();\n return this.host.getServiceStats(managementServiceUri)\n .get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "Avahi::Avahi()\n{\n org::freedesktop::Avahi::Server server(\"org.freedesktop.Avahi\", \"/\", QDBusConnection::systemBus());\n QDBusReply reply=server.ServiceBrowserNew(-1, -1, constServiceType, domainToDNS(QString()), 0);\n\n if (reply.isValid()) {\n service=new OrgFreedesktopAvahiServiceBrowserInterface(\"org.freedesktop.Avahi\", reply.value().path(), QDBusConnection::systemBus());\n connect(service, SIGNAL(ItemNew(int,int,QString,QString,QString,uint)), SLOT(addService(int,int,QString,QString,QString,uint)));\n connect(service, SIGNAL(ItemRemove(int,int,QString,QString,QString,uint)), SLOT(removeService(int,int,QString,QString,QString,uint)));\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"raises a ParseError if there is less than 1 arguments\" do\n expect { scope.function_prefix([]) }.to raise_error(Puppet::ParseError, /number of arguments/)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function testFilterBlank()\n {\n $this->assertFiltering('', 'http://example.com/foo/bar.html?q=s');\n }", "label": 1, "label_name": "safe"} -{"code": " def self.get_by_email(mail_addr, user, book=Address::BOOK_BOTH)\n\n SqlHelper.validate_token([mail_addr])\n\n email_con = []\n email_con.push(\"(email1='#{mail_addr}')\")\n email_con.push(\"(email2='#{mail_addr}')\")\n email_con.push(\"(email3='#{mail_addr}')\")\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, "label_name": "safe"} -{"code": "\t\"binary!==\": function(left, right, context) {\n\t\treturn function(scope, locals, assign, inputs) {\n\t\t\tvar arg =\n\t\t\t\tleft(scope, locals, assign, inputs) !==\n\t\t\t\tright(scope, locals, assign, inputs);\n\t\t\treturn context ? { value: arg } : arg;\n\t\t};\n\t},", "label": 1, "label_name": "safe"} -{"code": " $this->assertFalse ($contact->hasTag ($tag, null, true));\n }", "label": 1, "label_name": "safe"} -{"code": "static void handle_runtime(HttpRequest req, HttpResponse res) {\n LOCK(Run.mutex)\n do_runtime(req, res);\n END_LOCK;\n}", "label": 1, "label_name": "safe"} -{"code": " public function testExceptionIsRaisedWhenIniFileCannotBeParsed()\n {\n @$this->loader->load('nonvalid.ini');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "void FdInStream::readBytes(void* data, int length)\n{\n if (length < MIN_BULK_SIZE) {\n InStream::readBytes(data, length);\n return;\n }\n\n U8* dataPtr = (U8*)data;\n\n int n = end - ptr;\n if (n > length) n = length;\n\n memcpy(dataPtr, ptr, n);\n dataPtr += n;\n length -= n;\n ptr += n;\n\n while (length > 0) {\n n = readWithTimeoutOrCallback(dataPtr, length);\n dataPtr += n;\n length -= n;\n offset += n;\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "def keccak256_helper(expr, ir_arg, context):\n sub = ir_arg # TODO get rid of useless variable\n _check_byteslike(sub.typ, expr)\n\n # Can hash literals\n # TODO this is dead code.\n if isinstance(sub, bytes):\n return IRnode.from_list(bytes_to_int(keccak256(sub)), typ=BaseType(\"bytes32\"))\n\n # Can hash bytes32 objects\n if is_base_type(sub.typ, \"bytes32\"):\n return IRnode.from_list(\n [\n \"seq\",\n [\"mstore\", MemoryPositions.FREE_VAR_SPACE, sub],\n [\"sha3\", MemoryPositions.FREE_VAR_SPACE, 32],\n ],\n typ=BaseType(\"bytes32\"),\n add_gas_estimate=_gas_bound(1),\n )\n\n sub = ensure_in_memory(sub, context)\n\n return IRnode.from_list(\n [\n \"with\",\n \"_buf\",\n sub,\n [\"sha3\", [\"add\", \"_buf\", 32], [\"mload\", \"_buf\"]],\n ],\n typ=BaseType(\"bytes32\"),\n annotation=\"keccak256\",\n add_gas_estimate=_gas_bound(ceil(sub.typ.maxlen / 32)),\n )", "label": 0, "label_name": "vulnerable"} -{"code": " generate: function (length, options) {\n length = length || 10\n const generateOptions = options || {}\n\n generateOptions.digits = Object.prototype.hasOwnProperty.call(generateOptions, 'digits') ? options.digits : true\n generateOptions.alphabets = Object.prototype.hasOwnProperty.call(generateOptions, 'alphabets') ? options.alphabets : true\n generateOptions.upperCase = Object.prototype.hasOwnProperty.call(generateOptions, 'upperCase') ? options.upperCase : true\n generateOptions.specialChars = Object.prototype.hasOwnProperty.call(generateOptions, 'specialChars') ? options.specialChars : true\n\n const allowsChars = ((generateOptions.digits || '') && digits) +\n ((generateOptions.alphabets || '') && alphabets) +\n ((generateOptions.upperCase || '') && upperCase) +\n ((generateOptions.specialChars || '') && specialChars)\n let password = ''\n while (password.length < length) {\n const charIndex = crypto.randomInt(0, allowsChars.length)\n password += allowsChars[charIndex]\n }\n return password\n }", "label": 1, "label_name": "safe"} -{"code": " public function checkPersistCode($persistCode)\n {\n if (!$persistCode || !$this->persist_code) {\n return false;\n }\n\n return $persistCode == $this->persist_code;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "null,G)};var A=Menus.prototype.addPopupMenuEditItems;Menus.prototype.addPopupMenuEditItems=function(B,F,G){A.apply(this,arguments);this.editorUi.editor.graph.isSelectionEmpty()&&this.addMenuItems(B,[\"copyAsImage\"],null,G)};EditorUi.prototype.toggleFormatPanel=function(B){null!=this.formatWindow?this.formatWindow.window.setVisible(null!=B?B:!this.formatWindow.window.isVisible()):b(this)};DiagramFormatPanel.prototype.isMathOptionVisible=function(){return!0};var z=EditorUi.prototype.destroy;EditorUi.prototype.destroy=", "label": 1, "label_name": "safe"} -{"code": "\tfunction download($archiveName)\n\t{\n\n\t\t$headerInfo = '';\n\n\t\tif (ini_get('zlib.output_compression')) {\n\t\t\tini_set('zlib.output_compression', 'Off');\n\t\t}\n\n\t\t// Security checks\n\t\tif ($archiveName == \"\") {\n\t\t\techo \"Download Error
ERROR: The download file was NOT SPECIFIED.\";\n\t\t\texit;\n\t\t}\n\n\t\tif (!preg_match('/\\.zip$/', $archiveName)) {\n\t\t\t$archiveName .= '.zip';\n\t\t}\n\t\t$zippedData = $this->getZippedData();\n\t\t$size = strlen(bin2hex($zippedData)) / 2;\n\n\t\theader(\"Pragma: public\");\n\t\theader(\"Expires: 0\");\n\t\theader(\"Cache-Control: must-revalidate, post-check=0, pre-check=0\");\n\t\theader(\"Cache-Control: private\", false);\n\t\theader(\"Content-Type: application/zip\");\n\t\theader(\"Content-Disposition: attachment; filename=\" . $archiveName . \";\");\n\t\theader(\"Content-Transfer-Encoding: binary\");\n\t\theader(\"Content-Length: \" . $size);\n\t\techo $zippedData;\n\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "T[N],\"cells\"),this.updateCustomLinkAction(u,T[N],\"excludeCells\")}};Graph.prototype.updateCustomLinkAction=function(u,D,K){if(null!=D&&null!=D[K]){for(var T=[],N=0;Nu.excludeCells.indexOf(D[T].id)&&K.push(D[T]);\nD=K}return D};Graph.prototype.getCellsById=function(u){var D=[];if(null!=u)for(var K=0;K Self {\n let tokens = &self.tokens[..count];\n\n Input { source: self.source, tokens }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " default Optional getFirst(CharSequence name, ArgumentConversionContext conversionContext) {\n V v = get(name);\n if (v != null) {\n return ConversionService.SHARED.convert(v, conversionContext);\n }\n return Optional.empty();\n }", "label": 1, "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;DgetHtmlLog(), 200, [\n 'Content-Security-Policy' => \"default-src 'self'; style-src 'self' 'unsafe-inline'\"\n ]);\n } elseif ($request->get('type') == 'params') {", "label": 1, "label_name": "safe"} -{"code": "fa=Array(Z.length);for(var aa=0;aa{' + customCols[i] + '}';\n\t\t\t\t}\n\t\t\t\treturn cols;\n\t\t\t},", "label": 1, "label_name": "safe"} -{"code": " def testSparseCountSparseOutputBadNumberOfValues(self):\n indices = [[0, 0], [0, 1], [1, 0]]\n values = [1, 1, 1, 10]\n weights = [1, 2, 4, 6]\n dense_shape = [2, 3]\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n \"Number of values must match first dimension of indices\"):\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, "label_name": "safe"} -{"code": " def initialize(remote_host, remote_port, local_host = nil, local_port = nil)\n if Thread.current[:private_address_check] && PrivateAddressCheck.resolves_to_private_address?(remote_host)\n raise PrivateAddressCheck::PrivateConnectionAttemptedError\n end\n\n initialize_without_private_address_check(remote_host, remote_port, local_host, local_port)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def _expand_user_properties(self, template):\n # Make sure username and servername match the restrictions for DNS labels\n # Note: '-' is not in safe_chars, as it is being used as escape character\n safe_chars = set(string.ascii_lowercase + string.digits)\n\n raw_servername = self.name or ''\n safe_servername = escapism.escape(raw_servername, safe=safe_chars, escape_char='-').lower()\n\n legacy_escaped_username = ''.join([s if s in safe_chars else '-' for s in self.user.name.lower()])\n safe_username = escapism.escape(self.user.name, safe=safe_chars, escape_char='-').lower()\n rendered = template.format(\n userid=self.user.id,\n username=safe_username,\n unescaped_username=self.user.name,\n legacy_escape_username=legacy_escaped_username,\n servername=safe_servername,\n unescaped_servername=raw_servername,\n )\n # strip trailing - delimiter in case of empty servername.\n # k8s object names cannot have trailing -\n return rendered.rstrip(\"-\")", "label": 1, "label_name": "safe"} -{"code": "H.x+\" \"+H.y;S=\"\";d=[];for(V=2;Vf;)x.shift()},P=", "label": 0, "label_name": "vulnerable"} -{"code": " public function testBug19934()\n {\n if (!in_array('http', stream_get_wrappers())) {\n $this->markTestSkipped(\"This test requires an HTTP fopen wrapper enabled\");\n }\n\n $fp = fopen($this->baseUrl . '/bug19934.php', 'rb');\n $body = new HTTP_Request2_MultipartBody(\n array(),\n array(\n 'upload' => array(\n 'fp' => $fp,\n 'filename' => 'foo.txt',\n 'type' => 'text/plain',\n 'size' => 20000\n )\n )\n );\n $this->request->setMethod(HTTP_Request2::METHOD_POST)\n ->setUrl($this->baseUrl . 'uploads.php')\n ->setBody($body);\n\n set_error_handler(array($this, 'rewindWarningsHandler'));\n $response = $this->request->send();\n restore_error_handler();\n\n $this->assertContains(\"upload foo.txt text/plain 20000\", $response->getBody());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " opts.beforeRedirect = function (options) {\n assert.equal(options.hostname, \"sub.localhost\");\n options.hostname = \"localhost\";\n };", "label": 1, "label_name": "safe"} -{"code": "usage(void)\n{\n\tfprintf(stderr,\n\t \"usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\\n\"\n\t \" [-t life] [command [arg ...]]\\n\"\n\t \" ssh-agent [-c | -s] -k\\n\");\n\texit(1);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "Suite.prototype.eachTest = function(fn) {\n utils.forEach(this.tests, fn);\n utils.forEach(this.suites, function(suite) {\n suite.eachTest(fn);\n });\n return this;\n};", "label": 1, "label_name": "safe"} -{"code": "int bson_check_string( bson *b, const char *string,\n const int length ) {\n\n return bson_validate_string( b, ( const unsigned char * )string, length, 1, 0, 0 );\n}", "label": 0, "label_name": "vulnerable"} -{"code": "def main():\n _validate_untrusted_args(sys.argv)\n parser = get_argparser()\n argv = sys.argv[1:]\n args = parser.parse_args(argv)\n if args.json_args is not None:\n args = _unpack_json_args(args)\n earlyinit.early_init(args)\n # We do this imports late as earlyinit needs to be run first (because of\n # version checking and other early initialization)\n from qutebrowser import app\n return app.run(args)", "label": 1, "label_name": "safe"} -{"code": " return function directory(req, res, next) {\n if ('GET' != req.method && 'HEAD' != req.method) return next();\n\n var url = parse(req.url)\n , dir = decodeURIComponent(url.pathname)\n , path = normalize(join(root, dir))\n , originalUrl = parse(req.originalUrl)\n , originalDir = decodeURIComponent(originalUrl.pathname)\n , showUp = path != root;\n\n // null byte(s), bad request\n if (~path.indexOf('\\0')) return next(utils.error(400));\n\n // malicious path, forbidden\n if (0 != path.indexOf(root)) return next(utils.error(403));\n\n // check if we have a directory\n fs.stat(path, function(err, stat){\n if (err) return 'ENOENT' == err.code\n ? next()\n : next(err);\n\n if (!stat.isDirectory()) return next();\n\n // fetch files\n fs.readdir(path, function(err, files){\n if (err) return next(err);\n if (!hidden) files = removeHidden(files);\n if (filter) files = files.filter(filter);\n files.sort();\n\n // content-negotiation\n var type = new Negotiator(req).preferredMediaType(mediaTypes);\n\n // not acceptable\n if (!type) return next(utils.error(406));\n exports[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view, template);\n });\n });\n };", "label": 0, "label_name": "vulnerable"} -{"code": " public function testResolveNullSchemeAmbiguity()\n {\n $this->assertDef('///foo', '/foo');\n }", "label": 1, "label_name": "safe"} -{"code": " self._getForwarded = function(message) {\n\n try {\n // Check message is forwarded from our local user\n if(Common.bareXID(Common.getStanzaFrom(message)) == Common.getXID()) {\n var forwarded_message = $(message.getNode()).find('forwarded[xmlns=\"' + NS_URN_FORWARD + '\"]:first message:first');\n\n if(forwarded_message[0]) {\n return JSJaCPacket.wrapNode(forwarded_message[0]);\n }\n }\n\n return null;\n } catch(e) {\n Console.error('Carbons._getForwarded', e);\n }\n\n };", "label": 1, "label_name": "safe"} -{"code": "fn should_return_error_on_invalid_protocol() {\n\t// given\n\tlet (server, fetch) = serve_with_fetch(\"token\");\n\n\t// when\n\tlet response = request(server,\n\t\t\"\\\n\t\t\tGET /web/token/ftp/parity.io/ HTTP/1.1\\r\\n\\\n\t\t\tHost: localhost:8080\\r\\n\\\n\t\t\tConnection: close\\r\\n\\\n\t\t\t\\r\\n\\\n\t\t\"\n\t);\n\n\t// then\n\tresponse.assert_status(\"HTTP/1.1 400 Bad Request\");\n\tassert_security_headers_for_embed(&response.headers);\n\n\tfetch.assert_no_more_requests();\n}", "label": 0, "label_name": "vulnerable"} -{"code": "mxImageShape.prototype.redrawHtmlShape=function(){this.node.style.left=Math.round(this.bounds.x)+\"px\";this.node.style.top=Math.round(this.bounds.y)+\"px\";this.node.style.width=Math.max(0,Math.round(this.bounds.width))+\"px\";this.node.style.height=Math.max(0,Math.round(this.bounds.height))+\"px\";this.node.innerText=\"\";if(null!=this.image){var a=mxUtils.getValue(this.style,mxConstants.STYLE_IMAGE_BACKGROUND,\"\"),b=mxUtils.getValue(this.style,mxConstants.STYLE_IMAGE_BORDER,\"\");this.node.style.backgroundColor=\na;this.node.style.borderColor=b;a=document.createElement(\"img\");a.setAttribute(\"border\",\"0\");a.style.position=\"absolute\";a.src=this.image;b=100>this.opacity?\"alpha(opacity=\"+this.opacity+\")\":\"\";this.node.style.filter=b;this.flipH&&this.flipV?b+=\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)\":this.flipH?b+=\"progid:DXImageTransform.Microsoft.BasicImage(mirror=1)\":this.flipV&&(b+=\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)\");a.style.filter!=b&&(a.style.filter=b);\"image\"==\na.nodeName?a.style.rotation=this.rotation:0!=this.rotation?mxUtils.setPrefixedStyle(a.style,\"transform\",\"rotate(\"+this.rotation+\"deg)\"):mxUtils.setPrefixedStyle(a.style,\"transform\",\"\");a.style.width=this.node.style.width;a.style.height=this.node.style.height;this.node.style.backgroundImage=\"\";this.node.appendChild(a)}else this.setTransparentBackgroundImage(this.node)};function mxLabel(a,b,c,d){mxRectangleShape.call(this,a,b,c,d)}mxUtils.extend(mxLabel,mxRectangleShape);", "label": 1, "label_name": "safe"} -{"code": "PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner )\n{\n register char *s = scanner->curptr;\n int chr;\n\n if (s >= scanner->end || !*s) {\n\tpj_scan_syntax_err(scanner);\n\treturn 0;\n }\n\n chr = *s;\n\n ++s;\n scanner->curptr = s;\n if (PJ_SCAN_CHECK_EOF(s) && PJ_SCAN_IS_PROBABLY_SPACE(*s) &&\n \tscanner->skip_ws)\n {\n\tpj_scan_skip_whitespace(scanner);\n }\n return chr;\n}", "label": 1, "label_name": "safe"} -{"code": " function changePassword($username, $password)\n {\n $this->log('Auth::changePassword() called', AUTH_LOG_DEBUG);\n $this->_loadStorage();\n return $this->storage->changePassword($username, $password);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getInitTime()\n {\n if (!isset($this->data['events']['__section__'])) {\n return 0;\n }\n\n return $this->data['events']['__section__']->getOrigin() - $this->getStartTime();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function saveconfig() {\n if (!empty($this->params['aggregate']) || !empty($this->params['pull_rss'])) {\n if ($this->params['order'] == 'rank ASC') {\n expValidator::failAndReturnToForm(gt('User defined ranking is not allowed when aggregating or pull RSS data feeds.'), $this->params);\n }\n }\n\n parent::saveconfig();\n }", "label": 1, "label_name": "safe"} -{"code": "function(P,K){0setChroot(array($rootDir));\n $this->setRootDir($rootDir);\n $this->setTempDir(sys_get_temp_dir());\n $this->setFontDir($rootDir . \"/lib/fonts\");\n $this->setFontCache($this->getFontDir());\n\n $ver = \"\";\n $versionFile = realpath(__DIR__ . '/../VERSION');\n if (($version = file_get_contents($versionFile)) !== false) {\n $version = trim($version);\n if ($version !== '$Format:<%h>$') {\n $ver = \"/$version\";\n }\n }\n $this->setHttpContext([\n \"http\" => [\n \"follow_location\" => false,\n \"user_agent\" => \"Dompdf$ver https://github.com/dompdf/dompdf\"\n ]\n ]);\n\n $this->setAllowedProtocols([\"file://\", \"http://\", \"https://\"]);\n\n if (null !== $attributes) {\n $this->set($attributes);\n }\n }", "label": 1, "label_name": "safe"} -{"code": " OFB crypt/decrypt data using key key with cipher cipher starting with iv */\nPHP_FUNCTION(mcrypt_encrypt)\n{\n\tzval **mode;\n\tchar *cipher, *key, *data, *iv = NULL;\n\tint cipher_len, key_len, data_len, iv_len = 0;\n\t\n\tMCRYPT_GET_CRYPT_ARGS\n\t\n\tconvert_to_string_ex(mode);\n\n\tphp_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC);", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " int64_t size() const {\n return m_str ? m_str->size() : 0;\n }", "label": 1, "label_name": "safe"} -{"code": "static int install_thread_keyring(void)\n{\n\tstruct cred *new;\n\tint ret;\n\n\tnew = prepare_creds();\n\tif (!new)\n\t\treturn -ENOMEM;\n\n\tBUG_ON(new->thread_keyring);\n\n\tret = install_thread_keyring_to_cred(new);\n\tif (ret < 0) {\n\t\tabort_creds(new);\n\t\treturn ret;\n\t}\n\n\treturn commit_creds(new);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n if (UNLIKELY(ch1 != '0')) return false;\n auto const ch2 = *p++;\n if (UNLIKELY(ch2 != '0')) return false;\n auto const dch3 = dehexchar(*p++);\n if (UNLIKELY(dch3 < 0)) return false;\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(dch4 < 0)) return false;\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }", "label": 1, "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 = os.path.join(os.path.join(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 netfile = os.path.join(netdir, 'interfaces')\n utils.execute('tee', netfile, process_input=net, run_as_root=True)", "label": 0, "label_name": "vulnerable"} -{"code": "function yourls_check_username_password() {\n\tglobal $yourls_user_passwords;\n\n\t// If login form (not API), check for nonce\n if(!yourls_is_API()) {\n yourls_verify_nonce('admin_login');\n }\n\n\tif( isset( $yourls_user_passwords[ $_REQUEST['username'] ] ) && yourls_check_password_hash( $_REQUEST['username'], $_REQUEST['password'] ) ) {\n\t\tyourls_set_user( $_REQUEST['username'] );\n\t\treturn true;\n\t}\n\treturn false;\n}", "label": 1, "label_name": "safe"} -{"code": "TRIO_PRIVATE void TrioWriteString TRIO_ARGS5((self, string, flags, width, precision),\n trio_class_t* self, TRIO_CONST char* string,\n trio_flags_t flags, int width, int precision)\n{\n\tint length = 0;\n\tint ch;\n\n\tassert(VALID(self));\n\tassert(VALID(self->OutStream));\n\n\tif (string == NULL)\n\t{\n\t\tstring = internalNullString;\n\t\tlength = sizeof(internalNullString) - 1;\n#if TRIO_FEATURE_QUOTE\n\t\t/* Disable quoting for the null pointer */\n\t\tflags &= (~FLAGS_QUOTE);\n#endif\n\t\twidth = 0;\n\t}\n\telse\n\t{\n\t\tif (precision <= 0)\n\t\t{\n\t\t\tlength = trio_length(string);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlength = trio_length_max(string, precision);\n\t\t}\n\t}\n\tif ((NO_PRECISION != precision) && (precision < length))\n\t{\n\t\tlength = precision;\n\t}\n\twidth -= length;\n\n#if TRIO_FEATURE_QUOTE\n\tif (flags & FLAGS_QUOTE)\n\t\tself->OutStream(self, CHAR_QUOTE);\n#endif\n\n\tif (!(flags & FLAGS_LEFTADJUST))\n\t{\n\t\twhile (width-- > 0)\n\t\t\tself->OutStream(self, CHAR_ADJUST);\n\t}\n\n\twhile (length-- > 0)\n\t{\n\t\t/* The ctype parameters must be an unsigned char (or EOF) */\n\t\tch = (int)((unsigned char)(*string++));\n\t\tTrioWriteStringCharacter(self, ch, flags);\n\t}\n\n\tif (flags & FLAGS_LEFTADJUST)\n\t{\n\t\twhile (width-- > 0)\n\t\t\tself->OutStream(self, CHAR_ADJUST);\n\t}\n#if TRIO_FEATURE_QUOTE\n\tif (flags & FLAGS_QUOTE)\n\t\tself->OutStream(self, CHAR_QUOTE);\n#endif\n}", "label": 1, "label_name": "safe"} -{"code": "def test_no_string_escapes():\n assert utils.remove_string_escapes('an \"evil\" string') == 'an \\\\\"evil\\\\\" string'", "label": 1, "label_name": "safe"} -{"code": " void onComplete(const Status& status, ContextImpl& context) const override {\n auto& completion_state = context.getCompletionState(this);\n if (completion_state.is_completed_) {\n return;\n }\n\n // If any of children is OK, return OK\n if (Status::Ok == status) {\n completion_state.is_completed_ = true;\n completeWithStatus(status, context);\n return;\n }\n\n // Then wait for all children to be done.\n if (++completion_state.number_completed_children_ == verifiers_.size()) {\n // Aggregate all children status into a final status.\n // JwtMissing should be treated differently than other failure status\n // since it simply means there is not Jwt token for the required provider.\n // If there is a failure status other than JwtMissing in the children,\n // it should be used as the final status.\n Status final_status = Status::JwtMissed;\n for (const auto& it : verifiers_) {\n // If a Jwt is extracted from a location not specified by the required provider,\n // the authenticator returns JwtUnknownIssuer. It should be treated the same as\n // JwtMissed.\n Status child_status = context.getCompletionState(it.get()).status_;\n if (child_status != Status::JwtMissed && child_status != Status::JwtUnknownIssuer) {\n final_status = child_status;\n }\n }\n\n if (is_allow_missing_or_failed_) {\n final_status = Status::Ok;\n } else if (is_allow_missing_ && final_status == Status::JwtMissed) {\n final_status = Status::Ok;\n }\n completion_state.is_completed_ = true;\n completeWithStatus(final_status, context);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it 'should delete elements of the array' do\n pp = <<-EOS\n $output = delete_at(['a','b','c','b'], 1)\n if $output == ['a','c','b'] {\n notify { 'output correct': }\n }\n EOS\n\n apply_manifest(pp, :catch_failures => true) do |r|\n expect(r.stdout).to match(/Notice: output correct/)\n end\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function parse($uri)\n {\n $uri = $this->percentEncoder->normalize($uri);\n\n // Regexp is as per Appendix B.\n // Note that [\"<>] are an addition to the RFC's recommended\n // characters, because they represent external delimeters.\n $r_URI = '!'.\n '(([a-zA-Z0-9\\.\\+\\-]+):)?'. // 2. Scheme\n '(//([^/?#\"<>]*))?'. // 4. Authority\n '([^?#\"<>]*)'. // 5. Path\n '(\\?([^#\"<>]*))?'. // 7. Query\n '(#([^\"<>]*))?'. // 8. Fragment\n '!';\n\n $matches = array();\n $result = preg_match($r_URI, $uri, $matches);\n\n if (!$result) return false; // *really* invalid URI\n\n // seperate out parts\n $scheme = !empty($matches[1]) ? $matches[2] : null;\n $authority = !empty($matches[3]) ? $matches[4] : null;\n $path = $matches[5]; // always present, can be empty\n $query = !empty($matches[6]) ? $matches[7] : null;\n $fragment = !empty($matches[8]) ? $matches[9] : null;\n\n // further parse authority\n if ($authority !== null) {\n $r_authority = \"/^((.+?)@)?(\\[[^\\]]+\\]|[^:]*)(:(\\d*))?/\";\n $matches = array();\n preg_match($r_authority, $authority, $matches);\n $userinfo = !empty($matches[1]) ? $matches[2] : null;\n $host = !empty($matches[3]) ? $matches[3] : '';\n $port = !empty($matches[4]) ? (int) $matches[5] : null;\n } else {\n $port = $host = $userinfo = null;\n }\n\n return new HTMLPurifier_URI(\n $scheme, $userinfo, $host, $port, $path, $query, $fragment);\n }", "label": 1, "label_name": "safe"} -{"code": " foreach ($days as $value) {\n $regitem[] = $value;\n }", "label": 1, "label_name": "safe"} -{"code": " def self.update_for(user_id, fiscal_year, num)\n\n SqlHelper.validate_token([user_id, fiscal_year])\n\n if num <= 0\n con = []\n con << \"(user_id=#{user_id.to_i})\"\n con << \"(year=#{fiscal_year.to_i})\"\n PaidHoliday.destroy_all(con.join(' and '))\n return\n end\n\n paid_holiday = PaidHoliday.get_for(user_id, fiscal_year)\n\n if paid_holiday.nil?\n paid_holiday = PaidHoliday.new\n paid_holiday.user_id = user_id\n paid_holiday.year = fiscal_year\n paid_holiday.num = num\n paid_holiday.save!\n else\n paid_holiday.update_attribute(:num, num)\n end\n end", "label": 1, "label_name": "safe"} -{"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": 1, "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, "label_name": "safe"} -{"code": " def test_login_unknown_code(self):\n response = self.client.post('/accounts-rest/login/code/', {\n 'code': 'unknown',\n })\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json(), {\n 'code': ['Login code is invalid. It might have expired.'],\n })", "label": 0, "label_name": "vulnerable"} -{"code": "this.updateStyle()},getElement:function(){return this._.element},getName:function(){return this._.name},getContentElement:function(a,b){var c=this._.contents[a];return c&&c[b]},getValueOf:function(a,b){return this.getContentElement(a,b).getValue()},setValueOf:function(a,b,c){return this.getContentElement(a,b).setValue(c)},getButton:function(a){return this._.buttons[a]},click:function(a){return this._.buttons[a].click()},disableButton:function(a){return this._.buttons[a].disable()},enableButton:function(a){return this._.buttons[a].enable()},", "label": 1, "label_name": "safe"} -{"code": " function delete() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);\n $product = new $product_type($this->params['id'], true, false);\n //eDebug($product_type);\n //eDebug($product, true);\n //if (!empty($product->product_type_id)) {\n //$db->delete($product_type, 'id='.$product->product_id);\n //}\n\n $db->delete('option', 'product_id=' . $product->id . \" AND optiongroup_id IN (SELECT id from \" . $db->prefix . \"optiongroup WHERE product_id=\" . $product->id . \")\");\n $db->delete('optiongroup', 'product_id=' . $product->id);\n //die();\n $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type=\"' . $product_type . '\"');\n\n if ($product->product_type == \"product\") {\n if ($product->hasChildren()) {\n $this->deleteChildren();\n }\n }\n\n $product->delete();\n\n flash('message', gt('Product deleted successfully.'));\n expHistory::back();\n }", "label": 1, "label_name": "safe"} -{"code": "f.appendChild(m);f.appendChild(l);k.appendChild(f);var q=c,v,x,A=function(n,y,K,B){var F=\"data:\"==n.substring(0,5);!b.isOffline()||F&&\"undefined\"===typeof chrome?0getModel($id);\n\n\t\tif(isset($_POST['Quote'])){\n\t\t\t$model->setX2Fields($_POST['Quote']);\n\t\t\tif(isset($_POST['lineitem']))\n\t\t\t\t$model->lineItems = $_POST['lineitem'];\n\n\t\t\tif(!$model->hasLineItemErrors) {\n\t\t\t\tif($model->save()) {\n\t\t\t\t\t$model->saveLineItems();\n\t\t\t\t\t$this->redirect(array('view','id' => $model->id));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$users=User::getNames();\n\t\t$products = $model->activeProducts();\n\t\t$quoteProducts = $model->lineItems;\n\t\t$viewData = array(\n\t\t\t'model' => $model,\n\t\t\t'users' => $users,\n\t\t\t'products' => $products,\n\t\t\t'orders' => $quoteProducts,\n\t\t\t'quick'=>$quick,\n\t\t);\n\n\t\tif(!$quick)\n\t\t\t$this->render('update', $viewData);\n\t\telse {\n\t\t\tif($model->hasErrors() || $model->hasLineItemErrors) {\n\t\t\t\t// Sneak into the response that validation failed via setting\n\t\t\t\t// the response code manually:\n\t\t\t\theader('HTTP/1.1 400 Validation Error');\n\t\t\t}\n\t\t\t$this->renderPartial('update', $viewData,false,true);\n\t\t}\n\t}", "label": 1, "label_name": "safe"} -{"code": "b.Z||840a.Y?22801:1,b||a.Z?new Date(Date.UTC(a.Y,a.M,a.D,a.H,a.m+a.Z,a.s,a.S)):new Date(a.Y,a.M,a.D,a.H,a.m,a.s,a.S)):new Date(NaN)};d.transform=function(a,c,b,e){return d.format(d.parse(a,c),b,e)};d.addYears=function(a,c){return d.addMonths(a,12*c)};d.addMonths=function(a,c){var b=new Date(a.getTime());b.setMonth(b.getMonth()+c);return b};d.addDays=function(a,c){var b=new Date(a.getTime());b.setDate(b.getDate()+c);return b};", "label": 0, "label_name": "vulnerable"} -{"code": " def remove_all_groups\n check_write_access!\n self.package_group_role_relationships.delete_all\n end", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " $nodes[$level]->push($childNode);\n }\n }\n }\n $level--;\n if ($level && isset($closingNodes[$level])) {\n while ($node = array_pop($closingNodes[$level])) {\n $this->createEndNode($node, $tokens);\n }\n }\n } while ($level > 0);\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public function __construct(\n AuthManager $auth,\n Repository $config,\n CacheRepository $cache,\n UserRepositoryInterface $repository,\n ViewFactory $view\n ) {\n parent::__construct($auth, $config);\n\n $this->view = $view;\n $this->cache = $cache;\n $this->repository = $repository;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\"bVisible\").length}function aa(a,b) {var c=[];h.map(a.aoColumns,function(a,e) {a[b]&&c.push(e)});return c}function Ia(a) {var b=a.aoColumns,c=a.aoData,d=m.ext.type.detect,e,f,g,j,i,h,l,q,u;e=0;for(f=b.length;evbd.bdev;\n\tunsigned long secure;\n\n\tblkif->st_ds_req++;\n\n\txen_blkif_get(blkif);\n\tsecure = (blkif->vbd.discard_secure &&\n\t\t (req->u.discard.flag & BLKIF_DISCARD_SECURE)) ?\n\t\t BLKDEV_DISCARD_SECURE : 0;\n\n\terr = blkdev_issue_discard(bdev, req->u.discard.sector_number,\n\t\t\t\t req->u.discard.nr_sectors,\n\t\t\t\t GFP_KERNEL, secure);\n\n\tif (err == -EOPNOTSUPP) {\n\t\tpr_debug(DRV_PFX \"discard op failed, not supported\\n\");\n\t\tstatus = BLKIF_RSP_EOPNOTSUPP;\n\t} else if (err)\n\t\tstatus = BLKIF_RSP_ERROR;\n\n\tmake_response(blkif, req->u.discard.id, req->operation, status);\n\txen_blkif_put(blkif);\n\treturn err;\n}", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": "void PngImg::InitStorage_() {\n rowPtrs_.resize(info_.height, nullptr);\n // Extend height and rowbytes from uint32_t to size_t to avoid multiplication overflow when size_t is larger\n size_t h = info_.height;\n size_t rb = info_.rowbytes;\n // We need to make sure that info_.height * info_.rowbytes will not overflow size_t\n // Unfotunately, there's no simple and portable way to do this in C++\n // For integer division of positive numbers a * b > c <==> a > c / b holds\n if (h > std::numeric_limits::max() / rb) {\n // TODO Propagate this exception to JS, and test it\n throw std::runtime_error(\"Image is too large to allocate single buffer\");\n }\n data_ = new png_byte[h * rb];\n\n for(size_t i = 0; i < info_.height; ++i) {\n rowPtrs_[i] = data_ + i * rb;\n }\n}", "label": 1, "label_name": "safe"} -{"code": "PUBLIC int espOpenDatabase(HttpRoute *route, cchar *spec)\n{\n EspRoute *eroute;\n char *provider, *path, *dir;\n int flags;\n\n eroute = route->eroute;\n if (eroute->edi) {\n return 0;\n }\n flags = EDI_CREATE | EDI_AUTO_SAVE;\n if (smatch(spec, \"default\")) {\n#if ME_COM_SQLITE\n spec = sfmt(\"sdb://%s.sdb\", eroute->appName);\n#elif ME_COM_MDB\n spec = sfmt(\"mdb://%s.mdb\", eroute->appName);\n#endif\n }\n provider = stok(sclone(spec), \"://\", &path);\n if (provider == 0 || path == 0) {\n return MPR_ERR_BAD_ARGS;\n }\n path = mprJoinPath(httpGetDir(route, \"db\"), path);\n dir = mprGetPathDir(path);\n if (!mprPathExists(dir, X_OK)) {\n mprMakeDir(dir, 0755, -1, -1, 1);\n }\n if ((eroute->edi = ediOpen(mprGetRelPath(path, NULL), provider, flags)) == 0) {\n return MPR_ERR_CANT_OPEN;\n }\n route->database = sclone(spec);\n return 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "be32dec_vect(uint32_t *dst, const unsigned char *src, size_t len)\n{\n size_t i;\n uint32_t *s;\n\n for (i = 0; i < len / 4; i++) {\n s = (uint32_t *) (src + i * 4);\n dst[i] = folly::Endian::big32(*s);\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "this.init=function(){function G(H){if(null!=H){var S=H.getAttribute(\"background\");if(null==S||\"\"==S||S==mxConstants.NONE)S=Editor.isDarkMode()?\"transparent\":\"#ffffff\";B.style.backgroundColor=S;(new mxCodec(H.ownerDocument)).decode(H,I.getModel());I.maxFitScale=1;I.fit(8);I.center()}return H}function P(H){null!=H&&(H=G(Editor.parseDiagramNode(H)));return H}mxEvent.addListener(D,\"change\",function(H){z=parseInt(D.value);P(L[z]);mxEvent.consume(H)});if(\"mxfile\"==t.nodeName){var K=t.getElementsByTagName(\"diagram\");", "label": 0, "label_name": "vulnerable"} -{"code": "r=g.isEventsEnabled();g.setEventsEnabled(!1);var q=this.graph.isEnabled();this.graph.setEnabled(!1);var t=g.getTranslate();g.translate=new mxPoint(a,b);var u=this.graph.cellRenderer.redraw,x=g.states;a=g.scale;if(this.clipping){var A=new mxRectangle((f.x+t.x)*a,(f.y+t.y)*a,f.width*a/p,f.height*a/p),E=this;this.graph.cellRenderer.redraw=function(D,B,v){if(null!=D){var y=x.get(D.cell);if(null!=y&&(y=g.getBoundingBox(y,!1),null!=y&&0params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status_messages',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'body',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n\t\t\t//'columns'=>array('Name'=>'title')\n ));\n\n //eDebug($page);\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function Router (opts) {\n if (!(this instanceof Router)) {\n return new Router(opts)\n }\n opts = opts || {}\n\n if (opts.defaultRoute) {\n assert(typeof opts.defaultRoute === 'function', 'The default route must be a function')\n this.defaultRoute = opts.defaultRoute\n } else {\n this.defaultRoute = null\n }\n\n if (opts.onBadUrl) {\n assert(typeof opts.onBadUrl === 'function', 'The bad url handler must be a function')\n this.onBadUrl = opts.onBadUrl\n } else {\n this.onBadUrl = null\n }\n\n this.caseSensitive = opts.caseSensitive === undefined ? true : opts.caseSensitive\n this.ignoreTrailingSlash = opts.ignoreTrailingSlash || false\n this.maxParamLength = opts.maxParamLength || 100\n this.allowUnsafeRegex = opts.allowUnsafeRegex || false\n this.versioning = opts.versioning || acceptVersionStrategy(false)\n this.trees = {}\n this.routes = []\n}", "label": 1, "label_name": "safe"} -{"code": "void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));}", "label": 1, "label_name": "safe"} -{"code": "static void scsi_read_data(SCSIRequest *req)\n{\n SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);\n uint32_t n;\n\n if (r->sector_count == (uint32_t)-1) {\n DPRINTF(\"Read buf_len=%zd\\n\", r->iov.iov_len);\n r->sector_count = 0;\n scsi_req_data(&r->req, r->iov.iov_len);\n return;\n }\n DPRINTF(\"Read sector_count=%d\\n\", r->sector_count);\n if (r->sector_count == 0) {\n /* This also clears the sense buffer for REQUEST SENSE. */\n scsi_req_complete(&r->req, GOOD);\n return;\n }\n\n /* No data transfer may already be in progress */\n assert(r->req.aiocb == NULL);\n\n if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {\n DPRINTF(\"Data transfer direction invalid\\n\");\n scsi_read_complete(r, -EINVAL);\n return;\n }\n\n if (s->tray_open) {\n scsi_read_complete(r, -ENOMEDIUM);\n }\n n = scsi_init_iovec(r);\n bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);\n r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,\n scsi_read_complete, r);\n if (r->req.aiocb == NULL) {\n scsi_read_complete(r, -EIO);\n }\n}", "label": 1, "label_name": "safe"} -{"code": "App.prototype.descriptorChanged = function()\n{\n\tvar file = this.getCurrentFile();\n\t\n\tif (file != null)\n\t{\n\t\tif (this.fname != null)\n\t\t{\n\t\t\tthis.fnameWrapper.style.display = 'block';\n\t\t\tthis.fname.innerHTML = '';\n\t\t\tvar filename = (file.getTitle() != null) ? file.getTitle() : this.defaultFilename;\n\t\t\tmxUtils.write(this.fname, filename);\n\t\t\tthis.fname.setAttribute('title', filename + ' - ' + mxResources.get('rename'));\n\t\t}\n\t\t\n\t\tvar graph = this.editor.graph;\n\t\tvar editable = file.isEditable() && !file.invalidChecksum;\n\t\t\n\t\tif (graph.isEnabled() && !editable)\n\t\t{\n\t\t\tgraph.reset();\n\t\t}\n\t\t\n\t\tgraph.setEnabled(editable);\n\t\t\n\t\t// Ignores title and hash for revisions\n\t\tif (urlParams['rev'] == null)\n\t\t{\n\t\t\tthis.updateDocumentTitle();\n\t\t\tvar newHash = file.getHash();\n\t\t\t\n\t\t\tif (newHash.length > 0)\n\t\t\t{\n\t\t\t\twindow.location.hash = newHash;\n\t\t\t}\n\t\t\telse if (window.location.hash.length > 0)\n\t\t\t{\n\t\t\t\twindow.location.hash = '';\n\t\t\t}\n\t\t}\n\t}\n\t\n\tthis.updateUi();\n\t\n\t// Refresh if editable state has changed\n\tif (this.format != null && (file == null ||\n\t\tthis.fileEditable != file.isEditable()) &&\n\t\tthis.editor.graph.isSelectionEmpty())\n\t{\n\t\tthis.format.refresh();\n\t\tthis.fileEditable = (file != null) ? file.isEditable() : null;\n\t}\n\t\n\tthis.fireEvent(new mxEventObject('fileDescriptorChanged', 'file', file));\n};", "label": 0, "label_name": "vulnerable"} -{"code": " public function setDefinition($id, Definition $definition)\n {\n if ($this->isFrozen()) {\n throw new BadMethodCallException('Adding definition to a frozen container is not allowed');\n }\n\n $id = strtolower($id);\n\n unset($this->aliasDefinitions[$id]);\n\n return $this->definitions[$id] = $definition;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def to_yaml(self, **kwargs):\n \"\"\"Returns a yaml string containing the network configuration.\n\n To load a network from a yaml save file, use\n `keras.models.model_from_yaml(yaml_string, custom_objects={})`.\n\n `custom_objects` should be a dictionary mapping\n the names of custom losses / layers / etc to the corresponding\n functions / classes.\n\n Args:\n **kwargs: Additional keyword arguments\n to be passed to `yaml.dump()`.\n\n Returns:\n A YAML string.\n\n Raises:\n ImportError: if yaml module is not found.\n \"\"\"\n if yaml is None:\n raise ImportError(\n 'Requires yaml module installed (`pip install pyyaml`).')\n return yaml.dump(self._updated_config(), **kwargs)", "label": 0, "label_name": "vulnerable"} -{"code": " def initialize(session, query_operation)\n @session = session\n @query_op = query_operation.dup\n\n @get_more_op = Protocol::GetMore.new(\n @query_op.database,\n @query_op.collection,\n 0,\n @query_op.limit\n )\n\n @kill_cursor_op = Protocol::KillCursors.new([0])\n end", "label": 0, "label_name": "vulnerable"} -{"code": "ArcMemory::ArcMemory()\n{\n Loaded=false;\n SeekPos=0;\n}", "label": 1, "label_name": "safe"} -{"code": " private function timeToNext()\n {\n $currentTime = microtime(true);\n $nextTime = PHP_INT_MAX;\n foreach ($this->delays as $time) {\n if ($time < $nextTime) {\n $nextTime = $time;\n }\n }\n\n return max(0, $currentTime - $nextTime);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "void TensorSliceReader::LoadShard(int shard) const {\n CHECK_LT(shard, sss_.size());\n if (sss_[shard] || !status_.ok()) {\n return; // Already loaded, or invalid.\n }\n string value;\n SavedTensorSlices sts;\n const string fname = fnames_[shard];\n VLOG(1) << \"Reading meta data from file \" << fname << \"...\";\n Table* table;\n Status s = open_function_(fname, &table);\n if (!s.ok()) {\n status_ = errors::DataLoss(\"Unable to open table file \", fname, \": \",\n s.ToString());\n return;\n }\n sss_[shard].reset(table);\n if (!(table->Get(kSavedTensorSlicesKey, &value) &&\n ParseProtoUnlimited(&sts, value))) {\n status_ = errors::Internal(\n \"Failed to find the saved tensor slices at the beginning of the \"\n \"checkpoint file: \",\n fname);\n return;\n }\n status_ = CheckVersions(sts.meta().versions(), TF_CHECKPOINT_VERSION,\n TF_CHECKPOINT_VERSION_MIN_PRODUCER, \"Checkpoint\",\n \"checkpoint\");\n if (!status_.ok()) return;\n for (const SavedSliceMeta& ssm : sts.meta().tensor()) {\n TensorShape ssm_shape;\n status_ = TensorShape::BuildTensorShapeBase(ssm.shape(), &ssm_shape);\n if (!status_.ok()) return;\n for (const TensorSliceProto& tsp : ssm.slice()) {\n TensorSlice ss_slice(tsp);\n status_ = RegisterTensorSlice(ssm.name(), ssm_shape, ssm.type(), fname,\n ss_slice, &tensors_);\n if (!status_.ok()) return;\n }\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def _create(self):\n url = recurly.base_uri() + self.collection_path\n return self.post(url)", "label": 1, "label_name": "safe"} -{"code": " public function testConstruct()\n {\n $response = new CompletePurchaseresponse($this->getMockRequest(), array('order_number' => 'abc123'));\n\n $this->assertTrue($response->isSuccessful());\n $this->assertFalse($response->isRedirect());\n $this->assertSame('abc123', $response->getTransactionReference());\n $this->assertNull($response->getMessage());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static bool RunningAsService()\n {\n return GetCurrent().Name.ToLower().Contains(@\"nt authority\\system\");\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it 'sorts arrays' do\n pp = <<-EOS\n $a = [\"the\",\"public\",\"art\",\"galleries\"]\n # Anagram: Large picture halls, I bet\n $o = sort($a)\n notice(inline_template('sort is <%= @o.inspect %>'))\n EOS\n\n apply_manifest(pp, :catch_failures => true) do |r|\n expect(r.stdout).to match(/sort is \\[\"art\", \"galleries\", \"public\", \"the\"\\]/)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\t\t\tdrag_update : function() {\n\t\t\t\t\t\t\trhandlec.data({x: null, y: null});\n\t\t\t\t\t\t\tcrop.update();\n\t\t\t\t\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": " $timer->setMarker($key);\n }\n\n $timer->stop();\n $timer->display();\n}", "label": 1, "label_name": "safe"} -{"code": "App.Actions.DB.update_db_username_hint = function(elm, hint) {\n if (hint.trim() == '') {\n $(elm).parent().find('.hint').html('');\n } \n $(elm).parent().find('.hint').text(GLOBAL.DB_USER_PREFIX + hint);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it { should be_file }", "label": 0, "label_name": "vulnerable"} -{"code": " it 'should escape unsafe characters in attributes' do\n @s.fragment(input).must_equal(%[<#{tag_name} #{attr_name}=\"example.com\">foo])\n end", "label": 1, "label_name": "safe"} -{"code": " \"should set the correct value\": function(res) {\n assert.equal(res.a, \"b\");\n },", "label": 0, "label_name": "vulnerable"} -{"code": " def test_quotas_update_as_admin(self):\n body = {'quota_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\n req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me',\n use_admin_context=True)\n res_dict = self.controller.update(req, 'update_me', body)\n\n self.assertEqual(res_dict, body)", "label": 0, "label_name": "vulnerable"} -{"code": "function(){function O(ua,ya,Na){var Fa=U.menus.get(ua),Ra=R.addMenu(mxResources.get(ua),mxUtils.bind(this,function(){Fa.funct.apply(this,arguments)}),P);Ra.className=\"1\"==urlParams.sketch?\"geToolbarButton\":\"geMenuItem\";Ra.style.display=\"inline-block\";Ra.style.boxSizing=\"border-box\";Ra.style.top=\"6px\";Ra.style.marginRight=\"6px\";Ra.style.height=\"30px\";Ra.style.paddingTop=\"6px\";Ra.style.paddingBottom=\"6px\";Ra.style.cursor=\"pointer\";Ra.setAttribute(\"title\",mxResources.get(ua));U.menus.menuCreated(Fa,\nRa,\"geMenuItem\");null!=Na?(Ra.style.backgroundImage=\"url(\"+Na+\")\",Ra.style.backgroundPosition=\"center center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.backgroundSize=\"24px 24px\",Ra.style.width=\"34px\",Ra.innerHTML=\"\"):ya||(Ra.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\",Ra.style.backgroundPosition=\"right 6px center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.paddingRight=\"22px\");return Ra}function X(ua,ya,Na,Fa,Ra,db){var Va=document.createElement(\"a\");Va.className=", "label": 0, "label_name": "vulnerable"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct(\n FilesystemInterface $filesystemPrivate,\n FilesystemInterface $filesystemPublic,\n FilesystemInterface $filesystemTheme,\n FilesystemInterface $filesystemSitemap,\n FilesystemInterface $filesystemAsset\n ) {\n parent::__construct();\n $this->filesystemPrivate = $filesystemPrivate;\n $this->filesystemPublic = $filesystemPublic;\n $this->filesystemTheme = $filesystemTheme;\n $this->filesystemSitemap = $filesystemSitemap;\n $this->filesystemAsset = $filesystemAsset;\n }", "label": 1, "label_name": "safe"} -{"code": " function npgettext($context, $singular, $plural, $number) {\n $key = $context . chr(4) . $singular;\n $ret = $this->ngettext($key, $plural, $number);\n if (strpos($ret, \"\\004\") !== FALSE) {\n return $singular;\n } else {\n return $ret;\n }\n\n }", "label": 0, "label_name": "vulnerable"} -{"code": "1);break}D.className=la.join(\" \")}null!=ha?(D=ha,D.className+=\" \"+da,K=ca,Aa.className=\"geTempDlgCreateBtn\"):(K=D=null,Aa.className=\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function z(ha,da){if(null!=K){var ca=function(pa){ra.isExternal?g(ra,function(na){la(na,pa)},ia):ra.url?mxUtils.get(TEMPLATE_PATH+\"/\"+ra.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?la(na.getText(),pa):ia()})):la(b.emptyDiagramXml,pa)},la=function(pa,na){y||b.hideDialog(!0);e(pa,na,ra,da)},ia=function(){A(mxResources.get(\"cannotLoad\"));\nma()},ma=function(){K=ra;Aa.className=\"geTempDlgCreateBtn\";da&&(Ha.className=\"geTempDlgOpenBtn\")},ra=K;K=null;\"boolean\"!==typeof da&&(da=ra.isExternal&&p);1==ha?k(ra.url,ra):da?(Ha.className=\"geTempDlgOpenBtn geTempDlgBtnDisabled geTempDlgBtnBusy\",ca()):(Aa.className=\"geTempDlgCreateBtn geTempDlgBtnDisabled geTempDlgBtnBusy\",ha=null==b.mode||b.mode==App.MODE_GOOGLE||b.mode==App.MODE_BROWSER?mxResources.get(\"diagramName\"):mxResources.get(\"filename\"),ha=new FilenameDialog(b,b.defaultFilename+\".drawio\",", "label": 1, "label_name": "safe"} -{"code": "lldp_mgmt_addr_tlv_print(netdissect_options *ndo,\n const u_char *pptr, u_int len)\n{\n uint8_t mgmt_addr_len, intf_num_subtype, oid_len;\n const u_char *tptr;\n u_int tlen;\n char *mgmt_addr;\n\n tlen = len;\n tptr = pptr;\n\n if (tlen < 1) {\n return 0;\n }\n mgmt_addr_len = *tptr++;\n tlen--;\n\n if (tlen < mgmt_addr_len) {\n return 0;\n }\n\n mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len);\n if (mgmt_addr == NULL) {\n return 0;\n }\n ND_PRINT((ndo, \"\\n\\t Management Address length %u, %s\",\n mgmt_addr_len, mgmt_addr));\n tptr += mgmt_addr_len;\n tlen -= mgmt_addr_len;\n\n if (tlen < LLDP_INTF_NUM_LEN) {\n return 0;\n }\n\n intf_num_subtype = *tptr;\n ND_PRINT((ndo, \"\\n\\t %s Interface Numbering (%u): %u\",\n tok2str(lldp_intf_numb_subtype_values, \"Unknown\", intf_num_subtype),\n intf_num_subtype,\n EXTRACT_32BITS(tptr + 1)));\n\n tptr += LLDP_INTF_NUM_LEN;\n tlen -= LLDP_INTF_NUM_LEN;\n\n /*\n * The OID is optional.\n */\n if (tlen) {\n oid_len = *tptr;\n\n if (tlen < 1U + oid_len) {\n return 0;\n }\n if (oid_len) {\n ND_PRINT((ndo, \"\\n\\t OID length %u\", oid_len));\n safeputs(ndo, tptr + 1, oid_len);\n }\n }\n\n return 1;\n}", "label": 1, "label_name": "safe"} -{"code": "int main()\n{\n gdImagePtr im;\n char *buffer;\n size_t size;\n\n size = read_test_file(&buffer, \"heap_overflow.tga\");\n im = gdImageCreateFromTgaPtr(size, (void *) buffer);\n gdTestAssert(im == NULL);\n free(buffer);\n\n return gdNumFailures();\n}", "label": 1, "label_name": "safe"} -{"code": " function Auth_Anonymous($storageDriver, $options = '', $loginFunction = '', $showLogin = true) {\n parent::Auth($storageDriver, $options, $loginFunction, $showLogin);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function update (SplSubject $subject)\n {\n $this->calls++;\n $this->event = $subject->getLastEvent();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, jas_matind_t xstart,\n jas_matind_t ystart, jas_matind_t xend, jas_matind_t yend)\n{\n\tjas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,\n\t yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);\n}", "label": 1, "label_name": "safe"} -{"code": "\t\tsqlrequest($database_eonweb,\"insert into logs values ('','\".time().\"','\".$user.\"','$module','$command','\".$_SERVER[\"REMOTE_ADDR\"].\"');\");\n\t}", "label": 1, "label_name": "safe"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $action = $this->getAction($project);\n\n if (! empty($action) && $this->actionModel->remove($action['id'])) {\n $this->flash->success(t('Action removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this action.'));\n }\n\n $this->response->redirect($this->helper->url->to('ActionController', 'index', array('project_id' => $project['id'])));\n }", "label": 1, "label_name": "safe"} -{"code": "b.handleError(la,null,null,null,mxUtils.htmlEntities(mxResources.get(\"objectNotFound\")))},Y,da)}function Z(){c(aa,ua,function(la){ha()},!0)}var ea=W().pdiv,aa=b.newComment(P,b.getCurrentUser());aa.pCommentId=J.id;null==J.replies&&(J.replies=[]);var ua=q(aa,J.replies,ea,S+1);O?Z():ha()}if(U||!J.isResolved){n.style.display=\"none\";var X=document.createElement(\"div\");X.className=\"geCommentContainer\";X.setAttribute(\"data-commentId\",J.id);X.style.marginLeft=20*S+5+\"px\";J.isResolved&&!Editor.isDarkMode()&&", "label": 0, "label_name": "vulnerable"} -{"code": " def create\n execute([command(:rvmcmd), \"wrapper\", target_ruby, prefix || \"--no-prefix\", wrapper_name])\n end", "label": 0, "label_name": "vulnerable"} -{"code": "def remove_unsafe_chars(data):\n if isinstance(data, str):\n return \"\".join([char for char in data if char not in (\"=\", \"+\", \"-\")])\n\n return data", "label": 1, "label_name": "safe"} -{"code": " def initialize(*args)\n if Facter.fact('ip6tables_version').value.match /1\\.3\\.\\d/\n raise ArgumentError, 'The ip6tables provider is not supported on version 1.3 of iptables'\n else\n super\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "void AnnotateFlushState(const char *file, int line){}", "label": 0, "label_name": "vulnerable"} -{"code": "func defaultLocation(x ast.Node) *ast.Location {\n\treturn ast.NewLocation([]byte(x.String()), \"\", 1, 1)\n}", "label": 0, "label_name": "vulnerable"} -{"code": "void lpc54xxxEthEventHandler(NetInterface *interface)\n{\n error_t error;\n\n //Packet received?\n if((ENET->DMA_CH[0].DMA_CHX_STAT & ENET_DMA_CH_DMA_CHX_STAT_RI_MASK) != 0)\n {\n //Clear interrupt flag\n ENET->DMA_CH[0].DMA_CHX_STAT = ENET_DMA_CH_DMA_CHX_STAT_RI_MASK;\n\n //Process all pending packets\n do\n {\n //Read incoming packet\n error = lpc54xxxEthReceivePacket(interface);\n\n //No more data in the receive buffer?\n } while(error != ERROR_BUFFER_EMPTY);\n }\n\n //Re-enable DMA interrupts\n ENET->DMA_CH[0].DMA_CHX_INT_EN = ENET_DMA_CH_DMA_CHX_INT_EN_NIE_MASK |\n ENET_DMA_CH_DMA_CHX_INT_EN_RIE_MASK | ENET_DMA_CH_DMA_CHX_INT_EN_TIE_MASK;\n}", "label": 1, "label_name": "safe"} -{"code": "next_line(struct archive_read *a,\n const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)\n{\n\tssize_t len;\n\tint quit;\n\t\n\tquit = 0;\n\tif (*avail == 0) {\n\t\t*nl = 0;\n\t\tlen = 0;\n\t} else\n\t\tlen = get_line_size(*b, *avail, nl);\n\t/*\n\t * Read bytes more while it does not reach the end of line.\n\t */\n\twhile (*nl == 0 && len == *avail && !quit) {\n\t\tssize_t diff = *ravail - *avail;\n\t\tsize_t nbytes_req = (*ravail+1023) & ~1023U;\n\t\tssize_t tested;\n\n\t\t/* Increase reading bytes if it is not enough to at least\n\t\t * new two lines. */\n\t\tif (nbytes_req < (size_t)*ravail + 160)\n\t\t\tnbytes_req <<= 1;\n\n\t\t*b = __archive_read_ahead(a, nbytes_req, avail);\n\t\tif (*b == NULL) {\n\t\t\tif (*ravail >= *avail)\n\t\t\t\treturn (0);\n\t\t\t/* Reading bytes reaches the end of file. */\n\t\t\t*b = __archive_read_ahead(a, *avail, avail);\n\t\t\tquit = 1;\n\t\t}\n\t\t*ravail = *avail;\n\t\t*b += diff;\n\t\t*avail -= diff;\n\t\ttested = len;/* Skip some bytes we already determinated. */\n\t\tlen = get_line_size(*b + len, *avail - len, nl);\n\t\tif (len >= 0)\n\t\t\tlen += tested;\n\t}\n\treturn (len);\n}", "label": 1, "label_name": "safe"} -{"code": " it \"returns true\" do\n cursor.get_more_op.cursor_id = 123\n cursor.more?.should be_true\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link = $this->getExternalTaskLink($task);\n\n $this->response->html($this->template->render('task_external_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label": 1, "label_name": "safe"} -{"code": " def primary?\n @primary\n end", "label": 1, "label_name": "safe"} -{"code": " public function queryGetArray($table, $data, $where, $extra = \"\", $inner = \"\")\n {\n $q = $this->prepareData($table, $data, $where, $extra, $inner);\n\n $query_id = $this->query($q);\n\n if (isset($this->query_id)) {\n $record = mysql_fetch_assoc($this->query_id) or die(mysql_error().\" | \".$q);\n } else {\n $this->oops(\"Invalid query_id: $this->query_id. Records could not be fetched.\");\n }\n\n $this->freeResult($query_id);\n\n return $record;\n }#-#queryGetRow()", "label": 1, "label_name": "safe"} -{"code": "check_visual_pos(void)\n{\n if (VIsual.lnum > curbuf->b_ml.ml_line_count)\n {\n\tVIsual.lnum = curbuf->b_ml.ml_line_count;\n\tVIsual.col = 0;\n\tVIsual.coladd = 0;\n }\n else\n {\n\tint len = (int)STRLEN(ml_get(VIsual.lnum));\n\n\tif (VIsual.col > len)\n\t{\n\t VIsual.col = len;\n\t VIsual.coladd = 0;\n\t}\n }\n}", "label": 1, "label_name": "safe"} -{"code": " public ActionResult GetHlsAudioSegmentLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string segmentId)\n {\n // TODO: Deprecate with new iOS app\n var file = segmentId + Path.GetExtension(Request.Path);\n file = Path.Combine(_serverConfigurationManager.GetTranscodePath(), file);\n\n return FileStreamResponseHelpers.GetStaticFileResult(file, MimeTypes.GetMimeType(file)!, false, HttpContext);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "int module_load(\n YR_SCAN_CONTEXT* context,\n YR_OBJECT* module_object,\n void* module_data,\n size_t module_data_size)\n{\n set_integer(1, module_object, \"constants.one\");\n set_integer(2, module_object, \"constants.two\");\n set_string(\"foo\", module_object, \"constants.foo\");\n set_string(\"\", module_object, \"constants.empty\");\n\n set_integer(1, module_object, \"struct_array[1].i\");\n\n set_integer(0, module_object, \"integer_array[%i]\", 0);\n set_integer(1, module_object, \"integer_array[%i]\", 1);\n set_integer(2, module_object, \"integer_array[%i]\", 2);\n set_integer(256, module_object, \"integer_array[%i]\", 256);\n\n set_string(\"foo\", module_object, \"string_array[%i]\", 0);\n set_string(\"bar\", module_object, \"string_array[%i]\", 1);\n set_string(\"baz\", module_object, \"string_array[%i]\", 2);\n\n set_sized_string(\"foo\\0bar\", 7, module_object, \"string_array[%i]\", 3);\n\n set_string(\"foo\", module_object, \"string_dict[%s]\", \"foo\");\n set_string(\"bar\", module_object, \"string_dict[\\\"bar\\\"]\");\n\n set_string(\"foo\", module_object, \"struct_dict[%s].s\", \"foo\");\n set_integer(1, module_object, \"struct_dict[%s].i\", \"foo\");\n\n return ERROR_SUCCESS;\n}", "label": 1, "label_name": "safe"} -{"code": " public function getToken()\n {\n if (isset($this->data['object']) && 'token' === $this->data['object']) {\n return $this->data['id'];\n }\n\n return;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected function getCustomFilter(array $project)\n {\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n if (empty($filter)) {\n throw new PageNotFoundException();\n }\n\n if ($filter['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n return $filter;\n }", "label": 1, "label_name": "safe"} -{"code": "void nfcmrvl_nci_unregister_dev(struct nfcmrvl_private *priv)\n{\n\tstruct nci_dev *ndev = priv->ndev;\n\n\tnci_unregister_device(ndev);\n\tif (priv->ndev->nfc_dev->fw_download_in_progress)\n\t\tnfcmrvl_fw_dnld_abort(priv);\n\n\tnfcmrvl_fw_dnld_deinit(priv);\n\n\tif (gpio_is_valid(priv->config.reset_n_io))\n\t\tgpio_free(priv->config.reset_n_io);\n\n\tnci_free_device(ndev);\n\tkfree(priv);\n}", "label": 1, "label_name": "safe"} -{"code": " void setInVmContextCreatedForTesting() { in_vm_context_created_ = true; }", "label": 1, "label_name": "safe"} -{"code": " it \"returns the number of matching document\" do\n users.insert(documents)\n users.find(scope: scope).count.should eq 2\n end", "label": 1, "label_name": "safe"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " it \"should allow requests that are whitelisted\" do\n get '/whitelisted'\n # second time will ensure cookie is set\n # first time around there is no cookie, so no profiling\n get '/whitelisted'\n last_response.headers['X-MiniProfiler-Ids'].should_not be_nil\n end", "label": 1, "label_name": "safe"} -{"code": " it 'has_ip_address absent ipaddress' do\n pp = <<-EOS\n $a = '128.0.0.1'\n $o = has_ip_address($a)\n notice(inline_template('has_ip_address is <%= @o.inspect %>'))\n EOS\n\n apply_manifest(pp, :catch_failures => true) do |r|\n expect(r.stdout).to match(/has_ip_address is false/)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,\n const void *p, size_t tail, int line)\n{\n\tconst char *b = (const char *)sst->sst_tab;\n\tconst char *e = ((const char *)p) + tail;\n\t(void)&line;\n\tif (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len)\n\t\treturn 0;\n\tDPRINTF((\"%d: offset begin %p < end %p || %\" SIZE_T_FORMAT \"u\"\n\t \" > %\" SIZE_T_FORMAT \"u [%\" SIZE_T_FORMAT \"u %\"\n\t SIZE_T_FORMAT \"u]\\n\", line, b, e, (size_t)(e - b),\n\t CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len));\n\terrno = EFTYPE;\n\treturn -1;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function setProxyInstantiator(InstantiatorInterface $proxyInstantiator)\n {\n $this->proxyInstantiator = $proxyInstantiator;\n }", "label": 0, "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, "label_name": "vulnerable"} -{"code": "compile_alt(labellist *ll, nfa *nf, node *n, int *pa, int *pb)\n{\n int i;\n int a, b;\n\n REQ(n, ALT);\n i = n->n_nchildren;\n REQN(i, 1);\n n = n->n_child;\n REQ(n, ITEM);\n compile_item(ll, nf, n, pa, pb);\n --i;\n n++;\n for (; --i >= 0; n++) {\n REQ(n, ITEM);\n compile_item(ll, nf, n, &a, &b);\n addnfaarc(nf, *pb, a, EMPTY);\n *pb = b;\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function hasCustomToString(obj) {\n return isFunction(obj.toString) && obj.toString !== toString;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def add_statistics_group\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n current_id = params[:current_id]\n\n unless params[:thetisBoxSelKeeper].nil?\n group_id = params[:thetisBoxSelKeeper].split(':').last\n end\n SqlHelper.validate_token([current_id, group_id])\n\n if group_id.blank?\n @group_ids = Research.get_statistics_groups\n render(:partial => 'ajax_statistics_groups', :layout => false)\n return\n end\n\n unless current_id.blank?\n Research.delete_statistics_group(current_id)\n end\n\n @group_ids = Research.add_statistics_group(group_id)\n\n render(:partial => 'ajax_statistics_groups', :layout => false)\n end", "label": 1, "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, "label_name": "safe"} -{"code": " public void testGetAndRemove() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\");\n headers.add(\"name2\", \"value2\", \"value3\");\n headers.add(\"name3\", \"value4\", \"value5\", \"value6\");\n\n assertThat(headers.getAndRemove(\"name1\", \"defaultvalue\")).isEqualTo(\"value1\");\n assertThat(headers.getAndRemove(\"name2\")).isEqualTo(\"value2\");\n assertThat(headers.getAndRemove(\"name2\")).isNull();\n assertThat(headers.getAllAndRemove(\"name3\")).containsExactly(\"value4\", \"value5\", \"value6\");\n assertThat(headers.size()).isZero();\n assertThat(headers.getAndRemove(\"noname\")).isNull();\n assertThat(headers.getAndRemove(\"noname\", \"defaultvalue\")).isEqualTo(\"defaultvalue\");\n }", "label": 0, "label_name": "vulnerable"} -{"code": " handler && handler(self, name, instructions, prompts);\n break;\n }\n default:\n self._debug\n && self._debug('Inbound: Received unexpected payload type 60');\n }\n },", "label": 1, "label_name": "safe"} -{"code": "{sWrapper:\"dataTables_wrapper form-inline dt-bootstrap\",sFilterInput:\"form-control input-sm\",sLengthSelect:\"form-control input-sm\",sProcessing:\"dataTables_processing panel panel-default\"});d.ext.renderer.pageButton.bootstrap=function(a,h,r,m,j,n){var o=new d.Api(a),s=a.oClasses,k=a.oLanguage.oPaginate,t=a.oLanguage.oAria.paginate||{},f,g,p=0,q=function(d,e){var l,h,i,c,m=function(a){a.preventDefault();!b(a.currentTarget).hasClass(\"disabled\")&&o.page()!=a.data.action&&o.page(a.data.action).draw(\"page\")};", "label": 0, "label_name": "vulnerable"} -{"code": "Tine.Addressbook.ContactGridPanel.countryRenderer = function(data) {\n data = Locale.getTranslationData('CountryList', data);\n return Ext.util.Format.htmlEncode(data);\n};", "label": 1, "label_name": "safe"} -{"code": "static void stellaris_enet_save(QEMUFile *f, void *opaque)\n{\n stellaris_enet_state *s = (stellaris_enet_state *)opaque;\n int i;\n\n qemu_put_be32(f, s->ris);\n qemu_put_be32(f, s->im);\n qemu_put_be32(f, s->rctl);\n qemu_put_be32(f, s->tctl);\n qemu_put_be32(f, s->thr);\n qemu_put_be32(f, s->mctl);\n qemu_put_be32(f, s->mdv);\n qemu_put_be32(f, s->mtxd);\n qemu_put_be32(f, s->mrxd);\n qemu_put_be32(f, s->np);\n qemu_put_be32(f, s->tx_fifo_len);\n qemu_put_buffer(f, s->tx_fifo, sizeof(s->tx_fifo));\n for (i = 0; i < 31; i++) {\n qemu_put_be32(f, s->rx[i].len);\n qemu_put_buffer(f, s->rx[i].data, sizeof(s->rx[i].data));\n\n }\n qemu_put_be32(f, s->next_packet);\n qemu_put_be32(f, s->rx_fifo_offset);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " protected function fopenWrapper($file, $detectType = false)\n {\n if (!is_string($file) && !is_resource($file)) {\n throw new HTTP_Request2_LogicException(\n \"Filename or file pointer resource expected\",\n HTTP_Request2_Exception::INVALID_ARGUMENT\n );\n }\n $fileData = array(\n 'fp' => is_string($file)? null: $file,\n 'type' => 'application/octet-stream',\n 'size' => 0\n );\n if (is_string($file)) {\n if (!($fileData['fp'] = @fopen($file, 'rb'))) {\n $error = error_get_last();\n throw new HTTP_Request2_LogicException(\n $error['message'], HTTP_Request2_Exception::READ_ERROR\n );\n }\n if ($detectType) {\n $fileData['type'] = self::detectMimeType($file);\n }\n }\n if (!($stat = fstat($fileData['fp']))) {\n throw new HTTP_Request2_LogicException(\n \"fstat() call failed\", HTTP_Request2_Exception::READ_ERROR\n );\n }\n $fileData['size'] = $stat['size'];\n\n return $fileData;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " void ComputeAsync(OpKernelContext* c, DoneCallback done) override {\n auto col_params = new CollectiveParams();\n auto done_with_cleanup = [col_params, done = std::move(done)]() {\n done();\n col_params->Unref();\n };\n OP_REQUIRES_OK_ASYNC(c,\n FillCollectiveParams(col_params, REDUCTION_COLLECTIVE,\n /*group_size*/ c->input(1),\n /*group_key*/ c->input(2),\n /*instance_key*/ c->input(3)),\n done);\n col_params->instance.shape = c->input(0).shape();\n col_params->merge_op = merge_op_.get();\n col_params->final_op = final_op_.get();\n VLOG(1) << \"CollectiveReduceV2 group_size \" << col_params->group.group_size\n << \" group_key \" << col_params->group.group_key << \" instance_key \"\n << col_params->instance.instance_key;\n // Allocate the output tensor, trying to reuse the input.\n Tensor* output = nullptr;\n OP_REQUIRES_OK_ASYNC(c,\n c->forward_input_or_allocate_output(\n {0}, 0, col_params->instance.shape, &output),\n done_with_cleanup);\n Run(c, col_params, std::move(done_with_cleanup));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function &getAll(&$dbh, $proposalId)\n {\n $sql = \"SELECT *, UNIX_TIMESTAMP(timestamp) AS timestamp FROM package_proposal_votes WHERE pkg_prop_id = \". $dbh->quoteSmart($proposalId) .\" ORDER BY timestamp ASC\";\n $res = $dbh->query($sql);\n if (DB::isError($res)) {\n return $res;\n }\n $votes = array();\n while ($set = $res->fetchRow(DB_FETCHMODE_ASSOC)) {\n $set['reviews'] = unserialize($set['reviews']);\n $votes[$set['user_handle']] = new ppVote($set);\n }\n return $votes;\n }", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " it 'should generate a puppi::ze define' do\n content = catalogue.resource('puppi::ze', 'php').send(:parameters)[:helper]\n content.should == \"myhelper\"\n end", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($this->_to_convert as $error) {\n\n $message = $this->getMessage($error['field'], $error['rule'], $error['fallback'], $error['meta']);\n\n // If there is no generic `message()` set or the translated message is not equal to generic message\n // we can continue without worrying about duplications\n if ($this->_message === null || ($message != $this->_message && !in_array($message, $this->_errors))) {\n $this->_errors[] = $message;\n continue;\n }\n\n // If this new error is the generic message AND it has not already been added, add it\n if ($message == $this->_message && !in_array($this->_message, $this->_errors)) {\n $this->_errors[] = $this->_message;\n }\n }", "label": 1, "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, "label_name": "safe"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "EditorUi.prototype.cellProperties={id:!0,value:!0,xmlValue:!0,vertex:!0,edge:!0,visible:!0,collapsed:!0,connectable:!0,parent:!0,children:!0,previous:!0,source:!0,target:!0,edges:!0,geometry:!0,style:!0,overlays:!0,mxObjectId:!0,mxTransient:!0};EditorUi.prototype.codec=new mxCodec;EditorUi.prototype.applyPatches=function(b,f,l,d,u){if(null!=f)for(var t=0;tsource, strlen($prefix)) . $section->id;\n if (call_user_func(array($ref->module, 'hasContent'))) {\n $oloc = expCore::makeLocation($ref->module, $ref->source);\n $nloc = expCore::makeLocation($ref->module, $src);\n if ($ref->module != \"container\") {\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc);\n } else {\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc, $section->id);\n }\n }\n }", "label": 1, "label_name": "safe"} -{"code": "\t\t\t\t$item = trim( $item );\n\t\t\t\tif ( strpos( $item, '|-' ) === 0 ) {\n\t\t\t\t\t$item = explode( '|-', $item, 2 );\n\t\t\t\t\tif ( count( $item ) == 2 ) {\n\t\t\t\t\t\t$item = $item[1];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$rowsKey[$index] = $item;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ( strlen( $item ) > 0 ) {\n\t\t\t\t\t$word = explode( \"\\n|\", $item );\n\t\t\t\t\tif ( isset( $word[0] ) && empty( $word[0] ) ) {\n\t\t\t\t\t\tarray_shift( $word );\n\t\t\t\t\t}\n\t\t\t\t\tif ( isset( $word[abs( $sortColumn ) - 1] ) ) {\n\t\t\t\t\t\t$test = trim( $word[abs( $sortColumn ) - 1] );\n\t\t\t\t\t\tif ( strpos( $test, '|' ) > 0 ) {\n\t\t\t\t\t\t\t$test = trim( explode( '|', $test )[1] );\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$rowsKey[$index] = $test;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$this->sort($rowsKey, $sortColumn);\n\t\t\t$newItems = [];\n\t\t\tforeach ( $rowsKey as $index => $val ) {\n\t\t\t\t$newItems[] = $items[$index];\n\t\t\t}\n\t\t\t$items = $newItems;\n\t\t}\n\n\t\treturn $this->listStart . $this->implodeItems( $items ) . $this->listEnd;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " recyclebin::sendToRecycleBin($loc, $parent);\n //FIXME if we delete the module & sectionref the module completely disappears\n// if (class_exists($secref->module)) {\n// $modclass = $secref->module;\n// //FIXME: more module/controller glue code\n// if (expModules::controllerExists($modclass)) {\n// $modclass = expModules::getControllerClassName($modclass);\n// $mod = new $modclass($loc->src);\n// $mod->delete_instance();\n// } else {\n// $mod = new $modclass();\n// $mod->deleteIn($loc);\n// }\n// }\n }\n// $db->delete('sectionref', 'section=' . $parent);\n $db->delete('section', 'parent=' . $parent);\n }", "label": 1, "label_name": "safe"} -{"code": "struct sock *inet_csk_clone_lock(const struct sock *sk,\n\t\t\t\t const struct request_sock *req,\n\t\t\t\t const gfp_t priority)\n{\n\tstruct sock *newsk = sk_clone_lock(sk, priority);\n\n\tif (newsk) {\n\t\tstruct inet_connection_sock *newicsk = inet_csk(newsk);\n\n\t\tnewsk->sk_state = TCP_SYN_RECV;\n\t\tnewicsk->icsk_bind_hash = NULL;\n\n\t\tinet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;\n\t\tinet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;\n\t\tinet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);\n\t\tnewsk->sk_write_space = sk_stream_write_space;\n\n\t\t/* listeners have SOCK_RCU_FREE, not the children */\n\t\tsock_reset_flag(newsk, SOCK_RCU_FREE);\n\n\t\tinet_sk(newsk)->mc_list = NULL;\n\n\t\tnewsk->sk_mark = inet_rsk(req)->ir_mark;\n\t\tatomic64_set(&newsk->sk_cookie,\n\t\t\t atomic64_read(&inet_rsk(req)->ir_cookie));\n\n\t\tnewicsk->icsk_retransmits = 0;\n\t\tnewicsk->icsk_backoff\t = 0;\n\t\tnewicsk->icsk_probes_out = 0;\n\n\t\t/* Deinitialize accept_queue to trap illegal accesses. */\n\t\tmemset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));\n\n\t\tsecurity_inet_csk_clone(newsk, req);\n\t}\n\treturn newsk;\n}", "label": 1, "label_name": "safe"} -{"code": "EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createSvgDataUri\");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedCssFonts\");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedExtFonts\");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,y,A,z,L,M,n,x,K,B){EditorUi.logEvent(\"SHOULD NOT BE CALLED: exportToCanvas\");", "label": 1, "label_name": "safe"} -{"code": " public function testHTMLFormsConfigDirective()\n {\n $this->config->set('HTML.Trusted', false);\n $this->config->set('HTML.Forms', true);\n\n $this->assertResult('
');\n }", "label": 1, "label_name": "safe"} -{"code": "\tescape: function(value) {\n\t\tif (isString(value))\n\t\t\treturn (\n\t\t\t\t\"'\" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + \"'\"\n\t\t\t);\n\t\tif (isNumber(value)) return value.toString();\n\t\tif (value === true) return \"true\";\n\t\tif (value === false) return \"false\";\n\t\tif (value === null) return \"null\";\n\t\tif (typeof value === \"undefined\") return \"undefined\";\n\n\t\tthrow $parseMinErr(\"esc\", \"IMPOSSIBLE\");\n\t},", "label": 1, "label_name": "safe"} -{"code": "win_goto(win_T *wp)\n{\n#ifdef FEAT_CONCEAL\n win_T\t*owp = curwin;\n#endif\n\n#ifdef FEAT_PROP_POPUP\n if (ERROR_IF_ANY_POPUP_WINDOW)\n\treturn;\n if (popup_is_popup(wp))\n {\n\temsg(_(e_not_allowed_to_enter_popup_window));\n\treturn;\n }\n#endif\n if (text_locked())\n {\n\tbeep_flush();\n\ttext_locked_msg();\n\treturn;\n }\n if (curbuf_locked())\n\treturn;\n\n if (wp->w_buffer != curbuf)\n\treset_VIsual_and_resel();\n else if (VIsual_active)\n\twp->w_cursor = curwin->w_cursor;\n\n#ifdef FEAT_GUI\n need_mouse_correct = TRUE;\n#endif\n win_enter(wp, TRUE);\n\n#ifdef FEAT_CONCEAL\n // Conceal cursor line in previous window, unconceal in current window.\n if (win_valid(owp) && owp->w_p_cole > 0 && !msg_scrolled)\n\tredrawWinline(owp, owp->w_cursor.lnum);\n if (curwin->w_p_cole > 0 && !msg_scrolled)\n\tneed_cursor_line_redraw = TRUE;\n#endif\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function getBundles()\n {\n return $this->bundles;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function manage() {\n expHistory::set('manageable', $this->params);\n \n // build out a SQL query that gets all the data we need and is sortable.\n $sql = 'SELECT b.*, c.title as companyname, f.expfiles_id as file_id ';\n $sql .= 'FROM '.DB_TABLE_PREFIX.'_banner b, '.DB_TABLE_PREFIX.'_companies c , '.DB_TABLE_PREFIX.'_content_expFiles f ';\n $sql .= 'WHERE b.companies_id = c.id AND (b.id = f.content_id AND f.content_type=\"banner\")';\n\t\t\n\t\t$page = new expPaginator(array(\n\t\t\t'model'=>'banner',\n\t\t\t'sql'=>$sql,\n\t\t\t'order'=>'title',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n\t\t\t'columns'=>array(\n gt('Title')=>'title',\n gt('Company')=>'companyname',\n gt('Impressions')=>'impressions',\n gt('Clicks')=>'clicks'\n )\n ));\n\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "q):mxscript(\"js/extensions.min.js\",q))};EditorUi.prototype.generatePlantUmlImage=function(c,e,g,k){function m(x,A,z){c1=x>>2;c2=(x&3)<<4|A>>4;c3=(A&15)<<2|z>>6;c4=z&63;r=\"\";r+=q(c1&63);r+=q(c2&63);r+=q(c3&63);return r+=q(c4&63)}function q(x){if(10>x)return String.fromCharCode(48+x);x-=10;if(26>x)return String.fromCharCode(65+x);x-=26;if(26>x)return String.fromCharCode(97+x);x-=26;return 0==x?\"-\":1==x?\"_\":\"?\"}var v=new XMLHttpRequest;v.open(\"GET\",(\"txt\"==e?PLANT_URL+\"/txt/\":\"png\"==e?PLANT_URL+\"/png/\":", "label": 0, "label_name": "vulnerable"} -{"code": "return ka}function B(){function fa(ta,ka){var Ja=mxResources.get(ta);null==Ja&&(Ja=ta.substring(0,1).toUpperCase()+ta.substring(1));18=Z.scrollHeight&&", "label": 0, "label_name": "vulnerable"} -{"code": "CoreBasicHandler::CoreBasicHandler(CoreNetwork *parent)\n : BasicHandler(parent),\n _network(parent)\n{\n connect(this, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),\n network(), SLOT(displayMsg(Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));\n\n connect(this, SIGNAL(putCmd(QString, const QList &, const QByteArray &)),\n network(), SLOT(putCmd(QString, const QList &, const QByteArray &)));\n\n connect(this, SIGNAL(putCmd(QString, const QList> &, const QByteArray &)),\n network(), SLOT(putCmd(QString, const QList> &, const QByteArray &)));\n\n connect(this, SIGNAL(putRawLine(const QByteArray &)),\n network(), SLOT(putRawLine(const QByteArray &)));\n}", "label": 1, "label_name": "safe"} -{"code": " protected function createEndNode($node, &$tokens) {\n $tokens[] = $this->factory->createEnd($node->tagName);\n }", "label": 1, "label_name": "safe"} -{"code": "bool jas_image_cmpt_domains_same(jas_image_t *image)\n{\n\tint cmptno;\n\tjas_image_cmpt_t *cmpt;\n\tjas_image_cmpt_t *cmpt0;\n\n\tcmpt0 = image->cmpts_[0];\n\tfor (cmptno = 1; cmptno < image->numcmpts_; ++cmptno) {\n\t\tcmpt = image->cmpts_[cmptno];\n\t\tif (cmpt->tlx_ != cmpt0->tlx_ || cmpt->tly_ != cmpt0->tly_ ||\n\t\t cmpt->hstep_ != cmpt0->hstep_ || cmpt->vstep_ != cmpt0->vstep_ ||\n\t\t cmpt->width_ != cmpt0->width_ || cmpt->height_ != cmpt0->height_) {\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n}", "label": 1, "label_name": "safe"} -{"code": "ast_for_async_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)\n{\n /* async_funcdef: ASYNC funcdef */\n REQ(n, async_funcdef);\n REQ(CHILD(n, 0), ASYNC);\n REQ(CHILD(n, 1), funcdef);\n\n return ast_for_funcdef_impl(c, CHILD(n, 1), decorator_seq,\n 1 /* is_async */);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};\n }\n return left;\n },", "label": 0, "label_name": "vulnerable"} -{"code": " public static function _date2timestamp( $datetime, $wtz=null ) {\r\n if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;\r\n if( !isset( $datetime['min'] )) $datetime['min'] = 0;\r\n if( !isset( $datetime['sec'] )) $datetime['sec'] = 0;\r\n if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty( $datetime['tz'] )))\r\n return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\r\n $output = $offset = 0;\r\n if( empty( $wtz )) {\r\n if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {\r\n $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;\r\n $wtz = 'UTC';\r\n }\r\n else\r\n $wtz = $datetime['tz'];\r\n }\r\n if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))\r\n $wtz = 'UTC';\r\n try {\r\n $strdate = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );\r\n $d = new DateTime( $strdate, new DateTimeZone( $wtz ));\r\n if( 0 != $offset ) // adjust for offset\r\n $d->modify( $offset.' seconds' );\r\n $output = $d->format( 'U' );\r\n unset( $d );\r\n }\r\n catch( Exception $e ) {\r\n $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\r\n }\r\n return $output;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n\n switch (input->type) { // Already know in/out types are same.\n case kTfLiteFloat32:\n return EvalImpl(context, node);\n case kTfLiteUInt8:\n return EvalImpl(context, node);\n case kTfLiteInt8:\n return EvalImpl(context, node);\n case kTfLiteInt16:\n return EvalImpl(context, node);\n default:\n context->ReportError(context, \"Type %d not currently supported.\",\n input->type);\n return kTfLiteError;\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testCheckWithDifferentArgSeparator()\n {\n $this->iniSet('arg_separator.output', '&');\n $signer = new UriSigner('foobar');\n\n $this->assertSame(\n 'http://example.com/foo?baz=bay&foo=bar&_hash=rIOcC%2FF3DoEGo%2FvnESjSp7uU9zA9S%2F%2BOLhxgMexoPUM%3D',\n $signer->sign('http://example.com/foo?foo=bar&baz=bay')\n );\n $this->assertTrue($signer->check($signer->sign('http://example.com/foo?foo=bar&baz=bay')));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def check_auth(params, request, session)\n if params.include?(\"check_auth_only\")\n return [200, \"{\\\"success\\\":true}\"]\n end\n return JSON.generate({\n 'success' => true,\n 'node_list' => get_token_node_list,\n })\nend", "label": 0, "label_name": "vulnerable"} -{"code": " function isPartOfDirectivePrologue(node) {\n const block = node.parent.parent;\n\n if (block.type !== \"Program\" && (block.type !== \"BlockStatement\" || !astUtils.isFunction(block.parent))) {\n return false;\n }\n\n // Check the node is at a prologue.\n for (let i = 0; i < block.body.length; ++i) {\n const statement = block.body[i];\n\n if (statement === node.parent) {\n return true;\n }\n if (!isDirective(statement)) {\n break;\n }\n }\n\n return false;\n }", "label": 1, "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, "label_name": "safe"} -{"code": " private static void validateName(String name) {\n if (!RE_NAME.matcher(name).matches()) {\n throw new IllegalArgumentException(String.format(\"Illegal character in name: '%s'.\", name));\n }\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public function test_AllowedAttributes_duplicate()\n {\n $this->config->set('HTML.AllowedElements', array('p', 'br'));\n $this->config->set('HTML.AllowedAttributes', 'p.style,p@style');\n $this->assertPurification_AllowedAttributes_local_p_style();\n }", "label": 1, "label_name": "safe"} -{"code": "function isString(value) {return typeof value === 'string';}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testReadsAnEmptyArrayWithReadWhenNothingCachedAtKey()\n {\n $this->assertEmpty($this->getStoreMetadata('/nothing'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic void destroy() {\n\t\tStringResourceLoader.clearRepositories();\n\n\t\t_classLoaderVelocityContexts.clear();\n\n\t\t_classLoaderVelocityContexts = null;\n\t\t_restrictedVelocityContext = null;\n\t\t_standardVelocityContext = null;\n\t\t_velocityEngine = null;\n\t\t_templateContextHelper = null;\n\t}", "label": 1, "label_name": "safe"} -{"code": " public function transform($attr, $config, $context)\n {\n if (isset($attr['dir'])) {\n return $attr;\n }\n $attr['dir'] = $config->get('Attr.DefaultTextDir');\n return $attr;\n }", "label": 1, "label_name": "safe"} -{"code": " public function assertPurification_ForbiddenAttributes_b_style()\n {\n $this->assertPurification(\n 'bi',\n 'bi');\n }", "label": 1, "label_name": "safe"} -{"code": " protected function getBazService()\n {\n $this->services['baz'] = $instance = new \\Baz();\n\n $instance->setFoo($this->get('foo_with_inline'));\n\n return $instance;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def self.get_tmpl_folder\n\n tmpl_folder = Folder.where(name: TMPL_ROOT).first\n\n if tmpl_folder.nil?\n\n ary = self.setup_tmpl_folder\n\n unless ary.nil? or ary.empty?\n tmpl_folder = ary[0]\n tmpl_system_folder = ary[1]\n tmpl_workflows_folder = ary[2]\n tmpl_local_folder = ary[3]\n tmpl_q_folder = ary[4]\n end\n\n else\n\n folders = Folder.where(\"parent_id=#{tmpl_folder.id}\").to_a\n unless folders.nil?\n folders.each do |child|\n case child.name\n when TMPL_SYSTEM\n tmpl_system_folder = child\n when TMPL_WORKFLOWS\n tmpl_workflows_folder = child\n when TMPL_LOCAL\n tmpl_local_folder = child\n when TMPL_RESEARCH\n tmpl_q_folder = child\n end\n end\n end\n end", "label": 1, "label_name": "safe"} -{"code": "\tpublic int decryptWithAd(byte[] ad, byte[] ciphertext,\n\t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n\t\t\tint length) throws ShortBufferException, BadPaddingException {\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 (length > space)\n\t\t\tthrow new ShortBufferException();\n\t\tif (plaintextOffset > plaintext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = plaintext.length - plaintextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the ciphertext 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(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (length < 16)\n\t\t\tNoise.throwBadTagException();\n\t\tint dataLen = length - 16;\n\t\tif (dataLen > space)\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tghash.update(ciphertext, ciphertextOffset, dataLen);\n\t\tghash.pad(ad != null ? ad.length : 0, dataLen);\n\t\tghash.finish(enciv, 0, 16);\n\t\tint temp = 0;\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\ttemp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);\n\t\tif ((temp & 0xFF) != 0)\n\t\t\tNoise.throwBadTagException();\n\t\tencryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);\n\t\treturn dataLen;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " it 'should install a fcgi-program file' do\n\n pp = <<-EOS\n include supervisord\n supervisord::fcgi_program { 'test':\n socket => 'tcp://localhost:1000',\n command => 'echo',\n priority => '100',\n environment => {\n 'HOME' => '/root',\n 'PATH' => '/bin',\n }\n }\n EOS\n\n expect(apply_manifest(pp).exit_code).to_not eq(1)\n expect(apply_manifest(pp).exit_code).to eq(0)\n end", "label": 0, "label_name": "vulnerable"} -{"code": "function reducer(result, arg)\n{\n arg = arg.split('=')\n\n // Get key node\n const keypath = arg.shift().split('.')\n\n // Get value\n let val = true\n if(arg.length)\n {\n val = arg.join('=').split(',')\n if(val.length === 1) val = val[0]\n }\n\n let key = keypath.shift()\n\n if(!keypath.length) return {...result, [key]: val}\n\n if(!result.hasOwnProperty(key)) result = {...result, [key]: {}}\n\n let newKey\n let newNode\n let node = result\n\n while(true)\n {\n newKey = keypath.shift()\n newNode = node[key]\n\n if(!keypath.length) break\n\n node = node[key] = {...newNode, [newKey]: newNode[newKey] || {}}\n key = newKey\n }\n\n // Store value\n node[key] = {...newNode, [newKey]: val}\n\n return result\n}", "label": 1, "label_name": "safe"} -{"code": " client.on('error', mustCall((err) => {\n cliError = err;\n assert.strictEqual(err.level, 'client-authentication');\n assert(/configured authentication methods failed/i.test(err.message),\n msg('Wrong error message'));\n })).on('close', mustCall(() => {", "label": 1, "label_name": "safe"} -{"code": " protected function validate()\n {\n // Special case:\n if ($this->n === '+0' || $this->n === '-0') {\n $this->n = '0';\n }\n if ($this->n === '0' && $this->unit === false) {\n return true;\n }\n if (!ctype_lower($this->unit)) {\n $this->unit = strtolower($this->unit);\n }\n if (!isset(HTMLPurifier_Length::$allowedUnits[$this->unit])) {\n return false;\n }\n // Hack:\n $def = new HTMLPurifier_AttrDef_CSS_Number();\n $result = $def->validate($this->n, false, false);\n if ($result === false) {\n return false;\n }\n $this->n = $result;\n return true;\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "sa=F.actions.get(\"resetView\");P=F.actions.get(\"fullscreen\");var Ga=F.actions.get(\"undo\"),Ka=F.actions.get(\"redo\"),Ma=B(\"\",Ga.funct,null,mxResources.get(\"undo\")+\" (\"+Ga.shortcut+\")\",Ga,Editor.undoImage),Ia=B(\"\",Ka.funct,null,mxResources.get(\"redo\")+\" (\"+Ka.shortcut+\")\",Ka,Editor.redoImage),Ea=B(\"\",P.funct,null,mxResources.get(\"fullscreen\"),P,Editor.fullscreenImage);if(null!=I){sa=function(){pa.style.display=null!=F.pages&&(\"0\"!=urlParams.pages||1MF);\n\n\treturn rc;\n}", "label": 1, "label_name": "safe"} -{"code": "char *path_name(struct strbuf *path, const char *name)\n{\n\tstruct strbuf ret = STRBUF_INIT;\n\tif (path)\n\t\tstrbuf_addbuf(&ret, path);\n\tstrbuf_addstr(&ret, name);\n\treturn strbuf_detach(&ret, NULL);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testRemoveDirWhenNotRequired()\n {\n $this->assertResult(\n 'Invalid value!',\n 'Invalid value!'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "static int ip_options_get_finish(struct net *net, struct ip_options **optp,\n\t\t\t\t struct ip_options *opt, int optlen)\n{\n\twhile (optlen & 3)\n\t\topt->__data[optlen++] = IPOPT_END;\n\topt->optlen = optlen;\n\tif (optlen && ip_options_compile(net, opt, NULL)) {\n\t\tkfree(opt);\n\t\treturn -EINVAL;\n\t}\n\tkfree(*optp);\n\t*optp = opt;\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_AllowedAttributes_local_discouragedSyntax()\n {\n $this->config->set('HTML.AllowedElements', array('p', 'br'));\n $this->config->set('HTML.AllowedAttributes', 'p.style');\n $this->assertPurification_AllowedAttributes_local_p_style();\n }", "label": 1, "label_name": "safe"} -{"code": "null,\"Error fetching folder items\")+(null!=Ca?\" (\"+Ca+\")\":\"\"));V=!1;P.stop()}})}}function L(N){J.className=J.className.replace(\"odCatSelected\",\"\");J=N;J.className+=\" odCatSelected\"}function C(N){V||(T=null,z(\"search\",null,null,null,N))}var D=\"\";null==e&&(e=I,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\"];\nQ[N.id]=N;localStorage.setItem(\"mxODPickerRecentList\",JSON.stringify(Q))}});D='
OneDrive
'+mxUtils.htmlEntities(mxResources.get(\"files\"))+'
'+mxUtils.htmlEntities(mxResources.get(\"recent\"))+'
'+mxUtils.htmlEntities(mxResources.get(\"shared\"))+'
'+", "label": 0, "label_name": "vulnerable"} -{"code": " public static function hasChildren($i) {\n global $sections;\n\n if (($i + 1) >= count($sections)) return false;\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct($type)\n {\n $this->type = $type;\n }", "label": 1, "label_name": "safe"} -{"code": "\t\trtrim = function(str) {\n\t\t\treturn str.replace(/\\s+$/, '');\n\t\t},", "label": 1, "label_name": "safe"} -{"code": " public function setUp()\n {\n parent::setUp();\n $this->obj = new HTMLPurifier_Strategy_FixNesting();\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct() {\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function getFile($path = '', $root = null) {\r\n\r\n if (is_null($root)) $root = $this->root;\r\n $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));\r\n $result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/'));\r\n return $result['body'];\r\n\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_create_withDecoratorObject()\n {\n $this->factory->addDecorator(new HTMLPurifier_DefinitionCache_Decorator_Memory());\n $cache = $this->factory->create('Test', $this->config);\n $cache_real = new HTMLPurifier_DefinitionCache_Decorator_Memory();\n $ser = new HTMLPurifier_DefinitionCache_Serializer('Test');\n $cache_real = $cache_real->decorate($ser);\n $this->assertEqual($cache, $cache_real);\n }", "label": 1, "label_name": "safe"} -{"code": " public function load($id)\n {\n try {\n $select = $this->zdb->select(self::TABLE, 't');\n $select->where([self::PK => $id]);\n $select->join(\n array('a' => PREFIX_DB . Adherent::TABLE),\n 't.' . Adherent::PK . '=a.' . Adherent::PK,\n array()\n );\n\n //restrict query on current member id if he's not admin nor staff member\n if (!$this->login->isAdmin() && !$this->login->isStaff() && !$this->login->isGroupManager()) {\n if (!$this->login->isLogged()) {\n Analog::log(\n 'Non-logged-in users cannot load transaction id `' . $id,\n Analog::ERROR\n );\n return false;\n }\n $select->where\n ->nest()\n ->equalTo('a.' . Adherent::PK, $this->login->id)\n ->or\n ->equalTo('a.parent_id', $this->login->id)\n ->unnest()\n ->and\n ->equalTo('t.' . self::PK, $id)\n ;\n } else {\n $select->where->equalTo(self::PK, $id);\n }\n\n $results = $this->zdb->execute($select);\n $result = $results->current();\n if ($result) {\n $this->loadFromRS($result);\n return true;\n } else {\n Analog::log(\n 'Transaction id `' . $id . '` does not exists',\n Analog::WARNING\n );\n return false;\n }\n } catch (Throwable $e) {\n Analog::log(\n 'Cannot load transaction form id `' . $id . '` | ' .\n $e->getMessage(),\n Analog::WARNING\n );\n throw $e;\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public function testBdoAlternateDefaultDir()\n {\n $this->config->set('Attr.DefaultTextDir', 'rtl');\n $this->assertResult(\n 'Go right.',\n 'Go right.'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "document.createElement(\"tr\");ja.className=\"gePropHeader\";var Ba=document.createElement(\"th\");Ba.className=\"gePropHeaderCell\";var Da=document.createElement(\"img\");Da.src=Sidebar.prototype.expandedImage;Da.style.verticalAlign=\"middle\";Ba.appendChild(Da);mxUtils.write(Ba,mxResources.get(\"property\"));ja.style.cursor=\"pointer\";var qa=function(){var za=va.querySelectorAll(\".gePropNonHeaderRow\");if(Z.editorUi.propertiesCollapsed){Da.src=Sidebar.prototype.collapsedImage;var ta=\"none\";for(var ka=u.childNodes.length-\n1;0<=ka;ka--)try{var oa=u.childNodes[ka],sa=oa.nodeName.toUpperCase();\"INPUT\"!=sa&&\"SELECT\"!=sa||u.removeChild(oa)}catch(ya){}}else Da.src=Sidebar.prototype.expandedImage,ta=\"\";for(ka=0;kagetTask();\n $link = $this->getInternalTaskLink($task);\n\n $this->response->html($this->template->render('task_internal_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label": 1, "label_name": "safe"} -{"code": "function trim(str) {\n return str.replace(/^\\s*/, '').replace(/\\s*$/, '');\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def read_lines(filename, selector)\n if selector\n IO.foreach(filename).select.with_index(1, &selector)\n else\n URI.open(filename, &:read)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def fetch_file(self, in_path, out_path):\n ''' fetch a file from chroot to local '''\n\n vvv(\"FETCH %s TO %s\" % (in_path, out_path), host=self.chroot)\n\n try:\n p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE), None)\n except OSError:\n raise errors.AnsibleError(\"chroot connection requires dd command in the jail\")\n\n with open(out_path, 'wb+') as out_file:\n try:\n for chunk in p.stdout.read(BUFSIZE):\n out_file.write(chunk)\n except:\n traceback.print_exc()\n raise errors.AnsibleError(\"failed to transfer file %s to %s\" % (in_path, out_path))\n stdout, stderr = p.communicate()\n if p.returncode != 0:\n raise errors.AnsibleError(\"failed to transfer file %s to %s:\\n%s\\n%s\" % (in_path, out_path, stdout, stderr))", "label": 1, "label_name": "safe"} -{"code": "\tprivate static async Task ResponseFarmingBlacklistAdd(EAccess access, string botNames, string targetAppIDs) {\n\t\tif (!Enum.IsDefined(access)) {\n\t\t\tthrow new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(botNames)) {\n\t\t\tthrow new ArgumentNullException(nameof(botNames));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(targetAppIDs)) {\n\t\t\tthrow new ArgumentNullException(nameof(targetAppIDs));\n\t\t}\n\n\t\tHashSet? bots = Bot.GetBots(botNames);\n\n\t\tif ((bots == null) || (bots.Count == 0)) {\n\t\t\treturn access >= EAccess.Owner ? FormatStaticResponse(string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)) : null;\n\t\t}\n\n\t\tIList results = await Utilities.InParallel(bots.Select(bot => Task.Run(() => bot.Commands.ResponseFarmingBlacklistAdd(access, targetAppIDs)))).ConfigureAwait(false);\n\n\t\tList responses = new(results.Where(static result => !string.IsNullOrEmpty(result))!);\n\n\t\treturn responses.Count > 0 ? string.Join(Environment.NewLine, responses) : null;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "p&&I[T].getAttribute(\"data-font-src\")!=C&&I[T].setAttribute(\"data-font-src\",C)}};var n=Graph.prototype.isFastZoomEnabled;Graph.prototype.isFastZoomEnabled=function(){return n.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 p=JSON.parse(decodeURIComponent(urlParams.vars));if(null!=p)for(var C in p)this.globalVars[C]=\np[C]}catch(I){null!=window.console&&console.log(\"Error in vars URL parameter: \"+I)}};Graph.prototype.getExportVariables=function(){return null!=this.globalVars?mxUtils.clone(this.globalVars):{}};var x=Graph.prototype.getGlobalVariable;Graph.prototype.getGlobalVariable=function(p){var C=x.apply(this,arguments);null==C&&null!=this.globalVars&&(C=this.globalVars[p]);return C};Graph.prototype.getDefaultStylesheet=function(){if(null==this.defaultStylesheet){var p=this.themes[\"default-style2\"];this.defaultStylesheet=", "label": 1, "label_name": "safe"} -{"code": "void trustedEnclaveInit(uint64_t _logLevel) {\n CALL_ONCE\n LOG_INFO(__FUNCTION__);\n\n globalLogLevel_ = _logLevel;\n\n oc_realloc_func = &reallocate_function;\n oc_free_func = &free_function;\n\n LOG_INFO(\"Setting memory functions\");\n\n mp_get_memory_functions(NULL, &gmp_realloc_func, &gmp_free_func);\n mp_set_memory_functions(NULL, oc_realloc_func, oc_free_func);\n\n LOG_INFO(\"Calling enclave init\");\n\n\n enclave_init();\n\n\n LOG_INFO(\"Reading random\");\n\n globalRandom = calloc(32,1);\n\n int ret = sgx_read_rand(globalRandom, 32);\n\n if(ret != SGX_SUCCESS)\n {\n LOG_ERROR(\"sgx_read_rand failed. Aboring enclave.\");\n abort();\n }\n\n LOG_INFO(\"Successfully inited enclave. Signed enclave version:\" SIGNED_ENCLAVE_VERSION );\n#ifndef SGX_DEBUG\n LOG_INFO(\"SECURITY WARNING: sgxwallet is running in INSECURE DEBUG MODE! NEVER USE IN PRODUCTION!\");\n#endif\n\n#if SGX_DEBUG != 0\n LOG_INFO(\"SECURITY WARNING: sgxwallet is running in INSECURE DEBUG MODE! NEVER USE IN PRODUCTION!\");\n#endif\n\n#if SGX_MODE == SIM\n LOG_INFO(\"SECURITY WARNING: sgxwallet is running in INSECURE SIMULATION MODE! NEVER USE IN PRODUCTION!\");\n#endif\n\n\n\n\n\n\n}", "label": 1, "label_name": "safe"} -{"code": "static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n\t\t\tstruct msghdr *msg, size_t len, int noblock,\n\t\t\tint flags, int *addr_len)\n{\n\tstruct sk_buff *skb = NULL;\n\tstruct sockaddr_pn sa;\n\tint rval = -EOPNOTSUPP;\n\tint copylen;\n\n\tif (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|\n\t\t\tMSG_CMSG_COMPAT))\n\t\tgoto out_nofree;\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &rval);\n\tif (skb == NULL)\n\t\tgoto out_nofree;\n\n\tpn_skb_get_src_sockaddr(skb, &sa);\n\n\tcopylen = skb->len;\n\tif (len < copylen) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopylen = len;\n\t}\n\n\trval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);\n\tif (rval) {\n\t\trval = -EFAULT;\n\t\tgoto out;\n\t}\n\n\trval = (flags & MSG_TRUNC) ? skb->len : copylen;\n\n\tif (msg->msg_name != NULL) {\n\t\tmemcpy(msg->msg_name, &sa, sizeof(sa));\n\t\t*addr_len = sizeof(sa);\n\t}\n\nout:\n\tskb_free_datagram(sk, skb);\n\nout_nofree:\n\treturn rval;\n}", "label": 1, "label_name": "safe"} -{"code": " public function testNestedChameleonRemoveBlockInNodeWithInlineContent()\n {\n $this->assertResult(\n '

Not allowed!

',\n '

Not allowed!

'\n );\n }", "label": 1, "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, "label_name": "safe"} -{"code": "this.graph.isMouseDown=!0;x.hoverIcons.reset();mxEvent.consume(H)})))};var P=mxVertexHandler.prototype.redrawHandles;mxVertexHandler.prototype.redrawHandles=function(){P.apply(this,arguments);null!=this.moveHandle&&(this.moveHandle.style.left=this.state.x+this.state.width+(40>this.state.width?10:0)+2+\"px\",this.moveHandle.style.top=this.state.y+this.state.height+(40>this.state.height?10:0)+2+\"px\")};var K=mxVertexHandler.prototype.setHandlesVisible;mxVertexHandler.prototype.setHandlesVisible=function(H){K.apply(this,\narguments);null!=this.moveHandle&&(this.moveHandle.style.display=H?\"\":\"none\")};var F=mxVertexHandler.prototype.destroy;mxVertexHandler.prototype.destroy=function(H,S){F.apply(this,arguments);null!=this.moveHandle&&(this.moveHandle.parentNode.removeChild(this.moveHandle),this.moveHandle=null)}};if(\"undefined\"!==typeof Sidebar){var f=Sidebar.prototype.createAdvancedShapes;Sidebar.prototype.createAdvancedShapes=function(){var c=f.apply(this,arguments),m=this.graph;return c.concat([this.addEntry(\"tree container\",", "label": 0, "label_name": "vulnerable"} -{"code": " 'trace' => $exception->getTrace(),\n );\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static int proc_connectinfo(struct usb_dev_state *ps, void __user *arg)\n{\n\tstruct usbdevfs_connectinfo ci;\n\n\tmemset(&ci, 0, sizeof(ci));\n\tci.devnum = ps->dev->devnum;\n\tci.slow = ps->dev->speed == USB_SPEED_LOW;\n\n\tif (copy_to_user(arg, &ci, sizeof(ci)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": " private function filterHost($host)\n {\n if (!is_string($host)) {\n throw new \\InvalidArgumentException('Host must be a string');\n }\n\n return strtolower($host);\n }", "label": 1, "label_name": "safe"} -{"code": " public function params()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {\n $this->create();\n return;\n }\n\n $action = $this->actionManager->getAction($values['action_name']);\n $action_params = $action->getActionRequiredParameters();\n\n if (empty($action_params)) {\n $this->doCreation($project, $values + array('params' => array()));\n }\n\n $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());\n unset($projects_list[$project['id']]);\n\n $this->response->html($this->template->render('action_creation/params', array(\n 'values' => $values,\n 'action_params' => $action_params,\n 'columns_list' => $this->columnModel->getList($project['id']),\n 'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),\n 'projects_list' => $projects_list,\n 'colors_list' => $this->colorModel->getList(),\n 'categories_list' => $this->categoryModel->getList($project['id']),\n 'links_list' => $this->linkModel->getList(0, false),\n 'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'swimlane_list' => $this->swimlaneModel->getList($project['id']),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tbutton: function(elem){\n\t\t\treturn \"button\" === elem.type || elem.nodeName.toUpperCase() === \"BUTTON\";\n\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " getter: function (path, safe) {\n var parts = normalizePath(path)\n return (\n getCache.get(path) ||\n getCache.set(path, function getter(data) {\n var index = 0,\n len = parts.length\n while (index < len) {\n if (data != null || !safe) data = data[parts[index++]]\n else return\n }\n return data\n })\n )\n },", "label": 1, "label_name": "safe"} -{"code": "void dhcpAddOption(DhcpMessage *message, uint8_t optionCode,\n const void *optionValue, size_t optionLen)\n{\n size_t n;\n DhcpOption *option;\n\n //Point to the very first option\n n = 0;\n\n //Parse DHCP options\n while(1)\n {\n //Point to the current option\n option = (DhcpOption *) (message->options + n);\n\n //End option detected?\n if(option->code == DHCP_OPT_END)\n break;\n\n //Jump to the next option\n n += sizeof(DhcpOption) + option->length;\n }\n\n //Sanity check\n if(optionLen <= UINT8_MAX)\n {\n //Point to the buffer where the option is to be written\n option = (DhcpOption *) (message->options + n);\n\n //Option code\n option->code = optionCode;\n //Option length\n option->length = (uint8_t) optionLen;\n //Option value\n osMemcpy(option->value, optionValue, optionLen);\n\n //Jump to the next option\n n += sizeof(DhcpOption) + option->length;\n\n //Point to the buffer where the option is to be written\n option = (DhcpOption *) (message->options + n);\n\n //Always terminate the options field with 255\n option->code = DHCP_OPT_END;\n }\n}", "label": 1, "label_name": "safe"} -{"code": " if(!XmlHelpers.KnownSigningAlgorithms.Contains(value))\n {\n throw new ArgumentException(\"The signing algorithm \" + value +\n \" is unknown or not supported by the current .NET Framework.\");\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tpublic function renameRemote($oldName, $newName)\n\t\t{\n\t\t\t$this->run('remote', 'rename', $oldName, $newName);\n\t\t\treturn $this;\n\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testSupports()\n {\n $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator());\n\n $this->assertTrue($loader->supports('foo.yml'), '->supports() returns true if the resource is loadable');\n $this->assertTrue($loader->supports('foo.yaml'), '->supports() returns true if the resource is loadable');\n $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($nodes as $node) {\r\n if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {\r\n if ($node->active == 1) {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;\r\n } else {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';\r\n }\r\n $ar[$node->id] = $text;\r\n foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {\r\n $ar[$id] = $text;\r\n }\r\n }\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function routePostProvider()\n {\n return [\n ['/api/articles/', 1, 'articles', 'post', false],\n ['/api/v1/articles/', 1, 'articles', 'post', false],\n ['/api/v2/articles/', 2, 'articles', 'post', false],\n ['/api/articles/5', 1, 'articles', 'post', 5],\n ['/api/v1/articles/5', 1, 'articles', 'post', 5],\n ['/api/v2/articles/5', 2, 'articles', 'post', 5],\n ];\n }", "label": 0, "label_name": "vulnerable"} -{"code": " disconnect(reason) {\n const pktLen = 1 + 4 + 4 + 4;\n // We don't use _packetRW.write.* here because we need to make sure that\n // we always get a full packet allocated because this message can be sent\n // at any time -- even during a key exchange\n let p = this._packetRW.write.allocStartKEX;\n const packet = this._packetRW.write.alloc(pktLen, true);\n const end = p + pktLen;\n\n if (!VALID_DISCONNECT_REASONS.has(reason))\n reason = DISCONNECT_REASON.PROTOCOL_ERROR;\n\n packet[p] = MESSAGE.DISCONNECT;\n writeUInt32BE(packet, reason, ++p);\n packet.fill(0, p += 4, end);\n\n this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`);\n sendPacket(this, this._packetRW.write.finalize(packet, true), true);\n }", "label": 1, "label_name": "safe"} -{"code": "Runnable.prototype.resetTimeout = function(){\n var self = this;\n var ms = this.timeout() || 1e9;\n\n this.clearTimeout();\n this.timer = setTimeout(function(){\n self.callback(new Error('timeout of ' + ms + 'ms exceeded'));\n self.timedOut = true;\n }, ms);\n};", "label": 0, "label_name": "vulnerable"} -{"code": " def create\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n @address = Address.new(params.require(:address).permit(Address::PERMIT_BASE))\n\n @address = AddressbookHelper.arrange_per_scope(@address, @login_user, params[:scope], params[:groups], params[:teams])\n if @address.nil?\n flash[:notice] = t('msg.need_to_be_owner')\n redirect_to(:controller => 'desktop', :action => 'show')\n return\n end\n\n begin\n @address.save!\n rescue\n render(:controller => 'addressbook', :action => 'edit', :layout => (!request.xhr?))\n return\n end\n\n flash[:notice] = t('msg.register_success')\n\n if request.xhr?\n render(:partial => 'common/flash_notice', :layout => false)\n else\n list\n render(:action => 'list')\n end\n end", "label": 1, "label_name": "safe"} -{"code": "static void ptrace_hbptriggered(struct perf_event *bp, int unused,\n\t\t\t\t struct perf_sample_data *data,\n\t\t\t\t struct pt_regs *regs)\n{\n\tstruct arch_hw_breakpoint *bkpt = counter_arch_bp(bp);\n\tlong num;\n\tint i;\n\tsiginfo_t info;\n\n\tfor (i = 0; i < ARM_MAX_HBP_SLOTS; ++i)\n\t\tif (current->thread.debug.hbp[i] == bp)\n\t\t\tbreak;\n\n\tnum = (i == ARM_MAX_HBP_SLOTS) ? 0 : ptrace_hbp_idx_to_num(i);\n\n\tinfo.si_signo\t= SIGTRAP;\n\tinfo.si_errno\t= (int)num;\n\tinfo.si_code\t= TRAP_HWBKPT;\n\tinfo.si_addr\t= (void __user *)(bkpt->trigger);\n\n\tforce_sig_info(SIGTRAP, &info, current);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def allowed_tokens\n raise NotImplementedError.new(\"allowed_tokens is not implemented\")\n end", "label": 1, "label_name": "safe"} -{"code": " it \"doesn't raise an error if the string is equal to the min length\" do\n scope.function_validate_slength(['input', 10, 5])\n end", "label": 0, "label_name": "vulnerable"} -{"code": "!1;null!=H&&(S=\"1\"==y.getCurrentCellStyle(H).treeMoving);return S}function t(H){var S=!1;null!=H&&(H=A.getParent(H),S=y.view.getState(H),S=\"tree\"==(null!=S?S.style:y.getCellStyle(H)).containerType);return S}function D(H){var S=!1;null!=H&&(H=A.getParent(H),S=y.view.getState(H),y.view.getState(H),S=null!=(null!=S?S.style:y.getCellStyle(H)).childLayout);return S}function c(H){H=y.view.getState(H);if(null!=H){var S=y.getIncomingTreeEdges(H.cell);if(0(bs3()) ? $sorted : json_encode($sorted),\n \"top\"=>$top\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n\n try {\n\n Path path = ioService.get(new URI(request.getParameter(\"path\")));\n\n byte[] bytes = ioService.readAllBytes(path);\n\n response.setHeader(\"Content-Disposition\",\n String.format(\"attachment; filename=%s;\", path.getFileName().toString()));\n\n response.setContentType(\"application/octet-stream\");\n\n response.getOutputStream().write(\n bytes,\n 0,\n bytes.length);\n\n } catch (URISyntaxException e) {\n logger.error(\"Failed to download a file.\", e);\n }\n\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def aesEncrypt(data, key):\n cipher = AES.new(key)\n\n data = data + (\" \" * (16 - (len(data) % 16)))\n return cipher.encrypt(data)", "label": 0, "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, "label_name": "vulnerable"} -{"code": "\tfunction lockTable($table,$lockType=\"WRITE\") {\n $sql = \"LOCK TABLES `\" . $this->prefix . \"$table` $lockType\";\n \n $res = mysqli_query($this->connection, $sql); \n return $res;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " static function description() {\n return \"Manage events and schedules, and optionally publish them.\";\n }", "label": 1, "label_name": "safe"} -{"code": "NO_INLINE JsVar *jspeFactorDelete() {\n JSP_ASSERT_MATCH(LEX_R_DELETE);\n JsVar *parent = 0;\n JsVar *a = jspeFactorMember(jspeFactor(), &parent);\n JsVar *result = 0;\n if (JSP_SHOULD_EXECUTE) {\n bool ok = false;\n if (jsvIsName(a) && !jsvIsNewChild(a)) {\n // if no parent, check in root?\n if (!parent && jsvIsChild(execInfo.root, a))\n parent = jsvLockAgain(execInfo.root);\n\n#ifdef DEBUG\n if (jsvHasChildren(parent)) assert(jsvIsChild(parent, a));\n#endif\n if (jsvHasChildren(parent) && jsvIsChild(parent, a)) {\n // else remove properly.\n /* we use jsvIsChild here just in case. delete probably isn't called\n that often so it pays to be safe */\n if (jsvIsArray(parent)) {\n // For arrays, we must make sure we don't change the length\n JsVarInt l = jsvGetArrayLength(parent);\n jsvRemoveChild(parent, a);\n jsvSetArrayLength(parent, l, false);\n } else {\n jsvRemoveChild(parent, a);\n }\n ok = true;\n }\n }\n\n result = jsvNewFromBool(ok);\n }\n jsvUnLock2(a, parent);\n return result;\n}", "label": 1, "label_name": "safe"} -{"code": " def testSparseCountSparseOutputBadNumberOfValues(self):\n indices = [[0, 0], [0, 1], [1, 0]]\n values = [1, 1, 1, 10]\n weights = [1, 2, 4, 6]\n dense_shape = [2, 3]\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n \"Number of values must match first dimension of indices\"):\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, "label_name": "safe"} -{"code": " public function setUp()\n {\n parent::setUp();\n $this->obj = new HTMLPurifier_ChildDef_Required('dt | dd');\n }", "label": 1, "label_name": "safe"} -{"code": " $scope.removeAllNodes = function(foreignSource) {\n bootbox.confirm('Are you sure you want to remove all the nodes from ' + _.escape(foreignSource) + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.removeAllNodesFromRequisition(foreignSource).then(\n function() { // success\n growl.success('All the nodes from ' + _.escape(foreignSource) + ' have been removed, and the requisition has been synchronized.');\n var req = $scope.requisitionsData.getRequisition(foreignSource);\n req.reset();\n },\n $scope.errorHandler\n );\n }\n });\n };", "label": 1, "label_name": "safe"} -{"code": "\tpublic function isAllowedFilename($filename){\n\t\t$allow_array = array(\n\t\t\t'.jpg','.jpeg','.png','.bmp','.gif','.ico','.webp',\n\t\t\t'.mp3','.wav','.mp4','.mov','.flac','.mkv',\n\t\t\t'.zip','.tar','.gz','.tgz','.ipa','.apk','.rar','.iso',\n\t\t\t'.pdf','.epub','.xps','.doc','.docx','.wps',\n\t\t\t'.ppt','.pptx','.xls','.xlsx','.txt','.psd','.csv',\n\t\t\t'.cer','.ppt','.pub','.json','.css',\n\t\t) ;\n\n\t\t$ext = strtolower(substr($filename,strripos($filename,'.')) ); //\u83b7\u53d6\u6587\u4ef6\u6269\u5c55\u540d\uff08\u8f6c\u4e3a\u5c0f\u5199\u540e\uff09\n\t\tif(in_array( $ext , $allow_array ) ){\n\t\t\treturn true ;\n\t\t}\n\t\treturn false;\n\t}", "label": 1, "label_name": "safe"} -{"code": " $arcs['create']['application/x-rar'] = array('cmd' => ELFINDER_RAR_PATH, 'argc' => 'a -inul' . (defined('ELFINDER_RAR_MA4') && ELFINDER_RAR_MA4? ' -ma4' : '') . ' --', 'ext' => 'rar');", "label": 1, "label_name": "safe"} -{"code": "ctcompare(const char *a,\t\t/* I - First string */\n const char *b)\t\t/* I - Second string */\n{\n int\tresult = 0;\t\t\t/* Result */\n\n\n while (*a && *b)\n {\n result |= *a ^ *b;\n a ++;\n b ++;\n }\n\n /*\n * The while loop finishes when *a == '\\0' or *b == '\\0'\n * so after the while loop either both *a and *b == '\\0',\n * or one points inside a string, so when we apply logical OR on *a,\n * *b and result, we get a non-zero return value if the compared strings don't match.\n */\n\n return (result | *a | *b);\n}", "label": 1, "label_name": "safe"} -{"code": " public function initFromUrl($url)\n {\n if ($data = @file_get_contents($url)) {\n return $this->initFromBinary($data);\n }\n\n throw new \\Intervention\\Image\\Exception\\NotReadableException(\n \"Unable to init from given url (\".$url.\").\"\n );\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getRequestType()\n {\n return $this->requestType;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function onSuiteEnd(PHPT_Suite $suite)\n {\n //$this->reporter->paintGroupEnd('PHPT Suite');\n }", "label": 1, "label_name": "safe"} -{"code": " public AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException,\n SearchServiceDatabaseException {\n EntityManager em = null;\n try {\n em = emf.createEntityManager();\n SearchEntity entity = getSearchEntity(mediaPackageId, em);\n if (entity == null) {\n throw new NotFoundException(\"Could not found media package with ID \" + mediaPackageId);\n }\n if (entity.getAccessControl() == null) {\n return null;\n } else {\n return AccessControlParser.parseAcl(entity.getAccessControl());\n }\n } catch (NotFoundException e) {\n throw e;\n } catch (Exception e) {\n logger.error(\"Could not retrieve ACL {}: {}\", mediaPackageId, e.getMessage());\n throw new SearchServiceDatabaseException(e);\n } finally {\n em.close();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static void __sock_release(struct socket *sock, struct inode *inode)\n{\n\tif (sock->ops) {\n\t\tstruct module *owner = sock->ops->owner;\n\n\t\tif (inode)\n\t\t\tinode_lock(inode);\n\t\tsock->ops->release(sock);\n\t\tif (inode)\n\t\t\tinode_unlock(inode);\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": 1, "label_name": "safe"} -{"code": " def receivePing():\n vrequest = request.form['id']\n db.sentences_victim('report_online', [vrequest])\n return json.dumps({'status' : 'OK', 'vId' : vrequest});", "label": 0, "label_name": "vulnerable"} -{"code": "int __gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n{\n\tint error;\n\tint len;\n\tchar *data;\n\tconst char *name = gfs2_acl_name(type);\n\n\tif (acl && acl->a_count > GFS2_ACL_MAX_ENTRIES(GFS2_SB(inode)))\n\t\treturn -E2BIG;\n\n\tif (type == ACL_TYPE_ACCESS) {\n\t\tumode_t mode = inode->i_mode;\n\n\t\terror = posix_acl_equiv_mode(acl, &mode);\n\t\tif (error < 0)\n\t\t\treturn error;\n\n\t\tif (error == 0)\n\t\t\tacl = NULL;\n\n\t\tif (mode != inode->i_mode) {\n\t\t\tinode->i_mode = mode;\n\t\t\tmark_inode_dirty(inode);\n\t\t}\n\t}\n\n\tif (acl) {\n\t\tlen = posix_acl_to_xattr(&init_user_ns, acl, NULL, 0);\n\t\tif (len == 0)\n\t\t\treturn 0;\n\t\tdata = kmalloc(len, GFP_NOFS);\n\t\tif (data == NULL)\n\t\t\treturn -ENOMEM;\n\t\terror = posix_acl_to_xattr(&init_user_ns, acl, data, len);\n\t\tif (error < 0)\n\t\t\tgoto out;\n\t} else {\n\t\tdata = NULL;\n\t\tlen = 0;\n\t}\n\n\terror = __gfs2_xattr_set(inode, name, data, len, 0, GFS2_EATYPE_SYS);\n\tif (error)\n\t\tgoto out;\n\tset_cached_acl(inode, type, acl);\nout:\n\tkfree(data);\n\treturn error;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public void annotatedSubClassExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))\n .containsExactlyInAnyOrder(\n FAILED_RESULT,\n FAILED_RESULT+\"subclass\"\n );\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tthis.enabled = function() {\n\t\treturn node.is(':visible') && enabled;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " fetch: function () {\n var data = Dep.prototype.fetch.call(this);\n data.translatedOptions = {};\n (data[this.name] || []).forEach(function (value) {\n var valueInternal = value.replace(/\"/g, '\\\\\"');\n data.translatedOptions[value] = this.$el.find('input[data-name=\"translatedValue\"][data-value=\"'+valueInternal+'\"]').val() || value;\n }, this);\n\n return data;\n }", "label": 1, "label_name": "safe"} -{"code": " def legal?(string)\n string.to_s =~ /\\A[0-9a-f]{24}\\z/i ? true : false\n end", "label": 1, "label_name": "safe"} -{"code": "static int sco_sock_bind(struct socket *sock, struct sockaddr *addr,\n\t\t\t int addr_len)\n{\n\tstruct sockaddr_sco *sa = (struct sockaddr_sco *) addr;\n\tstruct sock *sk = sock->sk;\n\tint err = 0;\n\n\tBT_DBG(\"sk %p %pMR\", sk, &sa->sco_bdaddr);\n\n\tif (!addr || addr->sa_family != AF_BLUETOOTH)\n\t\treturn -EINVAL;\n\n\tif (addr_len < sizeof(struct sockaddr_sco))\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != BT_OPEN) {\n\t\terr = -EBADFD;\n\t\tgoto done;\n\t}\n\n\tif (sk->sk_type != SOCK_SEQPACKET) {\n\t\terr = -EINVAL;\n\t\tgoto done;\n\t}\n\n\tbacpy(&sco_pi(sk)->src, &sa->sco_bdaddr);\n\n\tsk->sk_state = BT_BOUND;\n\ndone:\n\trelease_sock(sk);\n\treturn err;\n}", "label": 1, "label_name": "safe"} -{"code": "struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,\n\t\t\t\t int *peeked, int *off, int *err)\n{\n\tstruct sk_buff *skb;\n\tlong timeo;\n\t/*\n\t * Caller is allowed not to check sk->sk_err before skb_recv_datagram()\n\t */\n\tint error = sock_error(sk);\n\n\tif (error)\n\t\tgoto no_packet;\n\n\ttimeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);\n\n\tdo {\n\t\t/* Again only user level code calls this function, so nothing\n\t\t * interrupt level will suddenly eat the receive_queue.\n\t\t *\n\t\t * Look at current nfs client by the way...\n\t\t * However, this function was correct in any case. 8)\n\t\t */\n\t\tunsigned long cpu_flags;\n\t\tstruct sk_buff_head *queue = &sk->sk_receive_queue;\n\n\t\tspin_lock_irqsave(&queue->lock, cpu_flags);\n\t\tskb_queue_walk(queue, skb) {\n\t\t\t*peeked = skb->peeked;\n\t\t\tif (flags & MSG_PEEK) {\n\t\t\t\tif (*off >= skb->len && skb->len) {\n\t\t\t\t\t*off -= skb->len;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tskb->peeked = 1;\n\t\t\t\tatomic_inc(&skb->users);\n\t\t\t} else\n\t\t\t\t__skb_unlink(skb, queue);\n\n\t\t\tspin_unlock_irqrestore(&queue->lock, cpu_flags);\n\t\t\treturn skb;\n\t\t}\n\t\tspin_unlock_irqrestore(&queue->lock, cpu_flags);\n\n\t\t/* User doesn't want to wait */\n\t\terror = -EAGAIN;\n\t\tif (!timeo)\n\t\t\tgoto no_packet;\n\n\t} while (!wait_for_packet(sk, err, &timeo));\n\n\treturn NULL;\n\nno_packet:\n\t*err = error;\n\treturn NULL;\n}", "label": 1, "label_name": "safe"} -{"code": "void PacketReader::getLabelFromContent(const vector& content, uint16_t& frompos, string& ret, int recurs) \n{\n if(recurs > 100) // the forward reference-check below should make this test 100% obsolete\n throw MOADNSException(\"Loop\");\n\n int pos = frompos;\n // it is tempting to call reserve on ret, but it turns out it creates a malloc/free storm in the loop\n for(;;) {\n unsigned char labellen=content.at(frompos++);\n\n if(!labellen) {\n if(ret.empty())\n ret.append(1,'.');\n break;\n }\n else if((labellen & 0xc0) == 0xc0) {\n uint16_t offset=256*(labellen & ~0xc0) + (unsigned int)content.at(frompos++) - sizeof(dnsheader);\n // cout<<\"This is an offset, need to go to: \"<= pos)\n throw MOADNSException(\"forward reference during label decompression\");\n return getLabelFromContent(content, offset, ret, ++recurs);\n }\n else if(labellen > 63) \n throw MOADNSException(\"Overly long label during label decompression (\"+lexical_cast((unsigned int)labellen)+\")\");\n else {\n // XXX FIXME THIS MIGHT BE VERY SLOW!\n\n for(string::size_type n = 0 ; n < labellen; ++n, frompos++) {\n if(content.at(frompos)=='.' || content.at(frompos)=='\\\\') {\n ret.append(1, '\\\\');\n ret.append(1, content[frompos]);\n }\n else if(content.at(frompos)==' ') {\n ret+=\"\\\\032\";\n }\n else \n ret.append(1, content[frompos]);\n }\n ret.append(1,'.');\n }\n if (ret.length() > 1024)\n throw MOADNSException(\"Total name too long\");\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\tfunc: (thiz) => {\n\t\t\t\t\treturn local.Reflect.apply(func, thiz, []);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\treturn callSiteGetters;\n\t}", "label": 1, "label_name": "safe"} -{"code": "once:function(){var b=arguments[1];arguments[1]=function(d){d.removeListener();return b.apply(this,arguments)};return this.on.apply(this,arguments)},capture:function(){CKEDITOR.event.useCapture=1;var b=this.on.apply(this,arguments);CKEDITOR.event.useCapture=0;return b},fire:function(){var b=0,d=function(){b=1},a=0,h=function(){a=1};return function(m,j,i){var n=e(this)[m],m=b,r=a;b=a=0;if(n){var o=n.listeners;if(o.length)for(var o=o.slice(0),u,f=0;f' + data.assignedUserName + '';\n\n if (this.isUserStream) {\n if (this.assignedUserId) {\n if (this.assignedUserId == this.model.get('createdById')) {\n this.messageName += 'Self';\n } else {\n if (this.assignedUserId == this.getUser().id) {\n this.messageName += 'You';\n }\n }\n } else {\n this.messageName += 'Void';\n }\n } else {\n if (this.assignedUserId) {\n if (this.assignedUserId == this.model.get('createdById')) {\n this.messageName += 'Self';\n }\n } else {\n this.messageName += 'Void';\n }\n }\n\n this.createMessage();\n },", "label": 0, "label_name": "vulnerable"} -{"code": " public function create($data)\n {\n if ($this->securityController->isWikiHibernated()) {\n throw new \\Exception(_t('WIKI_IN_HIBERNATION'));\n }\n // If ID is not set or if it is already used, find a new ID\n if (!$data['bn_id_nature'] || $this->getOne($data['bn_id_nature'])) {\n $data['bn_id_nature'] = $this->findNewId();\n }\n\n return $this->dbService->query('INSERT INTO ' . $this->dbService->prefixTable('nature')\n . '(`bn_id_nature` ,`bn_ce_i18n` ,`bn_label_nature` ,`bn_template` ,`bn_description` ,`bn_sem_context` ,`bn_sem_type` ,`bn_sem_use_template` ,`bn_condition`)'\n . ' VALUES (' . $data['bn_id_nature'] . ', \"fr-FR\", \"'\n . addslashes(_convert($data['bn_label_nature'], YW_CHARSET, true)) . '\",\"'\n . addslashes(_convert($data['bn_template'], YW_CHARSET, true)) . '\", \"'\n . addslashes(_convert($data['bn_description'], YW_CHARSET, true)) . '\", \"'\n . addslashes(_convert($data['bn_sem_context'], YW_CHARSET, true)) . '\", \"'\n . addslashes(_convert($data['bn_sem_type'], YW_CHARSET, true)) . '\", '\n . (isset($data['bn_sem_use_template']) ? '1' : '0') . ', \"'\n . addslashes(_convert($data['bn_condition'], YW_CHARSET, true)) . '\")');", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic PersistedMapper persistMapper(String sessionId, String mapperId, Serializable mapper, int expirationTime) {\n\t\tPersistedMapper m = new PersistedMapper();\n\t\tm.setMapperId(mapperId);\n\t\tDate currentDate = new Date();\n\t\tm.setLastModified(currentDate);\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\tm.setExpirationDate(cal.getTime());\n\t\t}\n\t\tm.setOriginalSessionId(sessionId);\n\t\t\n\t\tString configuration = XStreamHelper.createXStreamInstance().toXML(mapper);\n\t\tm.setXmlConfiguration(configuration);\n\t\t\n\t\tdbInstance.getCurrentEntityManager().persist(m);\n\t\treturn m;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "SPL_METHOD(SplFileInfo, setInfoClass)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tzend_class_entry *ce = spl_ce_SplFileInfo;\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->info_class = ce;\n\t}\n\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " function insertObject($object, $table) {\n //if ($table==\"text\") eDebug($object,true);\n $sql = \"INSERT INTO `\" . $this->prefix . \"$table` (\";\n $values = \") VALUES (\";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n if ($var{0} != '_') {\n $sql .= \"`$var`,\";\n if ($values != \") VALUES (\") {\n $values .= \",\";\n }\n $values .= \"'\" . $this->escapeString($val) . \"'\";\n }\n }\n $sql = substr($sql, 0, -1) . substr($values, 0) . \")\";\n //if($table=='text')eDebug($sql,true);\n if (@mysqli_query($this->connection, $sql) != false) {\n $id = mysqli_insert_id($this->connection);\n return $id;\n } else\n return 0;\n }", "label": 1, "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, "label_name": "safe"} -{"code": " def testProxyGET(self):\n data = (\n b\"GET https://example.com:8080/foobar HTTP/8.4\\r\\n\"\n b\"content-length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"Hello.\"\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(parser.headers, {\"CONTENT_LENGTH\": \"6\"})\n self.assertEqual(parser.path, \"/foobar\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.proxy_scheme, \"https\")\n self.assertEqual(parser.proxy_netloc, \"example.com:8080\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.query, \"\")\n self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello.\")", "label": 1, "label_name": "safe"} -{"code": "\t\t\t$connecttext = preg_replace(\"/#connectport#/\", $connectport, $connecttext); \n\t\t\t$connectMethods[$key][\"connecttext\"] = $connecttext;\n\t\t}\n\t\treturn array('status' => 'ready',\n\t\t 'serverIP' => $serverIP,\n\t\t 'user' => $thisuser,\n\t\t 'password' => $passwd,\n\t\t 'connectport' => $connectport,\n\t\t 'connectMethods' => $connectMethods);\n\t}\n\treturn array('status' => 'notready');\n}", "label": 1, "label_name": "safe"} -{"code": " def format_type(self):\n format_type = self.type.lower()\n if format_type == 'amazon':\n return u\"Amazon\"\n elif format_type.startswith(\"amazon_\"):\n return u\"Amazon.{0}\".format(format_type[7:])\n elif format_type == \"isbn\":\n return u\"ISBN\"\n elif format_type == \"doi\":\n return u\"DOI\"\n elif format_type == \"douban\":\n return u\"Douban\"\n elif format_type == \"goodreads\":\n return u\"Goodreads\"\n elif format_type == \"babelio\":\n return u\"Babelio\"\n elif format_type == \"google\":\n return u\"Google Books\"\n elif format_type == \"kobo\":\n return u\"Kobo\"\n elif format_type == \"litres\":\n return u\"\u041b\u0438\u0442\u0420\u0435\u0441\"\n elif format_type == \"issn\":\n return u\"ISSN\"\n elif format_type == \"isfdb\":\n return u\"ISFDB\"\n if format_type == \"lubimyczytac\":\n return u\"Lubimyczytac\"\n else:\n return self.type", "label": 1, "label_name": "safe"} -{"code": "\tModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE\n\t{\n\t\tstd::string ctcpname;\n\t\tbool is_ctcp = details.IsCTCP(ctcpname) && !irc::equals(ctcpname, \"ACTION\");\n\n\t\tSilenceEntry::SilenceFlags flag = SilenceEntry::SF_NONE;\n\t\tif (target.type == MessageTarget::TYPE_CHANNEL)\n\t\t{\n\t\t\tif (is_ctcp)\n\t\t\t\tflag = SilenceEntry::SF_CTCP_CHANNEL;\n\t\t\telse if (details.type == MSG_NOTICE)\n\t\t\t\tflag = SilenceEntry::SF_NOTICE_CHANNEL;\n\t\t\telse if (details.type == MSG_PRIVMSG)\n\t\t\t\tflag = SilenceEntry::SF_PRIVMSG_CHANNEL;\n\n\t\t\treturn BuildChannelExempts(user, target.Get(), flag, details.exemptions);\n\t\t}\n\n\t\tif (target.type == MessageTarget::TYPE_USER)\n\t\t{\n\t\t\tif (is_ctcp)\n\t\t\t\tflag = SilenceEntry::SF_CTCP_USER;\n\t\t\telse if (details.type == MSG_NOTICE)\n\t\t\t\tflag = SilenceEntry::SF_NOTICE_USER;\n\t\t\telse if (details.type == MSG_PRIVMSG)\n\t\t\t\tflag = SilenceEntry::SF_PRIVMSG_USER;\n\n\t\t\tif (!CanReceiveMessage(user, target.Get(), flag))\n\t\t\t{\n\t\t\t\tdetails.echo_original = true;\n\t\t\t\treturn MOD_RES_DENY;\n\t\t\t}\n\t\t}\n\n\t\treturn MOD_RES_PASSTHRU;\n\t}", "label": 1, "label_name": "safe"} -{"code": "function getTestability(rootElement) {\n var injector = angular.element(rootElement).injector();\n if (!injector) {\n throw ngMinErr('test',\n 'no injector found for element argument to getTestability');\n }\n return injector.get('$$testability');\n}", "label": 0, "label_name": "vulnerable"} -{"code": " protected function processJpeg()\n {\n ob_start();\n imagejpeg($this->image->getCore(), null, $this->quality);\n $this->image->mime = image_type_to_mime_type(IMAGETYPE_JPEG);\n $buffer = ob_get_contents();\n ob_end_clean();\n\n return $buffer;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "var T=document.createElement(\"tbody\"),N=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(g=mxUtils.indexOf(b.pages,b.currentPage));for(q=e.length-1;0<=q;q--){var Q=function(R){var Y=new Date(R.modifiedDate),ba=null;if(0<=Y.getTime()){var ea=function(fa){x.stop();v.innerHTML=\"\";var aa=mxUtils.parseXml(fa),va=b.editor.extractGraphModel(aa.documentElement,!0);if(null!=va){var ja=function(Ha){null!=Ha&&(Ha=Ba(Editor.parseDiagramNode(Ha)));return Ha},Ba=function(Ha){var ra=Ha.getAttribute(\"background\");", "label": 0, "label_name": "vulnerable"} -{"code": "process_demand_active(STREAM s)\n{\n\tuint8 type;\n\tuint16 len_src_descriptor, len_combined_caps;\n\tstruct stream packet = *s;\n\n\t/* at this point we need to ensure that we have ui created */\n\trd_create_ui();\n\n\tin_uint32_le(s, g_rdp_shareid);\n\tin_uint16_le(s, len_src_descriptor);\n\tin_uint16_le(s, len_combined_caps);\n\n\tif (!s_check_rem(s, len_src_descriptor))\n\t{\n\t\trdp_protocol_error(\"rdp_demand_active(), consume of source descriptor from stream would overrun\", &packet);\n\t}\n\tin_uint8s(s, len_src_descriptor);\n\n\tlogger(Protocol, Debug, \"process_demand_active(), shareid=0x%x\", g_rdp_shareid);\n\n\trdp_process_server_caps(s, len_combined_caps);\n\n\trdp_send_confirm_active();\n\trdp_send_synchronise();\n\trdp_send_control(RDP_CTL_COOPERATE);\n\trdp_send_control(RDP_CTL_REQUEST_CONTROL);\n\trdp_recv(&type);\t/* RDP_PDU_SYNCHRONIZE */\n\trdp_recv(&type);\t/* RDP_CTL_COOPERATE */\n\trdp_recv(&type);\t/* RDP_CTL_GRANT_CONTROL */\n\trdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0,\n\t\t g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0);\n\n\tif (g_rdp_version >= RDP_V5)\n\t{\n\t\trdp_enum_bmpcache2();\n\t\trdp_send_fonts(3);\n\t}\n\telse\n\t{\n\t\trdp_send_fonts(1);\n\t\trdp_send_fonts(2);\n\t}\n\n\trdp_recv(&type);\t/* RDP_PDU_UNKNOWN 0x28 (Fonts?) */\n\treset_order_state();\n}", "label": 1, "label_name": "safe"} -{"code": " public IESParameterSpec(\n byte[] derivation,\n byte[] encoding,\n int macKeySize,\n int cipherKeySize)\n {\n this(derivation, encoding, macKeySize, cipherKeySize, null, false);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function setUp()\n {\n parent::setUp();\n $this->obj = new HTMLPurifier_Strategy_RemoveForeignElements();\n $this->config->set('HTML.TidyLevel', 'heavy');\n }", "label": 1, "label_name": "safe"} -{"code": " public function addBlankElement($element)\n {\n if (!isset($this->info[$element])) {\n $this->elements[] = $element;\n $this->info[$element] = new HTMLPurifier_ElementDef();\n $this->info[$element]->standalone = false;\n } else {\n trigger_error(\"Definition for $element already exists in module, cannot redefine\");\n }\n return $this->info[$element];\n }", "label": 1, "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, "label_name": "safe"} -{"code": " public function setup($config) {\n\n // These definitions are not intrinsically safe: the attribute transforms\n // are a vital part of ensuring safety.\n\n $max = $config->get('HTML.MaxImgLength');\n $object = $this->addElement(\n 'object',\n 'Inline',\n 'Optional: param | Flow | #PCDATA',\n 'Common',\n array(\n // While technically not required by the spec, we're forcing\n // it to this value.\n 'type' => 'Enum#application/x-shockwave-flash',\n 'width' => 'Pixels#' . $max,\n 'height' => 'Pixels#' . $max,\n 'data' => 'URI#embedded',\n 'codebase' => new HTMLPurifier_AttrDef_Enum(array(\n 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0')),\n )\n );\n $object->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeObject();\n\n $param = $this->addElement('param', false, 'Empty', false,\n array(\n 'id' => 'ID',\n 'name*' => 'Text',\n 'value' => 'Text'\n )\n );\n $param->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeParam();\n $this->info_injector[] = 'SafeObject';\n\n }", "label": 1, "label_name": "safe"} -{"code": "\t\t\t$res = @unserialize ( base64_decode (str_replace ( array ( \"|02\" , \"|01\" ) , array ( \"/\" , \"|\" ) , $str ) ) ) ;", "label": 0, "label_name": "vulnerable"} -{"code": " $va[] = [$k2 => $m[$v2]];\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function isAbstract()\n {\n return $this->abstract;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " private function section($nodes, $id, $filters, $start, $end, $otag, $ctag, $level)\n {\n $source = var_export(substr($this->source, $start, $end - $start), true);\n $callable = $this->getCallable();\n\n if ($otag !== '{{' || $ctag !== '}}') {\n $delimTag = var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);\n $helper = sprintf('$this->lambdaHelper->withDelimiters(%s)', $delimTag);\n $delims = ', ' . $delimTag;\n } else {\n $helper = '$this->lambdaHelper';\n $delims = '';\n }\n\n $key = ucfirst(md5($delims . \"\\n\" . $source));\n\n if (!isset($this->sections[$key])) {\n $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $helper, $delims, $this->walk($nodes, 2));\n }\n\n $method = $this->getFindMethod($id);\n $id = var_export($id, true);\n $filters = $this->getFilters($filters, $level);\n\n return sprintf($this->prepare(self::SECTION_CALL, $level), $method, $id, $filters, $key);\n }", "label": 1, "label_name": "safe"} -{"code": " $ret .= $this->end('textarea');\n } else {\n $attr['value'] = $value;\n $attr['type'] = 'text';\n $ret .= $this->elementEmpty('input', $attr);\n }\n return $ret;\n }", "label": 1, "label_name": "safe"} -{"code": " private String marshallToString(Document document) throws TransformerException {\n StringWriter sw = new StringWriter();\n TransformerFactory tf = TransformerFactory.newInstance();\n Transformer transformer = tf.newTransformer();\n transformer.transform(new DOMSource(document), new StreamResult(sw));\n return sw.toString();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"raises an error if the second argument is not a string\" do\n expect {\n scope.function_prefix([['first', 'second'], 42])\n }.to raise_error(Puppet::ParseError, /expected second argument to be a String/)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " $contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, 'primary', null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('customer_data_groups.php', 'page=' . $_GET['page']), null, null, 'btn-light')];", "label": 0, "label_name": "vulnerable"} -{"code": " protected function renderText ($field, $makeLinks, $textOnly, $encode) {\n $fieldName = $field->fieldName;\n $value = preg_replace(\"/(\\
)|\\n/\",\" \",$this->owner->$fieldName);\n return Yii::app()->controller->convertUrls($this->render ($value, $encode));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def gate_process\n\n HistoryHelper.keep_last(request)\n\n SqlHelper.validate_token([session[:login_user_id]])\n begin\n @login_user = User.find(session[:login_user_id])\n rescue => evar\n @login_user = nil\n end\n\n begin\n if @login_user.nil? \\\n or @login_user.time_zone.nil? or @login_user.time_zone.empty?\n unless THETIS_USER_TIMEZONE_DEFAULT.nil? or THETIS_USER_TIMEZONE_DEFAULT.empty?\n Time.zone = THETIS_USER_TIMEZONE_DEFAULT\n end\n else\n Time.zone = @login_user.time_zone\n end\n rescue => evar\n logger.fatal(evar.to_s)\n end\n end", "label": 1, "label_name": "safe"} -{"code": " $comments->records[$key]->avatar = $db->selectObject('user_avatar',\"user_id='\".$record->poster.\"'\");\n }\n\n if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);\n // eDebug($sql, true);\n \n // count the unapproved comments\n if ($require_approval == 1 && $user->isAdmin()) {\n $sql = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';\n $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';\n $sql .= 'WHERE cnt.content_id='.$this->params['content_id'].\" AND cnt.content_type='\".$this->params['content_type'].\"' \";\n $sql .= 'AND com.approved=0';\n $unapproved = $db->countObjectsBySql($sql);\n } else {\n $unapproved = 0;\n } \n \n $this->config = $this->params['config'];\n $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');\n $ratings = !empty($this->params['ratings']) ? true : false;\n\n assign_to_template(array(\n 'comments'=>$comments,\n 'config'=>$this->params['config'],\n 'unapproved'=>$unapproved,\n\t\t\t'content_id'=>$this->params['content_id'], \n\t\t\t'content_type'=>$this->params['content_type'],\n\t\t\t'user'=>$user,\n\t\t\t'hideform'=>$this->params['hideform'],\n\t\t\t'hidecomments'=>$this->params['hidecomments'],\n\t\t\t'title'=>$this->params['title'],\n\t\t\t'formtitle'=>$this->params['formtitle'],\n 'type'=>$type,\n 'ratings'=>$ratings,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n\t\t));\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def collect\n @stats = Hash.new { |hash, key| hash[key] = [] }\n yield\n @stats\n ensure\n @stats = nil\n end", "label": 1, "label_name": "safe"} -{"code": " $save_value = expString::sanitize($value);\n $_REQUEST[$key] = $save_value;\n $_GET[$key] = $save_value;\n }\n\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($events as $event) {\n $extevents[$date][] = $event;\n }", "label": 1, "label_name": "safe"} -{"code": "archive_write_disk_set_acls(struct archive *a, int fd, const char *name,\n struct archive_acl *abstract_acl, __LA_MODE_T mode)\n{\n\tint\t\tret = ARCHIVE_OK;\n\n\t(void)mode;\t/* UNUSED */\n\n\tif ((archive_acl_types(abstract_acl)\n\t & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {\n\t\t/* Solaris writes POSIX.1e access and default ACLs together */\n\t\tret = set_acl(a, fd, name, abstract_acl, mode,\n\t\t ARCHIVE_ENTRY_ACL_TYPE_POSIX1E, \"posix1e\");\n\n\t\t/* Simultaneous POSIX.1e and NFSv4 is not supported */\n\t\treturn (ret);\n\t}\n#if ARCHIVE_ACL_SUNOS_NFS4\n\telse if ((archive_acl_types(abstract_acl) &\n\t ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {\n\t\tret = set_acl(a, fd, name, abstract_acl, mode,\n\t\t ARCHIVE_ENTRY_ACL_TYPE_NFS4, \"nfs4\");\n\t}\n#endif\n\treturn (ret);\n}", "label": 1, "label_name": "safe"} -{"code": " foreach ($attributes as $attribute => $x) {\n $allowed_attributes[\"$element.$attribute\"] = true;\n }", "label": 1, "label_name": "safe"} -{"code": "bool f_libxml_disable_entity_loader(bool disable /* = true */) {\n xmlParserInputBufferCreateFilenameFunc old;\n\n if (disable) {\n old = xmlParserInputBufferCreateFilenameDefault(hphp_libxml_input_buffer_noload);\n } else {\n old = xmlParserInputBufferCreateFilenameDefault(nullptr);\n }\n return (old == hphp_libxml_input_buffer_noload);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "func (x *WriteStorageObjectRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[45]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label": 1, "label_name": "safe"} -{"code": " public static function exist ($vars) {\r\n if(file_exists(GX_THEME.THEME.'/'.$vars.'.php')) {\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)\n{\n\treturn tags->rqs[tag];\n}", "label": 1, "label_name": "safe"} -{"code": "EditorUi.prototype.updateTabContainer=function(){null!=this.tabContainer&&(this.tabContainer.style.right=\"70px\",this.diagramContainer.style.bottom=\"1\"==urlParams.sketch?\"0px\":this.tabContainerHeight+\"px\");e.apply(this,arguments)};var g=EditorUi.prototype.updateActionStates;EditorUi.prototype.updateActionStates=function(){g.apply(this,arguments);this.menus.get(\"save\").setEnabled(null!=this.getCurrentFile()||\"1\"==urlParams.embed)};var k=Menus.prototype.addShortcut;Menus.prototype.addShortcut=function(A,\nB){null!=B.shortcut&&900>d&&!mxClient.IS_IOS?A.firstChild.nextSibling.setAttribute(\"title\",B.shortcut):k.apply(this,arguments)};var m=App.prototype.updateUserElement;App.prototype.updateUserElement=function(){m.apply(this,arguments);if(null!=this.userElement){var A=this.userElement;A.style.cssText=\"position:relative;margin-right:4px;cursor:pointer;display:\"+A.style.display;A.className=\"geToolbarButton\";A.innerText=\"\";A.style.backgroundImage=\"url(\"+Editor.userImage+\")\";A.style.backgroundPosition=\"center center\";", "label": 1, "label_name": "safe"} -{"code": " protected function getExternalTaskLink(array $task)\n {\n $link = $this->taskExternalLinkModel->getById($this->request->getIntegerParam('link_id'));\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n if ($link['task_id'] != $task['id']) {\n throw new AccessForbiddenException();\n }\n\n return $link;\n }", "label": 1, "label_name": "safe"} -{"code": "0>M?(H=M*V.width,M=0):1F?(S=F*V.height,F=0):1type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_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.rtv_annotations_attr.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}\n\t\t\tr_list_append (attr->info.annotation_array.annotations, (void *) annotation);\n\t\t}\n\t\tattr->size = offset;\n\t}\n\treturn attr;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function delete() {\n global $db, $history;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the comment you would like to delete'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n // delete the note\n $simplenote = new expSimpleNote($this->params['id']);\n $rows = $simplenote->delete();\n \n // delete the assocication too\n $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']); \n \n // send the user back where they came from.\n $lastUrl = expHistory::getLast('editable');\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "void Huff_transmit (huff_t *huff, int ch, byte *fout, int maxoffset) {\n\tint i;\n\tif (huff->loc[ch] == NULL) { \n\t\t/* node_t hasn't been transmitted, send a NYT, then the symbol */\n\t\tHuff_transmit(huff, NYT, fout, maxoffset);\n\t\tfor (i = 7; i >= 0; i--) {\n\t\t\tadd_bit((char)((ch >> i) & 0x1), fout);\n\t\t}\n\t} else {\n\t\tsend(huff->loc[ch], NULL, fout, maxoffset);\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": "PyParser_ParseFileObject(FILE *fp, PyObject *filename,\n const char *enc, grammar *g, int start,\n const char *ps1, const char *ps2,\n perrdetail *err_ret, int *flags)\n{\n struct tok_state *tok;\n\n if (initerr(err_ret, filename) < 0)\n return NULL;\n\n if ((tok = PyTokenizer_FromFile(fp, enc, ps1, ps2)) == NULL) {\n err_ret->error = E_NOMEM;\n return NULL;\n }\n if (*flags & PyPARSE_TYPE_COMMENTS) {\n tok->type_comments = 1;\n }\n#ifndef PGEN\n Py_INCREF(err_ret->filename);\n tok->filename = err_ret->filename;\n#endif\n return parsetok(tok, g, start, err_ret, flags);\n}", "label": 1, "label_name": "safe"} -{"code": " public function testProcessDoesNotSaveDuplicateReferences()\n {\n $container = new ContainerBuilder();\n\n $container\n ->register('a')\n ;\n $container\n ->register('b')\n ->addArgument(new Definition(null, array($ref1 = new Reference('a'))))\n ->addArgument(new Definition(null, array($ref2 = new Reference('a'))))\n ;\n\n $graph = $this->process($container);\n\n $this->assertCount(2, $graph->getNode('a')->getInEdges());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static function convertExceptionToVerboseString($exception)\n {\n if ($exception instanceof Exception) {\n $message = \"Exception ({$exception->getName()})\";\n } elseif ($exception instanceof ErrorException) {\n $message = \"{$exception->getName()}\";\n } else {\n $message = 'Exception';\n }\n $message .= \" '\" . get_class($exception) . \"' with message '{$exception->getMessage()}' \\n\\nin \"\n . $exception->getFile() . ':' . $exception->getLine() . \"\\n\\n\"\n . \"Stack trace:\\n\" . $exception->getTraceAsString();\n\n return $message;\n }", "label": 1, "label_name": "safe"} -{"code": "func (m *MockRequester) GrantScope(arg0 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"GrantScope\", arg0)\n}", "label": 1, "label_name": "safe"} -{"code": " protected function getScript($request)\n {\n $script = parent::getScript($request);\n\n $autoload = file_exists(__DIR__.'/../../vendor/autoload.php')\n ? __DIR__.'/../../vendor/autoload.php'\n : __DIR__.'/../../../../../../vendor/autoload.php'\n ;\n\n $script = preg_replace('/(\\->register\\(\\);)/', \"$0\\nrequire_once '$autoload';\\n\", $script);\n\n return $script;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "export function createCatalogWriteAction() {\n return createTemplateAction<{ name?: string; entity: Entity }>({\n id: 'catalog:write',\n description: 'Writes the catalog-info.yaml for your template',\n schema: {\n input: {\n type: 'object',\n properties: {\n entity: {\n title: 'Entity info to write catalog-info.yaml',\n description:\n 'You can provide the same values used in the Entity schema.',\n type: 'object',\n },\n },\n },\n },\n async handler(ctx) {\n ctx.logStream.write(`Writing catalog-info.yaml`);\n const { entity } = ctx.input;\n\n await fs.writeFile(\n resolveSafeChildPath(ctx.workspacePath, 'catalog-info.yaml'),\n yaml.stringify(entity),\n );\n },\n });\n}", "label": 1, "label_name": "safe"} -{"code": "EditorUi.prototype.setStatusText = function(value)\n{\n\tthis.statusContainer.innerHTML = value;\n\n\t// Wraps simple status messages in a div for styling\n\tif (this.statusContainer.getElementsByTagName('div').length == 0)\n\t{\n\t\tthis.statusContainer.innerText = '';\n\t\tvar div = this.createStatusDiv(value);\n\t\tthis.statusContainer.appendChild(div);\n\t}\n};", "label": 1, "label_name": "safe"} -{"code": "[H],\"{1} ago\"));F.setAttribute(\"title\",K.toLocaleDateString()+\" \"+K.toLocaleTimeString())}function k(K){var F=document.createElement(\"img\");F.className=\"geCommentBusyImg\";F.src=IMAGE_PATH+\"/spin.gif\";K.appendChild(F);K.busyImg=F}function l(K){K.style.border=\"1px solid red\";K.removeChild(K.busyImg)}function p(K){K.style.border=\"\";K.removeChild(K.busyImg)}function q(K,F,H,S,V){function M(N,Q,R){var Y=document.createElement(\"li\");Y.className=\"geCommentAction\";var ba=document.createElement(\"a\");ba.className=", "label": 0, "label_name": "vulnerable"} -{"code": " public function testRemoveCurlAuthorizationOptionsOnRedirect($auth)\n {\n if (!defined('\\CURLOPT_HTTPAUTH')) {\n self::markTestSkipped('ext-curl is required for this test');\n }\n\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://test.com']),\n static function (RequestInterface $request, $options) {\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_HTTPAUTH]),\n 'curl options still contain CURLOPT_HTTPAUTH entry'\n );\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_USERPWD]),\n 'curl options still contain CURLOPT_USERPWD entry'\n );\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);\n }", "label": 0, "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, "label_name": "vulnerable"} -{"code": " public function getController(Request $request)\n {\n return array($this, 'callController');\n }", "label": 0, "label_name": "vulnerable"} -{"code": "new CKEDITOR.dom.walker(b);b.guard=function(a,b){if(b)return false;if(a.type==CKEDITOR.NODE_ELEMENT)return a.is(CKEDITOR.dtd.$tableContent)};b.evaluator=function(a){return a.type==CKEDITOR.NODE_ELEMENT};return b}function b(a,c,e){c=a.getDocument().createElement(c);a.append(c,e);return c}function c(a){var b=a.count(),e;for(b;b-- >0;){e=a.getItem(b);if(!CKEDITOR.tools.trim(e.getHtml())){e.appendBogus();CKEDITOR.env.ie&&(CKEDITOR.env.version<9&&e.getChildCount())&&e.getFirst().remove()}}}return function(e){var d=", "label": 1, "label_name": "safe"} -{"code": "func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) {\n\tsess := x.Limit(20, (page-1)*20)\n\n\tif rid > 0 {\n\t\tsess.Where(\"repo_id=?\", rid).And(\"is_closed=?\", isClosed)\n\t} else {\n\t\tsess.Where(\"is_closed=?\", isClosed)\n\t}\n\n\tif uid > 0 {\n\t\tsess.And(\"assignee_id=?\", uid)\n\t} else if pid > 0 {\n\t\tsess.And(\"poster_id=?\", pid)\n\t}\n\n\tif mid > 0 {\n\t\tsess.And(\"milestone_id=?\", mid)\n\t}\n\n\tif len(labelIds) > 0 {\n\t\tfor _, label := range strings.Split(labelIds, \",\") {\n\t\t\t// Prevent SQL inject.\n\t\t\tif com.StrTo(label).MustInt() > 0 {\n\t\t\t\tsess.And(\"label_ids like '%$\" + label + \"|%'\")\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch sortType {\n\tcase \"oldest\":\n\t\tsess.Asc(\"created\")\n\tcase \"recentupdate\":\n\t\tsess.Desc(\"updated\")\n\tcase \"leastupdate\":\n\t\tsess.Asc(\"updated\")\n\tcase \"mostcomment\":\n\t\tsess.Desc(\"num_comments\")\n\tcase \"leastcomment\":\n\t\tsess.Asc(\"num_comments\")\n\tcase \"priority\":\n\t\tsess.Desc(\"priority\")\n\tdefault:\n\t\tsess.Desc(\"created\")\n\t}\n\n\tvar issues []Issue\n\terr := sess.Find(&issues)\n\treturn issues, err\n}", "label": 1, "label_name": "safe"} -{"code": " public function setScheme($scheme)\n {\n $this->_scheme = $scheme;\n return $this;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function(z){var L=null;null!=z&&0getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {\n $this->create();\n return;\n }\n\n $action = $this->actionManager->getAction($values['action_name']);\n $action_params = $action->getActionRequiredParameters();\n\n if (empty($action_params)) {\n $this->doCreation($project, $values + array('params' => array()));\n }\n\n $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());\n unset($projects_list[$project['id']]);\n\n $this->response->html($this->template->render('action_creation/params', array(\n 'values' => $values,\n 'action_params' => $action_params,\n 'columns_list' => $this->columnModel->getList($project['id']),\n 'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),\n 'projects_list' => $projects_list,\n 'colors_list' => $this->colorModel->getList(),\n 'categories_list' => $this->categoryModel->getList($project['id']),\n 'links_list' => $this->linkModel->getList(0, false),\n 'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'swimlane_list' => $this->swimlaneModel->getList($project['id']),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic static function recent_items($limit=5)\r\n\t{\r\n\t\tglobal $DB;\r\n\t\tglobal $user;\r\n\t\tglobal $website;\r\n\r\n\t\t// last month only!\r\n\t\t$DB->query('\r\n\t\t\tSELECT DISTINCT nvul.website, nvul.function, nvul.item, nvul.item_title,\r\n\t\t\t\t\t\t\tnvf.lid as function_title, nvf.icon as function_icon, nvul.date\r\n\t\t\tFROM nv_users_log nvul, \r\n\t\t\t\t nv_functions nvf\r\n\t\t\tWHERE nvul.user = '.intval($user->id).'\r\n\t\t\t AND nvul.function = nvf.id\r\n\t\t\t AND nvul.item > 0\r\n\t\t\t AND nvul.action = \"load\"\r\n\t\t\t AND nvul.website = '.intval($website->id).'\r\n\t\t\t AND nvul.item_title <> \"\"\r\n\t\t\t AND nvul.date > '.( core_time() - 30 * 86400).'\r\n\t\t\t AND nvul.date = (\tSELECT MAX(nvulm.date) \r\n\t\t\t \t\t\t\t\t FROM nv_users_log nvulm \r\n\t\t\t \t\t\t\t\t WHERE nvulm.function = nvul.function \r\n\t\t\t \t\t\t\t\t AND nvulm.item = nvul.item\r\n\t\t\t \t\t\t\t\t AND nvulm.item_title = nvul.item_title\r\n\t\t\t \t\t\t\t\t AND nvulm.website = '.intval($website->id).'\r\n\t\t\t \t\t\t\t\t AND nvulm.user = '.intval($user->id).'\r\n\t\t\t\t\t\t\t )\r\n\t\t\tORDER BY nvul.date DESC\r\n\t\t\tLIMIT '.$limit\r\n\t\t);\r", "label": 1, "label_name": "safe"} -{"code": " public function __get($var) {\n\n switch ($var) {\n case 'configuration_array':\n $this->configuration_array = array();\n if ($this->configuration != ''){\n $jsonData = json_decode($this->configuration,true);\n if ($jsonData !== null) {\n $this->configuration_array = $jsonData;\n } else {\n $this->configuration_array = array();\n }\n }\n return $this->configuration_array;\n break;\n\n case 'name_support':\n return $this->name_support = $this->nick;\n break;\n\n case 'has_photo':\n return $this->filename != '';\n break;\n\n case 'photo_path':\n $this->photo_path = ($this->filepath != '' ? erLhcoreClassSystem::getHost() . erLhcoreClassSystem::instance()->wwwDir() : erLhcoreClassSystem::instance()->wwwImagesDir() ) .'/'. $this->filepath . $this->filename;\n return $this->photo_path;\n break;\n\n case 'file_path_server':\n return $this->filepath . $this->filename;\n break;\n\n default:\n break;\n }\n }", "label": 1, "label_name": "safe"} -{"code": " $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);\r\n if (!$view) {\r\n// unset($navs[$i]); //FIXME this breaks jstree if we remove a parent and not the child\r\n $attr = new stdClass();\r\n $attr->class = 'hidden'; // bs3 class to hide elements\r\n $navs[$i]->li_attr = $attr;\r\n }\r\n }\r", "label": 0, "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, "label_name": "vulnerable"} -{"code": "static void perf_event_init_cpu(int cpu)\n{\n\tstruct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);\n\n\tmutex_lock(&swhash->hlist_mutex);\n\tswhash->online = true;\n\tif (swhash->hlist_refcount > 0) {\n\t\tstruct swevent_hlist *hlist;\n\n\t\thlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));\n\t\tWARN_ON(!hlist);\n\t\trcu_assign_pointer(swhash->swevent_hlist, hlist);\n\t}\n\tmutex_unlock(&swhash->hlist_mutex);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "TfLiteStatus Prepare(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;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* begin;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBeginTensor, &begin));\n const TfLiteTensor* size;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kSizeTensor, &size));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n // Ensure validity of input tensor and its dimension.\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n TF_LITE_ENSURE(context,\n begin->type == kTfLiteInt32 || begin->type == kTfLiteInt64);\n TF_LITE_ENSURE(context,\n size->type == kTfLiteInt32 || size->type == kTfLiteInt64);\n TF_LITE_ENSURE_EQ(context, NumDimensions(begin), 1);\n TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1);\n TF_LITE_ENSURE_EQ(context, NumElements(begin), NumElements(size));\n TF_LITE_ENSURE_MSG(context, NumDimensions(input) <= kMaxDim,\n \"Slice op only supports 1D-4D input arrays.\");\n\n // Postpone allocation of output if any of the indexing tensors is not\n // constant\n if (!(IsConstantTensor(begin) && IsConstantTensor(size))) {\n SetTensorToDynamic(output);\n return kTfLiteOk;\n }\n\n return ResizeOutputShape(context, input, begin, size, output);\n}", "label": 1, "label_name": "safe"} -{"code": " public static function isHadParent($parent='', $menuid = ''){\r\n if(isset($menuid)){\r\n $where = \" AND `menuid` = '{$menuid}'\";\r\n }else{\r\n $where = '';\r\n }\r\n if(isset($parent) && $parent != ''){\r\n $parent = \" `parent` = '{$parent}'\";\r\n }else{\r\n $parent = '1';\r\n }\r\n $sql = sprintf(\"SELECT * FROM `menus` WHERE %s %s\", $parent, $where);\r\n $menu = Db::result($sql);\r\n return $menu;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " def test_enrollment_report_features_csv(self):\n \"\"\"\n test to generate enrollment report.\n enroll users, admin staff using registration codes.\n \"\"\"\n InvoiceTransaction.objects.create(\n invoice=self.sale_invoice_1,\n amount=self.sale_invoice_1.total_amount,\n status='completed',\n created_by=self.instructor,\n last_modified_by=self.instructor\n )\n course_registration_code = CourseRegistrationCode.objects.create(\n code='abcde',\n course_id=self.course.id.to_deprecated_string(),\n created_by=self.instructor,\n invoice=self.sale_invoice_1,\n invoice_item=self.invoice_item,\n mode_slug='honor'\n )\n\n admin_user = AdminFactory()\n admin_cart = Order.get_cart_for_user(admin_user)\n PaidCourseRegistration.add_to_order(admin_cart, self.course.id)\n admin_cart.purchase()\n\n # create a new user/student and enroll\n # in the course using a registration code\n # and then validates the generated detailed enrollment report\n test_user = UserFactory()\n self.register_with_redemption_code(test_user, course_registration_code.code)\n\n CourseFinanceAdminRole(self.course.id).add_users(self.instructor)\n UserProfileFactory.create(user=self.students[0], meta='{\"company\": \"asdasda\"}')\n\n self.client.login(username=self.instructor.username, password='test')\n url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {})\n self.assertIn('The detailed enrollment report is being created.', response.content)", "label": 0, "label_name": "vulnerable"} -{"code": " def create\n if !@resource.value(:source)\n create_repository(@resource.value(:path))\n else\n clone_repository(@resource.value(:revision))\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\teach: function( callback, args ) {\n\t\treturn jQuery.each( this, callback, args );\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": "ast2obj_keyword(void* _o)\n{\n keyword_ty o = (keyword_ty)_o;\n PyObject *result = NULL, *value = NULL;\n if (!o) {\n Py_RETURN_NONE;\n }\n\n result = PyType_GenericNew(keyword_type, NULL, NULL);\n if (!result) return NULL;\n value = ast2obj_identifier(o->arg);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_arg, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_expr(o->value);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_value, value) == -1)\n goto failed;\n Py_DECREF(value);\n return result;\nfailed:\n Py_XDECREF(value);\n Py_XDECREF(result);\n return NULL;\n}", "label": 1, "label_name": "safe"} -{"code": "\tpublic function paramRules() {\n $parentRules = parent::paramRules ();\n $parentRules['options'] = array_merge (\n $parentRules['options'],\n array (\n array(\n 'name'=>'to',\n 'label'=>Yii::t( 'studio','To:'),\n 'type'=>'email'\n ),\n array(\n 'name' => 'template',\n 'label' => Yii::t('studio', 'Template'),\n 'type' => 'dropdown',\n 'defaultVal' => '',\n 'options' => array('' => Yii::t('studio', 'Custom')) + \n Docs::getEmailTemplates('email', 'Contacts')\n ),\n array(\n 'name' => 'subject',\n 'label' => Yii::t('studio', 'Subject'),\n 'optional' => 1\n ),\n array(\n 'name' => 'cc',\n 'label' => Yii::t('studio', 'CC:'),\n 'optional' => 1,\n 'type' => 'email'\n ),\n array(\n 'name' => 'bcc', \n 'label' => Yii::t('studio', 'BCC:'),\n 'optional' => 1,\n 'type' => 'email'\n ),\n array(\n 'name' => 'body', \n 'label' => Yii::t('studio', 'Message'),\n 'optional' => 1,\n 'type' => 'richtext'\n ),\n\n )\n );\n return $parentRules;\n }", "label": 1, "label_name": "safe"} -{"code": " public function testEmptyInput()\n {\n $this->assertResult('', false);\n }", "label": 1, "label_name": "safe"} -{"code": " public static function getKey($var)\n {\n return self::$hooks[$var];\n }", "label": 1, "label_name": "safe"} -{"code": " def create_repository(path)\n runcvs('-d', path, 'init')\n end", "label": 0, "label_name": "vulnerable"} -{"code": " protected function parseImplementation($var, $type, $allow_null)\n {\n return $var;\n }", "label": 1, "label_name": "safe"} -{"code": "function loadLocale(name) {\n var oldLocale = null,\n aliasedRequire;\n // TODO: Find a better way to register and load all the locales in Node\n if (\n locales[name] === undefined &&\n typeof module !== 'undefined' &&\n module &&\n module.exports\n ) {\n try {\n oldLocale = globalLocale._abbr;\n aliasedRequire = require;\n aliasedRequire('./locale/' + name);\n getSetGlobalLocale(oldLocale);\n } catch (e) {\n // mark as not found to avoid repeating expensive file require call causing high CPU\n // when trying to find en-US, en_US, en-us for every format call\n locales[name] = null; // null means not found\n }\n }\n return locales[name];\n}", "label": 0, "label_name": "vulnerable"} -{"code": " escape: function(value) {\n if (isString(value)) return '\\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\\'';\n if (isNumber(value)) return value.toString();\n if (value === true) return 'true';\n if (value === false) return 'false';\n if (value === null) return 'null';\n if (typeof value === 'undefined') return 'undefined';\n\n throw $parseMinErr('esc', 'IMPOSSIBLE');\n },", "label": 0, "label_name": "vulnerable"} -{"code": " function getUsername()\n {\n if (isset($this->session['username'])) {\n return($this->session['username']);\n }\n return('');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {\n super.onSuccessfulAuthentication(request,response,authResult);\n // make sure we have a session to store this successful authentication, given that we no longer\n // let HttpSessionContextIntegrationFilter2 to create sessions.\n // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later\n // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its\n // doFilter method.\n request.getSession().invalidate();\n request.getSession();\n }", "label": 1, "label_name": "safe"} -{"code": "export function buildQueryString(params: Object, traditional?: Boolean): string {\n let pairs = [];\n let keys = Object.keys(params || {}).sort();\n for (let i = 0, len = keys.length; i < len; i++) {\n let key = keys[i];\n pairs = pairs.concat(buildParam(key, params[key], traditional));\n }\n\n if (pairs.length === 0) {\n return '';\n }\n\n return pairs.join('&');\n}", "label": 0, "label_name": "vulnerable"} -{"code": " static buildSendOpReturn(config: configBuildSendOpReturn, type = 0x01) {\n return SlpTokenType1.buildSendOpReturn(\n config.tokenIdHex,\n config.outputQtyArray,\n type\n )\n }", "label": 0, "label_name": "vulnerable"} -{"code": " qtip: Tine.Tinebase.common.doubleEncode(attr.name),\n leaf: !!attr.account_grants,\n allowDrop: !!attr.account_grants && attr.account_grants.addGrant\n });\n\n // copy 'real' data to container space\n attr.container = Ext.copyTo({}, attr, Tine.Tinebase.Model.Container.getFieldNames());\n },", "label": 0, "label_name": "vulnerable"} -{"code": "mptctl_mpt_command (unsigned long arg)\n{\n\tstruct mpt_ioctl_command __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_command karg;\n\tMPT_ADAPTER\t*ioc;\n\tint\t\tiocnum;\n\tint\t\trc;\n\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_mpt_command - \"\n\t\t\t\"Unable to read in mpt_ioctl_command struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_mpt_command() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\trc = mptctl_do_mpt_command (karg, &uarg->MF);\n\n\treturn rc;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function load_from_post()\r\n\t{\r\n\t\t$this->title \t\t= $_REQUEST['title'];\r\n\t\t$this->file\t\t\t= $_REQUEST['file'];\r\n\t\t$this->permission\t= intval($_REQUEST['permission']);\r\n\t\t$this->enabled\t\t= intval($_REQUEST['enabled']);\t\r\n\t\t\r\n\t\t// sections\r\n\t\t$this->sections\t\t= array();\r\n\t\tfor($s = 0; $s < count($_REQUEST['template-sections-code']); $s++)\r\n\t\t{\r\n\t\t\tif(empty($_REQUEST['template-sections-code'][$s])) continue;\r\n\t\t\t$this->sections[] = array(\r\n\t\t\t 'code' => $_REQUEST['template-sections-code'][$s],\r\n\t\t\t\t'name' => $_REQUEST['template-sections-name'][$s],\r\n\t\t\t\t'editor' => $_REQUEST['template-sections-editor'][$s],\r\n\t\t\t\t'width' => $_REQUEST['template-sections-width'][$s]\r\n );\r\n\t\t}\r\n\t\tif(empty($this->sections))\r\n\t\t{\r\n\t\t\t$this->sections = array(\r\n\t\t\t\t0 => array(\r\n\t\t\t\t\t'code' => 'id',\r\n\t\t\t\t\t'name' => '#main#',\r\n\t\t\t\t\t'editor' => 'tinymce',\r\n\t\t\t\t\t'width' => '960'\r\n\t\t\t\t)\r\n\t\t\t);\r\n\t\t}\r\n\t\t\r\n\t\t$this->gallery\t\t= intval($_REQUEST['gallery']);\t\r\n\t\t$this->comments\t\t= intval($_REQUEST['comments']);\t\r\n\t\t$this->tags\t\t\t= intval($_REQUEST['tags']);\t\r\n\t\t$this->statistics\t= intval($_REQUEST['statistics']);\t\t\t\t\t\t\t\t\r\n\t}\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function testLocateResourceIgnoresDirOnNonResource()\n {\n $kernel = $this->getKernel(array('getBundle'));\n $kernel\n ->expects($this->once())\n ->method('getBundle')\n ->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))\n ;\n\n $this->assertEquals(\n __DIR__.'/Fixtures/Bundle1Bundle/foo.txt',\n $kernel->locateResource('@Bundle1Bundle/foo.txt', __DIR__.'/Fixtures')\n );\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function configure() {\n expHistory::set('editable', $this->params);\n // little bit of trickery so that that categories can have their own configs\n \n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n $this->config = $config->config;\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);\n $views = expTemplate::get_config_templates($this, $this->loc);\n \n $gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all');\n \n assign_to_template(array(\n 'config'=>$this->config,\n 'pullable_modules'=>$pullable_modules,\n 'views'=>$views,\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'title'=>static::displayname()\n ));\n } ", "label": 0, "label_name": "vulnerable"} -{"code": "var getValue = function(obj, key) {\n var o = obj;\n var keys = Array.isArray(key) ? key : key.split('.');\n\n for (var x = 0; x < keys.length -1; ++x) {\n var k = keys[x];\n if (!o[k]) return;\n o = o[k];\n }\n\n return o[keys[keys.length - 1]];\n};", "label": 0, "label_name": "vulnerable"} -{"code": "int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)\n{\n\tstruct sctp_association *asoc = sctp_id2assoc(sk, id);\n\tstruct sctp_sock *sp = sctp_sk(sk);\n\tstruct socket *sock;\n\tint err = 0;\n\n\t/* Do not peel off from one netns to another one. */\n\tif (!net_eq(current->nsproxy->net_ns, sock_net(sk)))\n\t\treturn -EINVAL;\n\n\tif (!asoc)\n\t\treturn -EINVAL;\n\n\t/* If there is a thread waiting on more sndbuf space for\n\t * sending on this asoc, it cannot be peeled.\n\t */\n\tif (waitqueue_active(&asoc->wait))\n\t\treturn -EBUSY;\n\n\t/* An association cannot be branched off from an already peeled-off\n\t * socket, nor is this supported for tcp style sockets.\n\t */\n\tif (!sctp_style(sk, UDP))\n\t\treturn -EINVAL;\n\n\t/* Create a new socket. */\n\terr = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);\n\tif (err < 0)\n\t\treturn err;\n\n\tsctp_copy_sock(sock->sk, sk, asoc);\n\n\t/* Make peeled-off sockets more like 1-1 accepted sockets.\n\t * Set the daddr and initialize id to something more random\n\t */\n\tsp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);\n\n\t/* Populate the fields of the newsk from the oldsk and migrate the\n\t * asoc to the newsk.\n\t */\n\tsctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);\n\n\t*sockp = sock;\n\n\treturn err;\n}", "label": 1, "label_name": "safe"} -{"code": " public function toString()\n {\n return implode('', array_slice($this->tokens, $this->i + 1));\n }", "label": 1, "label_name": "safe"} -{"code": " it \"returns a stepped letter range given a negative step\" do\n result = scope.function_range([\"a\",\"d\",\"-2\"])\n expect(result).to eq ['a','c']\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def test_with_admins(self) -> None:\n no_admins = InstanceConfig(admins=None, allowed_aad_tenants=[UUID(int=0)])\n with_admins = InstanceConfig(\n admins=[UUID(int=0)], allowed_aad_tenants=[UUID(int=0)]\n )\n with_admins_2 = InstanceConfig(\n admins=[UUID(int=1)], allowed_aad_tenants=[UUID(int=0)]\n )\n\n no_admins.update(with_admins)\n self.assertEqual(no_admins.admins, None)\n\n with_admins.update(with_admins_2)\n self.assertEqual(with_admins.admins, with_admins_2.admins)", "label": 1, "label_name": "safe"} -{"code": " body: JSON.stringify({\n ...keys,\n _method: 'POST',\n email: 'someemail@somedomain.com',\n }),\n });\n await this.user.fetch({ useMasterKey: true });\n const passwordResetResponse = await request({\n url: `${serverURL}/apps/test/request_password_reset?username=someemail@somedomain.com&token[$regex]=`,\n method: 'GET',\n });\n expect(passwordResetResponse.status).toEqual(302);\n expect(passwordResetResponse.headers.location).toMatch(\n `\\\\/invalid\\\\_link\\\\.html`\n );\n await request({\n url: `${serverURL}/apps/test/request_password_reset`,\n method: 'POST',\n body: {\n token: { $regex: '' },\n username: 'someemail@somedomain.com',\n new_password: 'newpassword',\n },\n });\n try {\n await Parse.User.logIn('someemail@somedomain.com', 'newpassword');\n fail('should not work');\n } catch (e) {\n expect(e.code).toEqual(101);\n expect(e.message).toEqual('Invalid username/password.');\n }\n });", "label": 1, "label_name": "safe"} -{"code": "\t\t\tselectAll = function() {\n\t\t\t\tvar phash = fm.cwd().hash;\n\n\t\t\t\tcwd.find('[id]:not(.'+clSelected+'):not(.elfinder-cwd-parent)').trigger(evtSelect); \n\t\t\t\tselectedFiles = $.map(fm.files(), function(f) { return f.phash == phash ? f.hash : null ;});\n\t\t\t\ttrigger();\n\t\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " it 'exists' do\n provider.class.instances\n provider.class.prefetch({})\n end", "label": 0, "label_name": "vulnerable"} -{"code": "return this.editor.exportToCanvas(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createImageUrlConverter\");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImages\");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImageToDataUri\");", "label": 0, "label_name": "vulnerable"} -{"code": "def subscribe_for_tags(request):\n \"\"\"process subscription of users by tags\"\"\"\n #todo - use special separator to split tags\n tag_names = request.REQUEST.get('tags','').strip().split()\n pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)\n if request.user.is_authenticated():\n if request.method == 'POST':\n if 'ok' in request.POST:\n request.user.mark_tags(\n pure_tag_names,\n wildcards,\n reason = 'good',\n action = 'add'\n )\n request.user.message_set.create(\n message = _('Your tag subscription was saved, thanks!')\n )\n else:\n message = _(\n 'Tag subscription was canceled (undo).'\n ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}\n request.user.message_set.create(message = message)\n return HttpResponseRedirect(reverse('index'))\n else:\n data = {'tags': tag_names}\n return render(request, 'subscribe_for_tags.html', data)\n else:\n all_tag_names = pure_tag_names + wildcards\n message = _('Please sign in to subscribe for: %(tags)s') \\\n % {'tags': ', '.join(all_tag_names)}\n request.user.message_set.create(message = message)\n request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)\n return HttpResponseRedirect(url_utils.get_login_url())", "label": 0, "label_name": "vulnerable"} -{"code": " public function execute($image)\n {\n $width = $this->argument(0)->type('numeric')->required()->value();\n $height = $this->argument(1)->type('numeric')->required()->value();\n $x = $this->argument(2)->type('numeric')->required()->value();\n $y = $this->argument(3)->type('numeric')->required()->value();\n $callback = $this->argument(4)->type('closure')->value();\n\n $ellipse_classname = sprintf('\\Intervention\\Image\\%s\\Shapes\\EllipseShape',\n $image->getDriver()->getDriverName());\n\n $ellipse = new $ellipse_classname($width, $height);\n\n if ($callback instanceof Closure) {\n $callback($ellipse);\n }\n\n $ellipse->applyToImage($image, $x, $y);\n\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public string Write()\r\n {\r\n var sb = new StringBuilder();\r\n\r\n //do tables\r\n foreach (var table in Schema.Tables)\r\n {\r\n var tableGenerator = LoadTableGenerator(table);\r\n tableGenerator.IncludeSchema = IncludeSchema;\r\n tableGenerator.EscapeNames = EscapeNames;\r\n sb.AppendLine(tableGenerator.Write());\r\n }\r\n sb.AppendLine();\r\n\r\n //now we can do foreign keys\r\n foreach (var table in Schema.Tables)\r\n {\r\n var constraintWriter = LoadConstraintWriter(table);\r\n //SQLite has no ALTER TABLE support, so this is not supported\r\n if (constraintWriter == null) continue;\r\n constraintWriter.IncludeSchema = IncludeSchema;\r\n constraintWriter.EscapeNames = EscapeNames;\r\n sb.AppendLine(constraintWriter.WriteForeignKeys());\r\n }\r\n sb.AppendLine();\r\n\r\n //in case we want to delete it again\r\n WriteDrops(sb);\r\n sb.AppendLine();\r\n\r\n return sb.ToString();\r\n }\r", "label": 1, "label_name": "safe"} -{"code": "def auth(params, request, session)\n token = PCSAuth.validUser(params['username'],params['password'], true)\n # If we authorized to this machine, attempt to authorize everywhere\n node_list = []\n if token and params[\"bidirectional\"]\n params.each { |k,v|\n if k.start_with?(\"node-\")\n node_list.push(v)\n end\n }\n if node_list.length > 0\n pcs_auth(\n session, node_list, params['username'], params['password'],\n params[\"force\"] == \"1\"\n )\n end\n end\n return token\nend", "label": 0, "label_name": "vulnerable"} -{"code": " int64_t length() const {\n return m_str ? m_str->size() : 0;\n }", "label": 1, "label_name": "safe"} -{"code": " public function isBase64()\n {\n if (!is_string($this->data)) {\n return false;\n }\n\n return base64_encode(base64_decode($this->data)) === $this->data;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "mxShape.prototype.clear=function(){if(null!=this.node.ownerSVGElement)for(;null!=this.node.lastChild;)this.node.removeChild(this.node.lastChild);else this.node.style.cssText=\"position:absolute;\"+(null!=this.cursor?\"cursor:\"+this.cursor+\";\":\"\"),this.node.innerHTML=\"\"};", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct($max = null)\n {\n $this->max = $max;\n }", "label": 1, "label_name": "safe"} -{"code": "\t\tgo = function(fwd) {\n\t\t\tif ((fwd && self.canForward()) || (!fwd && self.canBack())) {\n\t\t\t\tupdate = false;\n\t\t\t\treturn fm.exec('open', history[fwd ? ++current : --current]).fail(reset);\n\t\t\t}\n\t\t\treturn $.Deferred().reject();\n\t\t};", "label": 0, "label_name": "vulnerable"} -{"code": "def test_external_interface_bytes_clampers(get_contract, assert_tx_failed):\n external_contract = \"\"\"\n@external\ndef ok() -> Bytes[2]:\n return b\"12\"\n\n@external\ndef should_fail() -> Bytes[3]:\n return b\"123\"\n \"\"\"\n\n code = \"\"\"\ninterface BadContract:\n def ok() -> Bytes[2]: view\n def should_fail() -> Bytes[2]: view\n\nfoo: BadContract\n\n@external\ndef __init__(addr: BadContract):\n self.foo = addr\n\n\n@external\ndef test_ok() -> Bytes[2]:\n return self.foo.ok()\n\n@external\ndef test_fail() -> Bytes[3]:\n return self.foo.should_fail()\n \"\"\"\n\n bad_c = get_contract(external_contract)\n c = get_contract(code, bad_c.address)\n assert bad_c.ok() == b\"12\"\n assert bad_c.should_fail() == b\"123\"\n\n assert c.test_ok() == b\"12\"\n assert_tx_failed(lambda: c.test_fail())", "label": 1, "label_name": "safe"} -{"code": " public static function custom($vars) {\r\n $url = $vars;\r\n return $url;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "exports.get = function(obj, path) {\n\n\tvar cachekey = 'G=' + path;\n\n\tif (F.temporary.other[cachekey])\n\t\treturn F.temporary.other[cachekey](obj);\n\n\tvar arr = parsepath(path);\n\tvar builder = [];\n\n\tfor (var i = 0, length = arr.length - 1; i < length; i++)\n\t\tbuilder.push('if(!w' + (!arr[i] || arr[i][0] === '[' ? '' : '.') + arr[i] + ')return');\n\n\tvar v = arr[arr.length - 1];\n\tvar fn = (new Function('w', builder.join(';') + ';return w' + (v[0] === '[' ? '' : '.') + v));\n\tF.temporary.other[cachekey] = fn;\n\treturn fn(obj);\n};", "label": 0, "label_name": "vulnerable"} -{"code": " $scope.deleteNode = function(node) {\n bootbox.confirm('Are you sure you want to remove the node ' + _.escape(node.nodeLabel) + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteNode(node).then(\n function() { // success\n var index = -1;\n for(var i = 0; i < $scope.filteredNodes.length; i++) {\n if ($scope.filteredNodes[i].foreignId === node.foreignId) {\n index = i;\n }\n }\n if (index > -1) {\n $scope.filteredNodes.splice(index,1);\n }\n growl.success('The node ' + _.escape(node.nodeLabel) + ' has been deleted.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label": 1, "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){null==b||null==this.tokenRefreshThread||6E4>this.tokenExpiresOn-Date.now()?this.authenticate(e,this.emptyFn):e()};OneDriveClient.prototype.getItemRef=", "label": 0, "label_name": "vulnerable"} -{"code": " def test_erb_escape\n string = [192, 60].pack('CC')\n expected = 192.chr + \"<\"\n assert_equal expected, ERB::Util.html_escape(string)\n end", "label": 1, "label_name": "safe"} -{"code": " public function testCanCreateNewResponseWithStatusAndNoReason()\n {\n $r = new Response(200);\n $r2 = $r->withStatus(201);\n $this->assertEquals(200, $r->getStatusCode());\n $this->assertEquals('OK', $r->getReasonPhrase());\n $this->assertEquals(201, $r2->getStatusCode());\n $this->assertEquals('Created', $r2->getReasonPhrase());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " private function init($config) {\n if (!$this->init) {\n $def = $config->getHTMLDefinition();\n // allow all inline elements\n $this->real_elements = $this->elements;\n $this->fake_elements = $def->info_content_sets['Flow'];\n $this->fake_elements['#PCDATA'] = true;\n $this->init = true;\n }\n }", "label": 1, "label_name": "safe"} -{"code": "function GoodAuthDigestTestController($serverPort) {\n $args = array('Authorization' => 'Digest username=\"admin\", ' .\n 'realm=\"Restricted area\", nonce=\"564a12611dae8\", ' .\n 'uri=\"/test_auth_digest.php\", cnonce=\"MjIyMTg1\", nc=00000001, ' .\n 'qop=\"auth\", response=\"e544aaed06917adea3e5c74dd49f0e32\", ' .\n 'opaque=\"cdce8a5c95a1427d74df7acbf41c9ce0\"');\n var_dump(request('localhost', $serverPort, \"test_auth_digest.php\",\n [], [], $args));\n}", "label": 1, "label_name": "safe"} -{"code": "spnego_gss_wrap_iov(OM_uint32 *minor_status,\n\t\t gss_ctx_id_t context_handle,\n\t\t int conf_req_flag,\n\t\t gss_qop_t qop_req,\n\t\t int *conf_state,\n\t\t gss_iov_buffer_desc *iov,\n\t\t int iov_count)\n{\n\tOM_uint32 ret;\n\tret = gss_wrap_iov(minor_status,\n\t\t\t context_handle,\n\t\t\t conf_req_flag,\n\t\t\t qop_req,\n\t\t\t conf_state,\n\t\t\t iov,\n\t\t\t iov_count);\n\treturn (ret);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static bool glfs_check_config(const char *cfgstring, char **reason)\n{\n\tchar *path;\n\tglfs_t *fs = NULL;\n\tglfs_fd_t *gfd = NULL;\n\tgluster_server *hosts = NULL; /* gluster server defination */\n\tbool result = true;\n\n\tpath = strchr(cfgstring, '/');\n\tif (!path) {\n\t\tif (asprintf(reason, \"No path found\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto done;\n\t}\n\tpath += 1; /* get past '/' */\n\n\tfs = tcmu_create_glfs_object(path, &hosts);\n\tif (!fs) {\n\t\ttcmu_err(\"tcmu_create_glfs_object failed\\n\");\n\t\tgoto done;\n\t}\n\n\tgfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS);\n\tif (!gfd) {\n\t\tif (asprintf(reason, \"glfs_open failed: %m\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto unref;\n\t}\n\n\tif (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) {\n\t\tif (asprintf(reason, \"glfs_access file not present, or not writable\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto unref;\n\t}\n\n\tgoto done;\n\nunref:\n\tgluster_cache_refresh(fs, path);\n\ndone:\n\tif (gfd)\n\t\tglfs_close(gfd);\n\tgluster_free_server(&hosts);\n\n\treturn result;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "F.createStatusContainer();F.statusContainer.style.position=\"relative\";F.statusContainer.style.maxWidth=\"\";F.statusContainer.style.marginTop=\"7px\";F.statusContainer.style.marginLeft=\"6px\";F.statusContainer.style.color=\"gray\";F.statusContainer.style.cursor=\"default\";var W=F.hideCurrentMenu;F.hideCurrentMenu=function(){W.apply(this,arguments);this.editor.graph.popupMenuHandler.hideMenu()};var U=F.descriptorChanged;F.descriptorChanged=function(){U.apply(this,arguments);var da=F.getCurrentFile();if(null!=\nda&&null!=da.getTitle()){var ca=da.getMode();\"google\"==ca?ca=\"googleDrive\":\"github\"==ca?ca=\"gitHub\":\"gitlab\"==ca?ca=\"gitLab\":\"onedrive\"==ca&&(ca=\"oneDrive\");ca=mxResources.get(ca);S.setAttribute(\"title\",da.getTitle()+(null!=ca?\" (\"+ca+\")\":\"\"))}else S.removeAttribute(\"title\")};F.setStatusText(F.editor.getStatus());S.appendChild(F.statusContainer);F.buttonContainer=document.createElement(\"div\");F.buttonContainer.style.cssText=\"position:absolute;right:0px;padding-right:34px;top:10px;white-space:nowrap;padding-top:2px;background-color:inherit;\";", "label": 0, "label_name": "vulnerable"} -{"code": "H.x+\" \"+H.y;S=\"\";c=[];for(U=2;Ul;)v.shift()},N=", "label": 0, "label_name": "vulnerable"} -{"code": " consume: function(e1) {\n if (this.tokens.length === 0) {\n throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n }\n\n var token = this.expect(e1);\n if (!token) {\n this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());\n }\n return token;\n },", "label": 0, "label_name": "vulnerable"} -{"code": "def admin():\n version = updater_thread.get_current_version_info()\n if version is False:\n commit = _(u'Unknown')\n else:\n if 'datetime' in version:\n commit = version['datetime']\n\n tz = timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone)\n form_date = datetime.strptime(commit[:19], \"%Y-%m-%dT%H:%M:%S\")\n if len(commit) > 19: # check if string has timezone\n if commit[19] == '+':\n form_date -= timedelta(hours=int(commit[20:22]), minutes=int(commit[23:]))\n elif commit[19] == '-':\n form_date += timedelta(hours=int(commit[20:22]), minutes=int(commit[23:]))\n commit = format_datetime(form_date - tz, format='short', locale=get_locale())\n else:\n commit = version['version']\n\n allUser = ub.session.query(ub.User).all()\n email_settings = config.get_mail_settings()\n kobo_support = feature_support['kobo'] and config.config_kobo_sync\n return render_title_template(\"admin.html\", allUser=allUser, email=email_settings, config=config, commit=commit,\n feature_support=feature_support, kobo_support=kobo_support,\n title=_(u\"Admin page\"), page=\"admin\")", "label": 0, "label_name": "vulnerable"} -{"code": " it { should be_file }", "label": 0, "label_name": "vulnerable"} -{"code": " public function save_change_password() {\n global $user;\n\n $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;\n\n if (!$user->isAdmin() && !$isuser) {\n flash('error', gt('You do not have permissions to change this users password.'));\n expHistory::back();\n }\n\n if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {\n flash('error', gt('The current password you entered is not correct.'));\n expHistory::returnTo('editable');\n }\n //eDebug($user);\n $u = new user($this->params['uid']);\n\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n //eDebug($u, true);\n if (is_string($ret)) {\n flash('error', $ret);\n expHistory::returnTo('editable');\n } else {\n $params = array();\n $params['is_admin'] = !empty($u->is_admin);\n $params['is_acting_admin'] = !empty($u->is_acting_admin);\n $u->update($params);\n }\n\n if (!$isuser) {\n flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));\n } else {\n $user->password = $u->password;\n flash('message', gt('Your password has been changed.'));\n }\n expHistory::back();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getMethod()\n {\n if (null !== $this->method) {\n return $this->method;\n }\n\n $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));\n\n if ('POST' !== $this->method) {\n return $this->method;\n }\n\n $method = $this->headers->get('X-HTTP-METHOD-OVERRIDE');\n\n if (!$method && self::$httpMethodParameterOverride) {\n $method = $this->request->get('_method', $this->query->get('_method', 'POST'));\n }\n\n if (!\\is_string($method)) {\n return $this->method;\n }\n\n $method = strtoupper($method);\n\n if (\\in_array($method, ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH', 'PURGE', 'TRACE'], true)) {\n return $this->method = $method;\n }\n\n if (!preg_match('/^[A-Z]++$/D', $method)) {\n throw new SuspiciousOperationException(sprintf('Invalid method override \"%s\".', $method));\n }\n\n return $this->method = $method;\n }", "label": 1, "label_name": "safe"} -{"code": "ftrace_regex_lseek(struct file *file, loff_t offset, int whence)\n{\n\tloff_t ret;\n\n\tif (file->f_mode & FMODE_READ)\n\t\tret = seq_lseek(file, offset, whence);\n\telse\n\t\tfile->f_pos = ret = 1;\n\n\treturn ret;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"returns the default logger\" do\n config.logger.should eq logger\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def homepage(spec)\n URI.parse(URI.escape(spec.homepage))\n end", "label": 1, "label_name": "safe"} -{"code": " def test_list_course_role_members_noparams(self):\n \"\"\" Test missing all query parameters. \"\"\"\n url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.post(url)\n self.assertEqual(response.status_code, 400)", "label": 1, "label_name": "safe"} -{"code": " public function transform($attr, $config, $context)\n {\n if (!isset($attr['type'])) {\n $attr['type'] = 'text/javascript';\n }\n return $attr;\n }", "label": 1, "label_name": "safe"} -{"code": " private function computeErrorsCount()\n {\n $count = array(\n 'error_count' => $this->logger->countErrors(),\n 'deprecation_count' => 0,\n 'scream_count' => 0,\n 'priorities' => array(),\n );\n\n foreach ($this->logger->getLogs() as $log) {\n if (isset($count['priorities'][$log['priority']])) {\n ++$count['priorities'][$log['priority']]['count'];\n } else {\n $count['priorities'][$log['priority']] = array(\n 'count' => 1,\n 'name' => $log['priorityName'],\n );\n }\n\n if (isset($log['context']['type'], $log['context']['level'])) {\n if (E_DEPRECATED === $log['context']['type'] || E_USER_DEPRECATED === $log['context']['type']) {\n ++$count['deprecation_count'];\n } elseif (!($log['context']['type'] & $log['context']['level'])) {\n ++$count['scream_count'];\n }\n }\n }\n\n ksort($count['priorities']);\n\n return $count;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static int may_create_in_sticky(umode_t dir_mode, kuid_t dir_uid,\n\t\t\t\tstruct inode * const inode)\n{\n\tif ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||\n\t (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||\n\t likely(!(dir_mode & S_ISVTX)) ||\n\t uid_eq(inode->i_uid, dir_uid) ||\n\t uid_eq(current_fsuid(), inode->i_uid))\n\t\treturn 0;\n\n\tif (likely(dir_mode & 0002) ||\n\t (dir_mode & 0020 &&\n\t ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||\n\t (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {\n\t\tconst char *operation = S_ISFIFO(inode->i_mode) ?\n\t\t\t\t\t\"sticky_create_fifo\" :\n\t\t\t\t\t\"sticky_create_regular\";\n\t\taudit_log_path_denied(AUDIT_ANOM_CREAT, operation);\n\t\treturn -EACCES;\n\t}\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": " public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n DefaultArgumentConversionContext that = (DefaultArgumentConversionContext) o;\n return Objects.equals(getArgument(), that.getArgument()) &&\n Objects.equals(finalLocale, that.finalLocale) &&\n Objects.equals(finalCharset, that.finalCharset);\n }", "label": 1, "label_name": "safe"} -{"code": " private string BuildTcpRemotingUri()\r\n {\r\n return string.Format(\"tcp://{0}:{1}/{2}\", SvcConfiguration.RemotingUriHost, SvcConfiguration.RemotingPort, SvcConfiguration.RemotingUri);\r\n }\r", "label": 1, "label_name": "safe"} -{"code": "\tpublic static function onParserFirstCallInit( Parser $parser ) {\n\t\tself::init();\n\n\t\t// DPL offers the same functionality as Intersection. So we register the tag in case LabeledSection Extension is not installed so that the section markers are removed.\n\t\tif ( Config::getSetting( 'handleSectionTag' ) ) {\n\t\t\t$parser->setHook( 'section', [ __CLASS__, 'dplTag' ] );\n\t\t}\n\n\t\t$parser->setHook( 'DPL', [ __CLASS__, 'dplTag' ] );\n\t\t$parser->setHook( 'DynamicPageList', [ __CLASS__, 'intersectionTag' ] );\n\n\t\t$parser->setFunctionHook( 'dpl', [ __CLASS__, 'dplParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplnum', [ __CLASS__, 'dplNumParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplvar', [ __CLASS__, 'dplVarParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplreplace', [ __CLASS__, 'dplReplaceParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplchapter', [ __CLASS__, 'dplChapterParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplmatrix', [ __CLASS__, 'dplMatrixParserFunction' ] );\n\t}", "label": 1, "label_name": "safe"} -{"code": " protected function getJobIdFromWidgetConfiguration()\n {\n $db = \\Tuleap\\DB\\DBFactory::getMainTuleapDBConnection()->getDB();\n $job_id = $db->cell(\n 'SELECT job_id FROM plugin_hudson_widget WHERE widget_name = ? AND owner_id = ? AND owner_type = ? AND id = ?',\n $this->widget_id,\n $this->owner_id,\n $this->owner_type,\n $this->content_id,\n );\n\n if ($job_id === false) {\n return null;\n }\n\n return $job_id;\n }", "label": 1, "label_name": "safe"} -{"code": " public function validateReference()\n {\n $docElem = $this->sigNode->ownerDocument->documentElement;\n if (! $docElem->isSameNode($this->sigNode)) {\n if ($this->sigNode->parentNode != null) {\n $this->sigNode->parentNode->removeChild($this->sigNode);\n }\n }\n $xpath = $this->getXPathObj();\n $query = \"./secdsig:SignedInfo/secdsig:Reference\";\n $nodeset = $xpath->query($query, $this->sigNode);\n if ($nodeset->length == 0) {\n throw new Exception(\"Reference nodes not found\");\n }\n\n /* Initialize/reset the list of validated nodes. */\n $this->validatedNodes = array();\n\n foreach ($nodeset AS $refNode) {\n if (! $this->processRefNode($refNode)) {\n /* Clear the list of validated nodes. */\n $this->validatedNodes = null;\n throw new Exception(\"Reference validation failed\");\n }\n }\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function limit($value)\n {\n if ($value >= 0) {\n $this->limit = $value;\n }\n\n return $this;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function send_feedback() {\n $success = false;\n if (isset($this->params['id'])) {\n $ed = new eventdate($this->params['id']);\n// $email_addrs = array();\n if ($ed->event->feedback_email != '') {\n $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . expString::escape($this->params['formname']), $this->loc);\n $msgtemplate->assign('params', $this->params);\n $msgtemplate->assign('event', $ed);\n $email_addrs = explode(',', $ed->event->feedback_email);\n //This is an easy way to remove duplicates\n $email_addrs = array_flip(array_flip($email_addrs));\n $email_addrs = array_map('trim', $email_addrs);\n $mail = new expMail();\n $success += $mail->quickSend(array(\n \"text_message\" => $msgtemplate->render(),\n 'to' => $email_addrs,\n 'from' => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),\n 'subject' => $this->params['subject'],\n ));\n }\n }\n\n if ($success) {\n flashAndFlow('message', gt('Your feedback was successfully sent.'));\n } else {\n flashAndFlow('error', gt('We could not send your feedback. Please contact your administrator.'));\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public boolean needAppToken() {\n return true;\n }", "label": 1, "label_name": "safe"} -{"code": " def test_get_students_features_cohorted(self, is_cohorted):\n \"\"\"\n Test that get_students_features includes cohort info when the course is\n cohorted, and does not when the course is not cohorted.\n \"\"\"\n url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)})\n set_course_cohort_settings(self.course.id, is_cohorted=is_cohorted)\n\n response = self.client.get(url, {})\n res_json = json.loads(response.content)\n\n self.assertEqual('cohort' in res_json['feature_names'], is_cohorted)", "label": 0, "label_name": "vulnerable"} -{"code": " public static function mb_language($lang = null)\n {\n if (null === $lang) {\n return self::$language;\n }\n\n switch ($lang = strtolower($lang)) {\n case 'uni':\n case 'neutral':\n self::$language = $lang;\n\n return true;\n }\n\n return false;\n }", "label": 1, "label_name": "safe"} -{"code": "function setHashKey(obj, h) {\n if (h) {\n obj.$$hashKey = h;\n } else {\n delete obj.$$hashKey;\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "def add_fence_level(auth_user, level, devices, node, remove = false)\n if not remove\n stdout, stderr, retval = run_cmd(\n auth_user, PCS, \"stonith\", \"level\", \"add\", level, node, devices\n )\n return retval,stdout, stderr\n else\n stdout, stderr, retval = run_cmd(\n auth_user, PCS, \"stonith\", \"level\", \"remove\", level, node, devices\n )\n return retval,stdout, stderr\n end\nend", "label": 1, "label_name": "safe"} -{"code": " GraphQLPlayground.init(root, ${JSON.stringify(\n extendedOptions,\n null,\n 2,\n )})\n })", "label": 0, "label_name": "vulnerable"} -{"code": " public static function DragnDropReRank2() {\n global $router, $db;\n\n $id = $router->params['id'];\n $page = new section($id);\n $old_rank = $page->rank;\n $old_parent = $page->parent;\n $new_rank = $router->params['position'] + 1; // rank\n $new_parent = intval($router->params['parent']);\n\n $db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent); // close in hole\n $db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent); // make room\n\n $params = array();\n $params['parent'] = $new_parent;\n $params['rank'] = $new_rank;\n $page->update($params);\n\n self::checkForSectionalAdmins($id);\n expSession::clearAllUsersSessionCache('navigation');\n }", "label": 1, "label_name": "safe"} -{"code": "static void set_own_dir(const char *argv0) {\n\tsize_t l = strlen(argv0);\n\twhile(l && argv0[l - 1] != '/')\n\t\tl--;\n\tif(l == 0)\n#ifdef SUPER_SECURE\n\t\tmemcpy(own_dir, \"/dev/null/\", 2);\n#else\n\t\tmemcpy(own_dir, \".\", 2);\n#endif\n\telse {\n\t\tmemcpy(own_dir, argv0, l - 1);\n\t\town_dir[l] = 0;\n\t}\n}", "label": 1, "label_name": "safe"} -{"code": "static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)\n{\n\tjpc_ppm_t *ppm = &ms->parms.ppm;\n\n\t/* Eliminate compiler warning about unused variables. */\n\tcstate = 0;\n\n\tif (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {\n\t\treturn -1;\n\t}\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tmakeDataTable = function(perm, f) {\n\t\t\tvar _perm, fieldset;\n\t\t\tvar value = '';\n\t\t\tvar dataTable = tpl.dataTable;\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\tvalue += _perm.toString(8);\n\t\t\t\tfieldset = tpl.fieldset.replace('{f_title}', fm.i18n(level[i])).replace('{name}', makeName(f[level[i]])).replace(/\\{level\\}/g, level[i]);\n\t\t\t\tdataTable = dataTable.replace('{'+i+'}', fieldset)\n\t\t\t\t .replace('{checked-r}', ((_perm & 4) == 4)? checked : '')\n\t\t\t\t .replace('{checked-w}', ((_perm & 2) == 2)? checked : '')\n\t\t\t\t .replace('{checked-x}', ((_perm & 1) == 1)? checked : '');\n\t\t\t}\n\t\t\tdataTable = dataTable.replace('{value}', value).replace('{valueCaption}', msg['perm']);\n\t\t\treturn dataTable;\n\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " public function handleError(array $error, FatalErrorException $exception)\n {\n $messageLen = strlen($error['message']);\n $notFoundSuffix = '()';\n $notFoundSuffixLen = strlen($notFoundSuffix);\n if ($notFoundSuffixLen > $messageLen) {\n return;\n }\n\n if (0 !== substr_compare($error['message'], $notFoundSuffix, -$notFoundSuffixLen)) {\n return;\n }\n\n $prefix = 'Call to undefined function ';\n $prefixLen = strlen($prefix);\n if (0 !== strpos($error['message'], $prefix)) {\n return;\n }\n\n $fullyQualifiedFunctionName = substr($error['message'], $prefixLen, -$notFoundSuffixLen);\n if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedFunctionName, '\\\\')) {\n $functionName = substr($fullyQualifiedFunctionName, $namespaceSeparatorIndex + 1);\n $namespacePrefix = substr($fullyQualifiedFunctionName, 0, $namespaceSeparatorIndex);\n $message = sprintf('Attempted to call function \"%s\" from namespace \"%s\".', $functionName, $namespacePrefix);\n } else {\n $functionName = $fullyQualifiedFunctionName;\n $message = sprintf('Attempted to call function \"%s\" from the global namespace.', $functionName);\n }\n\n $candidates = array();\n foreach (get_defined_functions() as $type => $definedFunctionNames) {\n foreach ($definedFunctionNames as $definedFunctionName) {\n if (false !== $namespaceSeparatorIndex = strrpos($definedFunctionName, '\\\\')) {\n $definedFunctionNameBasename = substr($definedFunctionName, $namespaceSeparatorIndex + 1);\n } else {\n $definedFunctionNameBasename = $definedFunctionName;\n }\n\n if ($definedFunctionNameBasename === $functionName) {\n $candidates[] = '\\\\'.$definedFunctionName;\n }\n }\n }\n\n if ($candidates) {\n sort($candidates);\n $last = array_pop($candidates).'\"?';\n if ($candidates) {\n $candidates = 'e.g. \"'.implode('\", \"', $candidates).'\" or \"'.$last;\n } else {\n $candidates = '\"'.$last;\n }\n $message .= \"\\nDid you mean to call \".$candidates;\n }\n\n return new UndefinedFunctionException($message, $exception);\n }", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": "function(n){g.editorUiRefresh.apply(b,arguments);u()};u();var q=document.createElement(\"canvas\");q.width=m.offsetWidth;q.height=m.offsetHeight;m.style.overflow=\"hidden\";q.style.position=\"relative\";m.appendChild(q);var v=q.getContext(\"2d\");this.ui=b;var y=b.editor.graph;this.graph=y;this.container=m;this.canvas=q;var A=function(n,x,K,B,F){n=Math.round(n);x=Math.round(x);K=Math.round(K);B=Math.round(B);v.beginPath();v.moveTo(n+.5,x+.5);v.lineTo(K+.5,B+.5);v.stroke();F&&(l?(v.save(),v.translate(n,x),\nv.rotate(-Math.PI/2),v.fillText(F,0,0),v.restore()):v.fillText(F,n,x))},z=function(){v.clearRect(0,0,q.width,q.height);v.beginPath();v.lineWidth=.7;v.strokeStyle=k.strokeClr;v.setLineDash([]);v.font=\"9px Arial\";v.textAlign=\"center\";var n=y.view.scale,x=y.view.getBackgroundPageBounds(),K=y.view.translate,B=y.pageVisible;K=B?e+(l?x.y-y.container.scrollTop:x.x-y.container.scrollLeft):e+(l?K.y*n-y.container.scrollTop:K.x*n-y.container.scrollLeft);var F=0;B&&(F=y.getPageLayout(),F=l?F.y*y.pageFormat.height:", "label": 1, "label_name": "safe"} -{"code": " LiteralString(const std::string &s, bool ignore_case)\n : lit_(s), ignore_case_(ignore_case), is_word_(false) {}", "label": 1, "label_name": "safe"} -{"code": "def get_avail_fence_agents(params, request, auth_user)\n if not allowed_for_local_cluster(auth_user, Permissions::READ)\n return 403, 'Permission denied'\n end\n agents = getFenceAgents(auth_user)\n return JSON.generate(agents)\nend", "label": 1, "label_name": "safe"} -{"code": " $scope.save = function() {\n var form = this.nodeForm;\n RequisitionsService.startTiming();\n RequisitionsService.saveNode($scope.node).then(\n function() { // success\n growl.success('The node ' + _.escape($scope.node.nodeLabel) + ' has been saved.');\n $scope.foreignId = $scope.node.foreignId;\n form.$dirty = false;\n },\n $scope.errorHandler\n );\n };", "label": 1, "label_name": "safe"} -{"code": "\t\tenable : function() { this.update(void(0), this.value); },", "label": 0, "label_name": "vulnerable"} -{"code": "static HashTable *spl_array_get_gc(zval *object, zval ***gc_data, int *gc_data_count TSRMLS_DC) /* {{{ */\n{\n\tspl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);\n\n\t*gc_data = &intern->array;\n\t*gc_data_count = 1;\n\treturn zend_std_get_properties(object);\n}", "label": 1, "label_name": "safe"} -{"code": "def publisher_list():\n if current_user.get_view_property('publisher', 'dir') == 'desc':\n order = db.Publishers.name.desc()\n order_no = 0\n else:\n order = db.Publishers.name.asc()\n order_no = 1\n if current_user.check_visibility(constants.SIDEBAR_PUBLISHER):\n entries = calibre_db.session.query(db.Publishers, func.count('books_publishers_link.book').label('count')) \\\n .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \\\n .group_by(text('books_publishers_link.publisher')).order_by(order).all()\n char_list = generate_char_list(db.Publishers.name, db.books_publishers_link)\n return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=char_list,\n title=_(u\"Publishers\"), page=\"publisherlist\", data=\"publisher\", order=order_no)\n else:\n abort(404)", "label": 1, "label_name": "safe"} -{"code": " public function getAliases()\n {\n return $this->aliasDefinitions;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\t\t\t\ttop : Math.max(0, parseInt((parent.height() - dialog.outerHeight())/2 - 42))+'px',\n\t\t\t\t\t\t\tleft : Math.max(0, parseInt((parent.width() - dialog.outerWidth())/2))+'px'\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tdialog.css(css);\n\t\t\t\t})", "label": 0, "label_name": "vulnerable"} -{"code": " public function testParagraphWrappingOnlyLink()\n {\n $this->assertResult(\n 'http://example.com',\n '

http://example.com

'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " link: new ApolloLink((operation, forward) => {\n return forward(operation).map((response) => {\n const context = operation.getContext();\n const {\n response: { headers },\n } = context;\n expect(headers.get('access-control-allow-origin')).toEqual('*');\n checked = true;\n return response;\n });\n }).concat(", "label": 0, "label_name": "vulnerable"} -{"code": " static function dropdownConnect($itemtype, $fromtype, $myname, $entity_restrict = -1,\n $onlyglobal = 0, $used = []) {\n global $CFG_GLPI;\n\n $rand = mt_rand();\n\n $field_id = Html::cleanId(\"dropdown_\".$myname.$rand);\n $param = [\n 'entity_restrict' => $entity_restrict,\n 'fromtype' => $fromtype,\n 'itemtype' => $itemtype,\n 'onlyglobal' => $onlyglobal,\n 'used' => $used,\n '_idor_token' => Session::getNewIDORToken($itemtype),\n ];\n\n echo Html::jsAjaxDropdown($myname, $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownConnect.php\",\n $param);\n\n return $rand;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=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, "label_name": "safe"} -{"code": " $this->_auth_obj->setAuthData($key, $value);\n }\n return true;\n }\n\n $this->activeUser = $res[$this->options['usernamecol']];\n return false;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function db_properties($table) {\n global $DatabaseType, $DatabaseUsername;\n\n switch ($DatabaseType) {\n case 'mysqli':\n $result = DBQuery(\"SHOW COLUMNS FROM $table\");\n while ($row = db_fetch_row($result)) {\n $properties[strtoupper($row['FIELD'])]['TYPE'] = strtoupper($row['TYPE'], strpos($row['TYPE'], '('));\n if (!$pos = strpos($row['TYPE'], ','))\n $pos = strpos($row['TYPE'], ')');\n else\n $properties[strtoupper($row['FIELD'])]['SCALE'] = substr($row['TYPE'], $pos + 1);\n\n $properties[strtoupper($row['FIELD'])]['SIZE'] = substr($row['TYPE'], strpos($row['TYPE'], '(') + 1, $pos);\n\n if ($row['NULL'] != '')\n $properties[strtoupper($row['FIELD'])]['NULL'] = \"Y\";\n else\n $properties[strtoupper($row['FIELD'])]['NULL'] = \"N\";\n }\n break;\n }\n return $properties;\n}", "label": 1, "label_name": "safe"} -{"code": " $vars = self::$mysqli->escape_string($vars);\r\n }else{\r\n $vars = $vars;\r\n }\r\n return $vars;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function __construct($escapeChar = \"'\", array $startingChars = ['=', '-', '+', '@'])\n {\n $this->escapeChar = $escapeChar;\n $this->startingChars = $startingChars;\n }", "label": 1, "label_name": "safe"} -{"code": " $f = function (\\Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition $v = null) { return $v; }; return $f(${($_ = isset($this->services['Symfony\\\\Component\\\\DependencyInjection\\\\Tests\\\\Fixtures\\\\CustomDefinition']) ? $this->services['Symfony\\\\Component\\\\DependencyInjection\\\\Tests\\\\Fixtures\\\\CustomDefinition'] : ($this->services['Symfony\\\\Component\\\\DependencyInjection\\\\Tests\\\\Fixtures\\\\CustomDefinition'] = new \\Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition())) && false ?: '_'});", "label": 1, "label_name": "safe"} -{"code": " def check_valid_db(cls, config_calibre_dir, app_db_path, config_calibre_uuid):\n if not config_calibre_dir:\n return False, False\n dbpath = os.path.join(config_calibre_dir, \"metadata.db\")\n if not os.path.exists(dbpath):\n return False, False\n try:\n check_engine = create_engine('sqlite://',\n echo=False,\n isolation_level=\"SERIALIZABLE\",\n connect_args={'check_same_thread': False},\n poolclass=StaticPool)\n with check_engine.begin() as connection:\n connection.execute(text(\"attach database '{}' as calibre;\".format(dbpath)))\n connection.execute(text(\"attach database '{}' as app_settings;\".format(app_db_path)))\n local_session = scoped_session(sessionmaker())\n local_session.configure(bind=connection)\n database_uuid = local_session().query(LibraryId).one_or_none()\n # local_session.dispose()\n\n check_engine.connect()\n db_change = config_calibre_uuid != database_uuid.uuid\n except Exception:\n return False, False\n return True, db_change", "label": 1, "label_name": "safe"} -{"code": "dump_threads(void)\n{\n\tFILE *fp;\n\tchar time_buf[26];\n\telement e;\n\tvrrp_t *vrrp;\n\tchar *file_name;\n\n\tfile_name = make_file_name(\"/tmp/thread_dump.dat\",\n\t\t\t\t\t\"vrrp\",\n#if HAVE_DECL_CLONE_NEWNET\n\t\t\t\t\tglobal_data->network_namespace,\n#else\n\t\t\t\t\tNULL,\n#endif\n\t\t\t\t\tglobal_data->instance_name);\n\tfp = fopen_safe(file_name, \"a\");\n\tFREE(file_name);\n\n\tset_time_now();\n\tctime_r(&time_now.tv_sec, time_buf);\n\n\tfprintf(fp, \"\\n%.19s.%6.6ld: Thread dump\\n\", time_buf, time_now.tv_usec);\n\n\tdump_thread_data(master, fp);\n\n\tfprintf(fp, \"alloc = %lu\\n\", master->alloc);\n\n\tfprintf(fp, \"\\n\");\n\tLIST_FOREACH(vrrp_data->vrrp, vrrp, e) {\n\t\tctime_r(&vrrp->sands.tv_sec, time_buf);\n\t\tfprintf(fp, \"VRRP instance %s, sands %.19s.%6.6lu, status %s\\n\", vrrp->iname, time_buf, vrrp->sands.tv_usec,\n\t\t\t\tvrrp->state == VRRP_STATE_INIT ? \"INIT\" :\n\t\t\t\tvrrp->state == VRRP_STATE_BACK ? \"BACKUP\" :\n\t\t\t\tvrrp->state == VRRP_STATE_MAST ? \"MASTER\" :\n\t\t\t\tvrrp->state == VRRP_STATE_FAULT ? \"FAULT\" :\n\t\t\t\tvrrp->state == VRRP_STATE_STOP ? \"STOP\" :\n\t\t\t\tvrrp->state == VRRP_DISPATCHER ? \"DISPATCHER\" : \"unknown\");\n\t}\n\tfclose(fp);\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " def testBoostedTreesSparseCalculateBestFeatureSplitSecurity(self):\n node_id_range = []\n stats_summary_indices = [[]]\n stats_summary_values = [1.0]\n stats_summary_shape = [1, 1, 1, 1]\n l1 = [1.0]\n l2 = [1.0]\n tree_complexity = [0.5]\n min_node_weight = [1.0]\n logits_dimension = 3\n split_type = 'inequality'\n with self.assertRaises((errors.InvalidArgumentError, ValueError)):\n gen_boosted_trees_ops.boosted_trees_sparse_calculate_best_feature_split(\n node_id_range=node_id_range,\n stats_summary_indices=stats_summary_indices,\n stats_summary_values=stats_summary_values,\n stats_summary_shape=stats_summary_shape,\n l1=l1,\n l2=l2,\n tree_complexity=tree_complexity,\n min_node_weight=min_node_weight,\n logits_dimension=logits_dimension,\n split_type=split_type)", "label": 1, "label_name": "safe"} -{"code": "func NewReader(src io.Reader, size int64, md5Hex, sha256Hex string) (*Reader, error) {\n\tif _, ok := src.(*Reader); ok {\n\t\treturn nil, errNestedReader\n\t}\n\n\tsha256sum, err := hex.DecodeString(sha256Hex)\n\tif err != nil {\n\t\treturn nil, SHA256Mismatch{}\n\t}\n\n\tmd5sum, err := hex.DecodeString(md5Hex)\n\tif err != nil {\n\t\treturn nil, BadDigest{}\n\t}\n\n\tvar sha256Hash hash.Hash\n\tif len(sha256sum) != 0 {\n\t\tsha256Hash = sha256.New()\n\t}\n\n\treturn &Reader{\n\t\tmd5sum: md5sum,\n\t\tsha256sum: sha256sum,\n\t\tsrc: io.LimitReader(src, size),\n\t\tsize: size,\n\t\tmd5Hash: md5.New(),\n\t\tsha256Hash: sha256Hash,\n\t}, nil\n}", "label": 0, "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(\"cannot handle supplied parameter spec: \" + e.getMessage());\n }\n\n }", "label": 1, "label_name": "safe"} -{"code": " public function withHeader($header, $value)\n {\n /** @var Request $newInstance */\n $newInstance = $this->withParentHeader($header, $value);\n return $newInstance;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def test_magic_response_http_error():\n mw = _get_mw()\n req = SplashRequest('http://example.com/foo')\n req = mw.process_request(req, None)\n\n resp_data = {\n \"info\": {\n \"error\": \"http404\",\n \"message\": \"Lua error: [string \\\"function main(splash)\\r...\\\"]:3: http404\",\n \"line_number\": 3,\n \"type\": \"LUA_ERROR\",\n \"source\": \"[string \\\"function main(splash)\\r...\\\"]\"\n },\n \"description\": \"Error happened while executing Lua script\",\n \"error\": 400,\n \"type\": \"ScriptError\"\n }\n resp = TextResponse(\"http://mysplash.example.com/execute\", status=400,\n headers={b'Content-Type': b'application/json'},\n body=json.dumps(resp_data).encode('utf8'))\n resp = mw.process_response(req, resp, None)\n assert resp.data == resp_data\n assert resp.status == 404\n assert resp.splash_response_status == 400\n assert resp.url == \"http://example.com/foo\"", "label": 0, "label_name": "vulnerable"} -{"code": " public function save()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n $values['project_id'] = $project['id'];\n\n list($valid, $errors) = $this->taskValidator->validateCreation($values);\n\n if (! $valid) {\n $this->flash->failure(t('Unable to create your task.'));\n $this->show($values, $errors);\n } else if (! $this->helper->projectRole->canCreateTaskInColumn($project['id'], $values['column_id'])) {\n $this->flash->failure(t('You cannot create tasks in this column.'));\n $this->response->redirect($this->helper->url->to('BoardViewController', 'show', array('project_id' => $project['id'])), true);\n } else {\n $task_id = $this->taskCreationModel->create($values);\n\n if ($task_id > 0) {\n $this->flash->success(t('Task created successfully.'));\n $this->afterSave($project, $values, $task_id);\n } else {\n $this->flash->failure(t('Unable to create this task.'));\n $this->response->redirect($this->helper->url->to('BoardViewController', 'show', array('project_id' => $project['id'])), true);\n }\n }\n }", "label": 1, "label_name": "safe"} -{"code": "void AnnotateRWLockCreate(const char *file, int line,\n const volatile void *lock){}", "label": 0, "label_name": "vulnerable"} -{"code": " final void setObject(CharSequence name, Iterable values) {\n final AsciiString normalizedName = HttpHeaderNames.of(name);\n requireNonNull(values, \"values\");\n\n final int h = normalizedName.hashCode();\n final int i = index(h);\n\n remove0(h, i, normalizedName);\n for (Object v: values) {\n requireNonNullElement(values, v);\n add0(h, i, normalizedName, fromObject(v));\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public static function rewindStream($resource)\n {\n if (ftell($resource) !== 0 && static::isSeekableStream($resource)) {\n rewind($resource);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " foreach (array_keys($this->cookies[$domain]) as $path) {\n foreach ($this->cookies[$domain][$path] as $name => $cookie) {\n $cookies[] = $cookie;\n }\n }\n }", "label": 0, "label_name": "vulnerable"} -{"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++ RequestsCookieJar:\n jar = RequestsCookieJar()\n for name, cookie_dict in self['cookies'].items():\n jar.set_cookie(create_cookie(\n name, cookie_dict.pop('value'), **cookie_dict))\n jar.clear_expired_cookies()\n return jar", "label": 0, "label_name": "vulnerable"} -{"code": "ka-aa,ha=ua+(ya.y-ua)/ka-aa,da=new Image;da.onload=function(){try{for(var ca=-Math.round(sa-mxUtils.mod((wa-xa)*Y,sa)),la=-Math.round(sa-mxUtils.mod((ua-ha)*Y,sa));cadictionary[substr($key, strlen($field.'-'))][$field] = $purifier->purify($value);\r\n }\r\n\t\t\t}\r", "label": 1, "label_name": "safe"} -{"code": "def remote_add_node(params, request, auth_user, all=false)\n if not allowed_for_local_cluster(auth_user, Permissions::FULL)\n return 403, 'Permission denied'\n end\n auto_start = false\n if params[:auto_start] and params[:auto_start] == \"1\"\n auto_start = true\n end\n\n if params[:new_nodename] != nil\n node = params[:new_nodename]\n if params[:new_ring1addr] != nil\n node += ',' + params[:new_ring1addr]\n end\n retval, output = add_node(auth_user, node, all, auto_start)\n end\n\n if retval == 0\n return [200, JSON.generate([retval, get_corosync_conf()])]\n end\n\n return [400,output]\nend", "label": 1, "label_name": "safe"} -{"code": " public void validate() {\n final String filter = format(ldapConfiguration.getUserSearchFilter(), \"test\");\n ldapConnectionTemplate.searchFirst(ldapConfiguration.getSearchBases().get(0), filter, SearchScope.SUBTREE, entry -> entry);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $value = str_replace($originalName, $cleanedName, $value);\n }\n unset($value);\n }\n $result = hash_equals(GeneralUtility::hmac(serialize($fieldChangeFunctions), 'backend-link-browser'), $this->parameters['fieldChangeFuncHash']);\n }\n return $result;\n }", "label": 1, "label_name": "safe"} -{"code": " public function setUp()\n {\n parent::setUp();\n $this->config->set('HTML.TargetNoreferrer', false);\n $this->config->set('HTML.TargetNoopener', true);\n $this->config->set('Attr.AllowedFrameTargets', '_blank');\n }", "label": 1, "label_name": "safe"} -{"code": "int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj)\n{\n char obj_txt[128];\n\n int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);\n BIO_write(bio, obj_txt, len);\n BIO_write(bio, \"\\n\", 1);\n\n return 1;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " context.test.skip = function(title) {\n context.test(title);\n };", "label": 1, "label_name": "safe"} -{"code": " def virtualenv=(install)\n # Yes Symbols instead of Booleans because we get Symbols from Puppet when\n # we use the virtualenv property. This is madness!\n if install == :true and virtualenv == :false\n command = [\"#{PYENV_ROOT}/versions/#{resource[:name]}/bin/pip\",\n 'install', '-q', 'virtualenv', '>/dev/null 2>&1']\n `#{command.join(' ')}`\n if $?.success?\n @property_hash[:virtualenv] = :true\n else\n fail('failed to install virtualenv')\n end\n pyenv('rehash')\n elsif install == :false and virtualenv == :true\n command = [\"#{PYENV_ROOT}/versions/#{resource[:name]}/bin/pip\",\n 'uninstall', '-q', '-y', 'virtualenv', '>/dev/null 2>&1']\n `#{command.join(' ')}`\n if $?.success?\n @property_hash[:virtualenv] = :false\n else\n fail('failed to uninstall virtualenv')\n end\n pyenv('rehash')\n else\n # We can never hit this block as the newvalues on the virtualenv property\n # should prevent us from getting here in the first place. However, this\n # is Puppet so you never know.\n fail('go home puppet, you\\'re drunk')\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "mxText.prototype.updateValue=function(){if(mxUtils.isNode(this.value))this.node.innerHTML=\"\",this.node.appendChild(this.value);else{var a=this.value;this.dialect!=mxConstants.DIALECT_STRICTHTML&&(a=mxUtils.htmlEntities(a,!1));a=mxUtils.replaceTrailingNewlines(a,\"

\");a=this.replaceLinefeeds?a.replace(/\\n/g,\"
\"):a;var b=null!=this.background&&this.background!=mxConstants.NONE?this.background:null,c=null!=this.border&&this.border!=mxConstants.NONE?this.border:null;if(\"fill\"==this.overflow||\n\"width\"==this.overflow)null!=b&&(this.node.style.backgroundColor=b),null!=c&&(this.node.style.border=\"1px solid \"+c);else{var d=\"\";null!=b&&(d+=\"background-color:\"+mxUtils.htmlEntities(b)+\";\");null!=c&&(d+=\"border:1px solid \"+mxUtils.htmlEntities(c)+\";\");a='
'+a+\"
\"}this.node.innerHTML=\na;a=this.node.getElementsByTagName(\"div\");0checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol)\n{\n\tstruct snd_ctl_elem_id id;\n\tunsigned int idx;\n\tunsigned int count;\n\tint err = -EINVAL;\n\n\tif (! kcontrol)\n\t\treturn err;\n\tif (snd_BUG_ON(!card || !kcontrol->info))\n\t\tgoto error;\n\tid = kcontrol->id;\n\tdown_write(&card->controls_rwsem);\n\tif (snd_ctl_find_id(card, &id)) {\n\t\tup_write(&card->controls_rwsem);\n\t\tdev_err(card->dev, \"control %i:%i:%i:%s:%i is already present\\n\",\n\t\t\t\t\tid.iface,\n\t\t\t\t\tid.device,\n\t\t\t\t\tid.subdevice,\n\t\t\t\t\tid.name,\n\t\t\t\t\tid.index);\n\t\terr = -EBUSY;\n\t\tgoto error;\n\t}\n\tif (snd_ctl_find_hole(card, kcontrol->count) < 0) {\n\t\tup_write(&card->controls_rwsem);\n\t\terr = -ENOMEM;\n\t\tgoto error;\n\t}\n\tlist_add_tail(&kcontrol->list, &card->controls);\n\tcard->controls_count += kcontrol->count;\n\tkcontrol->id.numid = card->last_numid + 1;\n\tcard->last_numid += kcontrol->count;\n\tcount = kcontrol->count;\n\tup_write(&card->controls_rwsem);\n\tfor (idx = 0; idx < count; idx++, id.index++, id.numid++)\n\t\tsnd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);\n\treturn 0;\n\n error:\n\tsnd_ctl_free_one(kcontrol);\n\treturn err;\n}", "label": 1, "label_name": "safe"} -{"code": " def convert_autorequire(autorequire)\n autorequire = autorequire.first\n return autorequire if autorequire == \"false\"\n autorequire.inspect\n end", "label": 1, "label_name": "safe"} -{"code": " public function testPurchaseSuccess()\n {\n $httpResponse = $this->getMockHttpResponse('PurchaseSuccess.txt');\n $response = new Response($this->getMockRequest(), $httpResponse->json());\n\n $this->assertTrue($response->isSuccessful());\n $this->assertFalse($response->isRedirect());\n $this->assertSame('ch_1IU9gcUiNASROd', $response->getTransactionReference());\n $this->assertSame('card_16n3EU2baUhq7QENSrstkoN0', $response->getCardReference());\n $this->assertNull($response->getMessage());\n $this->assertInternalType('array', $response->getSource());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def create_patchinfo_from_request(req)\n check_write_access!\n\n patchinfo = Package.new(:name => \"patchinfo\", :title => \"Patchinfo\", :description => \"Collected packages for update\")\n self.packages << patchinfo\n patchinfo.add_flag(\"build\", \"enable\", nil, nil)\n patchinfo.add_flag(\"useforbuild\", \"disable\", nil, nil)\n patchinfo.add_flag(\"publish\", \"enable\", nil, nil) unless self.flags.find_by_flag_and_status(\"access\", \"disable\")\n patchinfo.store\n \n # create patchinfo XML file\n node = Nokogiri::XML::Builder.new\n attrs = { }\n if self.project_type.to_s == \"maintenance_incident\"\n # this is a maintenance incident project, the sub project name is the maintenance ID\n attrs[:incident] = self.name.gsub(/.*:/, '')\n end\n \n description = req.description || ''\n node.patchinfo(attrs) do |n|\n n.packager req.creator\n n.category \"recommended\" # update_patchinfo may switch to security\n n.rating \"low\"\n n.summary description.split(/\\n|\\r\\n/)[0] # first line only\n n.description req.description\n end\n data = ActiveXML::Node.new( node.doc.to_xml )\n data = self.update_patchinfo( data, enfore_issue_update: true )\n p = { :user => User.current.login, :comment => \"generated by request id #{req.id} accept call\" }\n patchinfo_path = \"/source/#{CGI.escape(patchinfo.project.name)}/patchinfo/_patchinfo\"\n patchinfo_path << Suse::Backend.build_query_from_hash(p, [:user, :comment])\n Suse::Backend.put( patchinfo_path, data.dump_xml )\n patchinfo.sources_changed\n end", "label": 1, "label_name": "safe"} -{"code": " private function defaultTextParse($bbcode)\n {\n $parser = new JBBCode\\Parser();\n $parser->addCodeDefinitionSet(new JBBCode\\DefaultCodeDefinitionSet());\n $parser->parse($bbcode);\n return $parser->getAsText();\n }", "label": 1, "label_name": "safe"} -{"code": " it \"should raise an error if the image fails to be processed when downloaded\" do\n stub_request(:get, \"www.example.com/test.jpg\").to_return(body: File.read(file_path(\"test.jpg\")))\n\n expect(running {\n @instance.remote_image_url = \"http://www.example.com/test.jpg\"\n }).to raise_error(CarrierWave::ProcessingError)\n end", "label": 0, "label_name": "vulnerable"} -{"code": "function minErr(module, ErrorConstructor) {\n ErrorConstructor = ErrorConstructor || Error;\n return function() {\n var SKIP_INDEXES = 2;\n\n var templateArgs = arguments,\n code = templateArgs[0],\n message = '[' + (module ? module + ':' : '') + code + '] ',\n template = templateArgs[1],\n paramPrefix, i;\n\n message += template.replace(/\\{\\d+\\}/g, function(match) {\n var index = +match.slice(1, -1),\n shiftedIndex = index + SKIP_INDEXES;\n\n if (shiftedIndex < templateArgs.length) {\n return toDebugString(templateArgs[shiftedIndex]);\n }\n\n return match;\n });\n\n message += '\\nhttp://errors.angularjs.org/\"NG_VERSION_FULL\"/' +\n (module ? module + '/' : '') + code;\n\n for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {\n message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +\n encodeURIComponent(toDebugString(templateArgs[i]));\n }\n\n return new ErrorConstructor(message);\n };\n}", "label": 0, "label_name": "vulnerable"} -{"code": " static function testLDAPConnection($auths_id, $replicate_id = -1) {\n\n $config_ldap = new self();\n $res = $config_ldap->getFromDB($auths_id);\n\n // we prevent some delay...\n if (!$res) {\n return false;\n }\n\n //Test connection to a replicate\n if ($replicate_id != -1) {\n $replicate = new AuthLdapReplicate();\n $replicate->getFromDB($replicate_id);\n $host = $replicate->fields[\"host\"];\n $port = $replicate->fields[\"port\"];\n\n } else {\n //Test connection to a master ldap server\n $host = $config_ldap->fields['host'];\n $port = $config_ldap->fields['port'];\n }\n $ds = self::connectToServer($host, $port, $config_ldap->fields['rootdn'],\n Toolbox::decrypt($config_ldap->fields['rootdn_passwd'], GLPIKEY),\n $config_ldap->fields['use_tls'],\n $config_ldap->fields['deref_option']);\n if ($ds) {\n return true;\n }\n return false;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static void main(\n String[] args)\n {\n Security.addProvider(new BouncyCastleProvider());\n\n runTest(new DHTest());\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h)\n{\n PadContext *s = inlink->dst->priv;\n\n AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0],\n w + (s->w - s->in_w),\n h + (s->h - s->in_h));\n int plane;\n\n if (!frame)\n return NULL;\n\n frame->width = w;\n frame->height = h;\n\n for (plane = 0; plane < 4 && frame->data[plane]; plane++) {\n int hsub = s->draw.hsub[plane];\n int vsub = s->draw.vsub[plane];\n frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] +\n (s->y >> vsub) * frame->linesize[plane];\n }\n\n return frame;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tappendMessage = func(targetOffset uint32) bool {\n\t\tfor _, f := range frags {\n\t\t\tif f.handshakeHeader.FragmentOffset == targetOffset {\n\t\t\t\tfragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength)\n\t\t\t\tif fragmentEnd != f.handshakeHeader.Length {\n\t\t\t\t\tif !appendMessage(fragmentEnd) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\trawMessage = append(f.data, rawMessage...)\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "\tconstructor(options) {\n\t\tsuper(options);\n\n\t\tthis.name = \"continuous\";\n\n\t\tthis.settings = extend(this.settings || {}, {\n\t\t\tinfinite: true,\n\t\t\toverflow: undefined,\n\t\t\taxis: undefined,\n\t\t\twritingMode: undefined,\n\t\t\tflow: \"scrolled\",\n\t\t\toffset: 500,\n\t\t\toffsetDelta: 250,\n\t\t\twidth: undefined,\n\t\t\theight: undefined,\n\t\t\tsnap: false,\n\t\t\tafterScrolledTimeout: 10,\n\t\t\tallowScriptedContent: false\n\t\t});\n\n\t\textend(this.settings, options.settings || {});\n\n\t\t// Gap can be 0, but defaults doesn't handle that\n\t\tif (options.settings.gap != \"undefined\" && options.settings.gap === 0) {\n\t\t\tthis.settings.gap = options.settings.gap;\n\t\t}\n\n\t\tthis.viewSettings = {\n\t\t\tignoreClass: this.settings.ignoreClass,\n\t\t\taxis: this.settings.axis,\n\t\t\tflow: this.settings.flow,\n\t\t\tlayout: this.layout,\n\t\t\twidth: 0,\n\t\t\theight: 0,\n\t\t\tforceEvenPages: false,\n\t\t\tallowScriptedContent: this.settings.allowScriptedContent\n\t\t};\n\n\t\tthis.scrollTop = 0;\n\t\tthis.scrollLeft = 0;\n\t}", "label": 1, "label_name": "safe"} -{"code": " public function testMissingValue()\n {\n $this->assertResult(array(\n 'type' => 'checkbox',\n ), array(\n 'type' => 'checkbox',\n 'value' => '',\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "struct crypto_template *crypto_lookup_template(const char *name)\n{\n\treturn try_then_request_module(__crypto_lookup_template(name), \"%s\",\n\t\t\t\t name);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " private String getPath(String test, int sequence, boolean poison) {\n String path = contextPath + \"/servlet?action=\" + test + \"&sequence=\" + sequence;\n if (poison) {\n path += \"&poison=true\";\n }\n return path;\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function set_controller($controller, $action)\n\t{\n\t\tinclude CLASS_DIR . 'module.php';\n\n\t\t$module = new Module($controller);\n\n\t\tdefine ('MODULE_NAME', $module->get_name());\n\n\t\t$class_file = APP_DIR . 'controller/' . MODULE_NAME . '.php';\n\t\t$class_name = ucfirst(MODULE_NAME) . '_Controller';\n\t\t$class_method = ucfirst($action) . '_Action';\n\n\t\t// tworzy obiekt kontrolera:\n\n\t\tif (file_exists($class_file))\n\t\t{\n\t\t\tinclude $class_file;\n\n\t\t\tif (class_exists($class_name))\n\t\t\t{\n\t\t\t\t$this->controller_object = new $class_name($this);\n\n\t\t\t\t$this->set_acl($this);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdie ('Class:

'.$class_name.'

not found.');\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdie ('File:

'.$class_file.'

not found.');\n\t\t}\n\n\t\t// tworzy obiekt modelu:\n\n\t\t$this->set_model_object(MODULE_NAME);\n\n\t\t// tworzy obiekt widoku:\n\n\t\t$this->set_view_object(MODULE_NAME);\n\n\t\t// wywo\u0142uje akcj\u0119 (metod\u0119) kontrolera:\n\n\t\tif (method_exists($class_name, $class_method))\n\t\t{\n\t\t\t$this->controller_object->{$class_method}();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdie ('Method:

'.$class_method.'

in class:

'.$class_name.'

not found.');\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "def fence_device_form(params, request, auth_user)\n if not allowed_for_local_cluster(auth_user, Permissions::READ)\n return 403, 'Permission denied'\n end\n\n @cur_resource = get_resource_by_id(params[:resource], get_cib_dom(auth_user))\n\n if @cur_resource.instance_of?(ClusterEntity::Primitive) and @cur_resource.stonith\n @resource_agents = getFenceAgents(auth_user, @cur_resource.agentname)\n @existing_resource = true\n @fenceagent = @resource_agents[@cur_resource.type]\n erb :fenceagentform\n else\n \"Can't find fence device\"\n end\nend", "label": 1, "label_name": "safe"} -{"code": " public static function returnChildrenAsJSON() {\r\n global $db;\r\n\r\n //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));\r\n $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;\r\n $nav = $db->selectObjects('section', 'parent=' . $id, 'rank');\r\n //FIXME $manage_all is moot w/ cascading perms now?\r\n $manage_all = false;\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {\r\n $manage_all = true;\r\n }\r\n //FIXME recode to use foreach $key=>$value\r\n $navcount = count($nav);\r\n for ($i = 0; $i < $navcount; $i++) {\r\n if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {\r\n $nav[$i]->manage = 1;\r\n $view = true;\r\n } else {\r\n $nav[$i]->manage = 0;\r\n $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));\r\n }\r\n $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);\r\n if (!$view) unset($nav[$i]);\r\n }\r\n $nav= array_values($nav);\r\n// $nav[$navcount - 1]->last = true;\r\n if (count($nav)) $nav[count($nav) - 1]->last = true;\r\n// echo expJavascript::ajaxReply(201, '', $nav);\r\n $ar = new expAjaxReply(201, '', $nav);\r\n $ar->send();\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "MagickExport int LocaleUppercase(const int c)\n{\n#if defined(MAGICKCORE_LOCALE_SUPPORT)\n if (c_locale != (locale_t) NULL)\n return(toupper_l((int) ((unsigned char) c),c_locale));\n#endif\n return(toupper((int) ((unsigned char) c)));\n}", "label": 1, "label_name": "safe"} -{"code": "\t\t\tforeach($CurrentError as $CurrentErrorVar => $CurrentErrorVal)\n\t\t\t{\n\t\t\t\tif($CurrentErrorVar == 'L_ERRORCODE')\n\t\t\t\t{\n\t\t\t\t\t$CurrentVarName = 'Error Code';\n\t\t\t\t}\n\t\t\t\telseif($CurrentErrorVar == 'L_SHORTMESSAGE')\n\t\t\t\t{\n\t\t\t\t\t$CurrentVarName = 'Short Message';\n\t\t\t\t}\n\t\t\t\telseif($CurrentErrorVar == 'L_LONGMESSAGE')\n\t\t\t\t{\n\t\t\t\t\t$CurrentVarName = 'Long Message';\n\t\t\t\t}\n\t\t\t\telseif($CurrentErrorVar == 'L_SEVERITYCODE')\n\t\t\t\t{\n\t\t\t\t\t$CurrentVarName = 'Severity Code';\n\t\t\t\t}\n\t\t\t\n\t\t\t\techo $CurrentVarName . ': ' . $CurrentErrorVal . '
';\t\t\n\t\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": "def test_external_interface_int_clampers(get_contract, assert_tx_failed, typ):\n external_contract = f\"\"\"\n@external\ndef ok() -> {typ}:\n return 1\n\n@external\ndef should_fail() -> int256:\n return -2**255 # OOB for all int/uint types with less than 256 bits\n \"\"\"\n\n code = f\"\"\"\ninterface BadContract:\n def ok() -> {typ}: view\n def should_fail() -> {typ}: view\n\nfoo: BadContract\n\n@external\ndef __init__(addr: BadContract):\n self.foo = addr\n\n\n@external\ndef test_ok() -> {typ}:\n return self.foo.ok()\n\n@external\ndef test_fail() -> {typ}:\n return self.foo.should_fail()\n\n@external\ndef test_fail2() -> {typ}:\n x: {typ} = self.foo.should_fail()\n return x\n\n@external\ndef test_fail3() -> int256:\n return convert(self.foo.should_fail(), int256)\n \"\"\"\n\n bad_c = get_contract(external_contract)\n c = get_contract(\n code,\n bad_c.address,\n interface_codes={\"BadCode\": {\"type\": \"vyper\", \"code\": external_contract}},\n )\n assert bad_c.ok() == 1\n assert bad_c.should_fail() == -(2 ** 255)\n\n assert c.test_ok() == 1\n assert_tx_failed(lambda: c.test_fail())\n assert_tx_failed(lambda: c.test_fail2())\n assert_tx_failed(lambda: c.test_fail3())", "label": 1, "label_name": "safe"} -{"code": " static function isSearchable() {\n return true;\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public function testInvalidOptionUrlBBCode()\n {\n $parser = new JBBCode\\Parser();\n $parser->addCodeDefinitionSet(new JBBCode\\DefaultCodeDefinitionSet());\n $parser->parse('[url=javascript:alert(\"HACKED!\");]click me[/url]');\n $this->assertEquals('[url=javascript:alert(\"HACKED!\");]click me[/url]',\n $parser->getAsHtml());\n }", "label": 1, "label_name": "safe"} -{"code": "this.toolbar.staticElements.push(c);c.style.right=\"atlas\"==uiTheme||\"1\"==urlParams.atlas?\"42px\":\"52px\"}};EditorUi.prototype.showImportCsvDialog=function(){null==this.importCsvDialog&&(this.importCsvDialog=new TextareaDialog(this,mxResources.get(\"csv\")+\":\",Editor.defaultCsvValue,mxUtils.bind(this,function(c){this.importCsv(c)}),null,null,620,430,null,!0,!0,mxResources.get(\"import\"),this.isOffline()?null:\"https://drawio-app.com/import-from-csv-to-drawio/\"));this.showDialog(this.importCsvDialog.container,\n640,520,!0,!0,null,null,null,null,!0);this.importCsvDialog.init()};EditorUi.prototype.executeLayoutList=function(c,e){for(var g=this.editor.graph,k=g.getSelectionCells(),m=0;mlist);\n}", "label": 1, "label_name": "safe"} -{"code": " public function validate($string, $config, $context) {\n\n $string = $this->parseCDATA($string);\n\n if ($string === '') return false;\n $length = strlen($string);\n if ($length === 1) return false;\n if ($string[$length - 1] !== '%') return false;\n\n $number = substr($string, 0, $length - 1);\n $number = $this->number_def->validate($number, $config, $context);\n\n if ($number === false) return false;\n return \"$number%\";\n\n }", "label": 1, "label_name": "safe"} -{"code": " function scan_page($parent_id) {\r\n global $db;\r\n\r\n $sections = $db->selectObjects('section','parent=' . $parent_id);\r\n $ret = '';\r\n foreach ($sections as $page) {\r\n $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r\n return $ret;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "func (mr *MockRequesterMockRecorder) Sanitize(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sanitize\", reflect.TypeOf((*MockRequester)(nil).Sanitize), arg0)\n}", "label": 1, "label_name": "safe"} -{"code": "void pef7071DumpPhyReg(NetInterface *interface)\n{\n uint8_t i;\n\n //Loop through PHY registers\n for(i = 0; i < 32; i++)\n {\n //Display current PHY register\n TRACE_DEBUG(\"%02\" PRIu8 \": 0x%04\" PRIX16 \"\\r\\n\", i,\n pef7071ReadPhyReg(interface, i));\n }\n\n //Terminate with a line feed\n TRACE_DEBUG(\"\\r\\n\");\n}", "label": 1, "label_name": "safe"} -{"code": " private function createException($foo)\n {\n return new \\Exception();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def uniq(inpt):\n output = []\n inpt = [ \" \".join(inp.split()) for inp in inpt]\n for x in inpt:\n if x not in output:\n output.append(x)\n return output", "label": 0, "label_name": "vulnerable"} -{"code": "spnego_gss_pseudo_random(OM_uint32 *minor_status,\n\t\t\t gss_ctx_id_t context,\n\t\t\t int prf_key,\n\t\t\t const gss_buffer_t prf_in,\n\t\t\t ssize_t desired_output_len,\n\t\t\t gss_buffer_t prf_out)\n{\n\tOM_uint32 ret;\n\tspnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context;\n\n\tif (sc->ctx_handle == GSS_C_NO_CONTEXT)\n\t\treturn (GSS_S_NO_CONTEXT);\n\n\tret = gss_pseudo_random(minor_status,\n\t\t\t\tsc->ctx_handle,\n\t\t\t\tprf_key,\n\t\t\t\tprf_in,\n\t\t\t\tdesired_output_len,\n\t\t\t\tprf_out);\n return (ret);\n}", "label": 1, "label_name": "safe"} -{"code": "\tpublic void highlightInMuc(Conversation conversation, String nick) {\n\t\tswitchToConversation(conversation, null, false, nick, false);\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def generate(time, counter = 0)\n [time, @machine_id, Process.pid, counter << 8].pack(\"N NX lXX NX\")\n end", "label": 1, "label_name": "safe"} -{"code": "function(){return mxClient.IS_CHROMEAPP||this.useCanvasForExport};Editor.prototype.getMaxCanvasScale=function(p,C,I){var T=mxClient.IS_FF?8192:16384;return Math.min(I,Math.min(T/p,T/C))};Editor.prototype.exportToCanvas=function(p,C,I,T,P,O,R,Y,da,ha,Z,ea,aa,va,la,Aa,Ba,ua){try{O=null!=O?O:!0;R=null!=R?R:!0;ea=null!=ea?ea:this.graph;aa=null!=aa?aa:0;var Da=da?null:ea.background;Da==mxConstants.NONE&&(Da=null);null==Da&&(Da=T);null==Da&&0==da&&(Da=Aa?this.graph.defaultPageBackgroundColor:\"#ffffff\");", "label": 1, "label_name": "safe"} -{"code": " def request(args = {})\n { :ip => '10.1.1.1', :node => 'host.domain.com', :key => 'key', :authenticated => true }.each do |k,v|\n args[k] ||= v\n end\n ['test', :find, args[:key], args]\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def auth\n @auth ||= {}\n end", "label": 1, "label_name": "safe"} -{"code": "function main() {\n tests(10);\n tests(1026);\n}", "label": 1, "label_name": "safe"} -{"code": "function XMLRPCaddResourceGroupPriv($name, $type, $nodeid, $permissions){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n\n if(! checkUserHasPriv(\"resourceGrant\", $user['id'], $nodeid)){\n return array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to add resource group to this node');\n }\n\n if($typeid = getResourceTypeID($type)){\n if(!checkForGroupName($name, 'resource', '', $typeid)){\n return array('status' => 'error',\n 'errorcode' => 28,\n 'errormsg' => 'resource group does not exist');\n }\n $perms = explode(':', $permissions);\n updateResourcePrivs(\"$type/$name\", $nodeid, $perms, array());\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'Invalid resource type');\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "func padBuffer(buffer []byte, blockSize int) []byte {\n\tmissing := blockSize - (len(buffer) % blockSize)\n\tret, out := resize(buffer, len(buffer)+missing)\n\tpadding := bytes.Repeat([]byte{byte(missing)}, missing)\n\tcopy(out, padding)\n\treturn ret\n}", "label": 0, "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 || 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, "label_name": "safe"} -{"code": "def _parse_authentication_info(headers, headername=\"authentication-info\"):\n \"\"\"https://tools.ietf.org/html/rfc7615\n \"\"\"\n header = headers.get(headername, \"\").strip()\n if not header:\n return {}\n try:\n parsed = authentication_info.parseString(header)\n except pp.ParseException as ex:\n # print(ex.explain(ex))\n raise MalformedHeader(headername)\n\n return parsed.asDict()", "label": 1, "label_name": "safe"} -{"code": "\tprotected void switchToConversation(Contact contact, String body) {\n\t\tConversation conversation = xmppConnectionService\n\t\t\t\t.findOrCreateConversation(contact.getAccount(),\n\t\t\t\t\t\tcontact.getJid(), false, true);\n\t\tswitchToConversation(conversation, body);\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "null==ha&&null!=l&&(ha=new mxPoint(l.getCenterX(),l.getCenterY()));null==B&&null!=x&&(B=new mxPoint(x.getCenterX(),x.getCenterY()));var K=rb.x,xa=rb.y,na=zb.x,$a=zb.y,ib=\"horizontal\"==mxUtils.getValue(c.style,\"elbow\",\"horizontal\");if(null!=B&&null!=ha){c=function(Ga,Ja,Ia){Ga-=db.x;var Ha=Ja-db.y;Ja=($a*Ga-na*Ha)/(K*$a-xa*na);Ga=(xa*Ga-K*Ha)/(xa*na-K*$a);ib?(Ia&&(db=new mxPoint(db.x+K*Ja,db.y+xa*Ja),v.push(db)),db=new mxPoint(db.x+na*Ga,db.y+$a*Ga)):(Ia&&(db=new mxPoint(db.x+na*Ga,db.y+$a*Ga),v.push(db)),\ndb=new mxPoint(db.x+K*Ja,db.y+xa*Ja));v.push(db)};var db=ha;null==p&&(p=new mxPoint(ha.x+(B.x-ha.x)/2,ha.y+(B.y-ha.y)/2));c(p.x,p.y,!0);c(B.x,B.y,!1)}};mxStyleRegistry.putValue(\"isometricEdgeStyle\",mxEdgeStyle.IsometricConnector);var nb=Graph.prototype.createEdgeHandler;Graph.prototype.createEdgeHandler=function(c,l){if(l==mxEdgeStyle.IsometricConnector){var x=new mxElbowEdgeHandler(c);x.snapToTerminals=!1;return x}return nb.apply(this,arguments)};t.prototype.constraints=[];F.prototype.getConstraints=", "label": 0, "label_name": "vulnerable"} -{"code": " protected function assertNoErrors () {\n\t\t$this->assertElementNotPresent('css=.xdebug-error');\n\t\t$this->assertElementNotPresent('css=#x2-php-error');\n $this->storeEval (\n \"window.document.body.attributes['x2-js-error'] ? 'true' : 'false'\", \n 'hasJsErrorAttr');\n $hasJsErrorAttr = $this->getExpression ('${hasJsErrorAttr}');\n if ($hasJsErrorAttr === 'true') {\n $this->storeAttribute ('dom=document.body@x2-js-error', 'errorMessage');\n $errorMessage = $this->getExpression ('${errorMessage}');\n println ($errorMessage);\n $this->assertTrue (false, $errorMessage);\n } \n }", "label": 1, "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,E=arguments,J=function(){U=null;X=Date.now();M.apply(u,E)};Date.now()-X>W?J():U=setTimeout(J,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||", "label": 0, "label_name": "vulnerable"} -{"code": " public function testCanSetHeaderAsArray()\n {\n $r = new Response(200, [\n 'foo' => ['baz ', ' bar ']\n ]);\n $this->assertEquals('baz, bar', $r->getHeaderLine('foo'));\n $this->assertEquals(['baz', 'bar'], $r->getHeader('foo'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function newpassword() {\n\n if ($token = $this->param('token')) {\n\n if (!\\is_string($token)) {\n return false;\n }\n\n $user = $this->app->storage->findOne('cockpit/accounts', ['_reset_token' => $token]);\n\n if (!$user) {\n return false;\n }\n\n $user = [\n 'md5email' => md5($user['email']),\n 'user' => $user['name'],\n 'name' => $user['user'],\n ];\n\n return $this->render('cockpit:views/layouts/newpassword.php', compact('user', 'token'));\n }\n\n return false;\n\n }", "label": 1, "label_name": "safe"} -{"code": "static LUA_FUNCTION(openssl_x509_check_ip)\n{\n X509 * cert = CHECK_OBJECT(1, X509, \"openssl.x509\");\n size_t sz;\n const char *ip = luaL_checklstring(L, 2, &sz);\n int flags = luaL_optint(L, 3, 0);\n int ret = X509_check_ip(cert, (const unsigned char*)ip, sz, flags);\n return openssl_push_check_result(L, ret, NULL);\n}", "label": 1, "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, "label_name": "safe"} -{"code": " $loc = expCore::makeLocation('navigation', '', $standalone->id);\n if (expPermissions::check('manage', $loc)) return true;\n }\n return false;\n }", "label": 1, "label_name": "safe"} -{"code": " def down\n raise ActiveRecord::IrreversibleMigration\n end", "label": 1, "label_name": "safe"} -{"code": "\t\t\tforeach ( $titles as $title ) {\n\t\t\t\tif ( $this->parameters->getParameter( 'openreferences' ) ) {\n\t\t\t\t\tif ( $this->parameters->getParameter( 'ignorecase' ) ) {\n\t\t\t\t\t\t$_or = \"LOWER(CAST(pl_title AS char)) {$comparisonType}\" . strtolower( $this->DB->addQuotes( $title ) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$_or = \"pl_title {$comparisonType} \" . $this->DB->addQuotes( $title );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif ( $this->parameters->getParameter( 'ignorecase' ) ) {\n\t\t\t\t\t\t$_or = \"LOWER(CAST({$this->tableNames['page']}.page_title AS char)) {$comparisonType}\" . strtolower( $this->DB->addQuotes( $title ) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$_or = \"{$this->tableNames['page']}.page_title {$comparisonType}\" . $this->DB->addQuotes( $title );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t$ors[] = $_or;\n\t\t\t}", "label": 1, "label_name": "safe"} -{"code": "def get_node_status(session, cib_dom)\n node_status = {\n :cluster_name => $cluster_name,\n :groups => [],\n :constraints => {\n # :rsc_location => [],\n # :rcs_colocation => [],\n # :rcs_order => []\n },\n :cluster_settings => {},\n :need_ring1_address => need_ring1_address?,\n :is_cman_with_udpu_transport => is_cman_with_udpu_transport?,\n :acls => get_acls(session, cib_dom),\n :username => session[:username],\n :fence_levels => get_fence_levels(session, cib_dom),\n :node_attr => node_attrs_to_v2(get_node_attributes(session, cib_dom)),\n :nodes_utilization => get_nodes_utilization(cib_dom),\n :known_nodes => []\n }\n\n nodes = get_nodes_status()\n\n known_nodes = []\n nodes.each { |_, node_list|\n known_nodes.concat node_list\n }\n node_status[:known_nodes] = known_nodes.uniq\n\n nodes.each do |k,v|\n node_status[k.to_sym] = v\n end\n\n if cib_dom\n node_status[:groups] = get_resource_groups(cib_dom)\n node_status[:constraints] = getAllConstraints(cib_dom.elements['/cib/configuration/constraints'])\n end\n\n node_status[:cluster_settings] = getAllSettings(session, cib_dom)\n\n return node_status\nend", "label": 0, "label_name": "vulnerable"} -{"code": " public void testInvalidGroupId(final String groupId, final boolean mustFail) {\n adminPage();\n findElementByLink(\"Configure Users, Groups and On-Call Roles\").click();\n findElementByLink(\"Configure Groups\").click();\n findElementByLink(\"Add new group\").click();\n\n enterText(By.id(\"groupName\"), groupId);\n enterText(By.id(\"groupComment\"), \"SmokeTestComment\");\n findElementByXpath(\"//button[@type='submit' and text()='OK']\").click();\n\n if (mustFail) {\n try {\n final Alert alert = wait.withTimeout(Duration.of(5, ChronoUnit.SECONDS)).until(ExpectedConditions.alertIsPresent());\n alert.dismiss();\n } catch (final Exception e) {\n LOG.debug(\"Got an exception waiting for a 'invalid group ID' alert.\", e);\n throw e;\n }\n } else {\n wait.until(ExpectedConditions.elementToBeClickable(By.name(\"finish\")));\n }\n }", "label": 1, "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\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, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " bool load_face(Face & face, unsigned int options)\n {\n#ifdef GRAPHITE2_TELEMETRY\n telemetry::category _misc_cat(face.tele.misc);\n#endif\n Face::Table silf(face, Tag::Silf, 0x00050000);\n if (!silf)\n return false;\n\n if (!face.readGlyphs(options))\n return false;\n\n if (silf)\n {\n if (!face.readFeatures() || !face.readGraphite(silf))\n {\n#if !defined GRAPHITE2_NTRACING\n if (global_log)\n {\n *global_log << json::object\n << \"type\" << \"fontload\"\n << \"failure\" << face.error()\n << \"context\" << face.error_context()\n << json::close;\n }\n#endif\n return false;\n }\n else\n return true;\n }\n else\n return false;\n }", "label": 1, "label_name": "safe"} -{"code": " public static function getModelTypes($assoc = false) {\n $modelTypes = Yii::app()->db->createCommand()\n ->selectDistinct('modelName')\n ->from('x2_fields')\n ->where('modelName!=\"Calendar\"')\n ->order('modelName ASC')\n ->queryColumn();\n\n if ($assoc === true) {\n $modelTypes = array_combine($modelTypes, array_map(function($type) {\n return X2Model::model ($type)->getDisplayName (true, false);\n }, $modelTypes));\n asort ($modelTypes);\n return $modelTypes;\n }\n $modelTypes = array_map(function($term) {\n return Yii::t('app', $term);\n }, $modelTypes);\n return $modelTypes;\n }", "label": 1, "label_name": "safe"} -{"code": " $directive->aliases[] = $this->id($alias);\n }\n }\n\n if (isset($hash['VERSION'])) {\n $directive->version = $hash->offsetGet('VERSION');\n }\n\n if (isset($hash['DEPRECATED-USE'])) {\n $directive->deprecatedUse = $this->id($hash->offsetGet('DEPRECATED-USE'));\n }\n\n if (isset($hash['DEPRECATED-VERSION'])) {\n $directive->deprecatedVersion = $hash->offsetGet('DEPRECATED-VERSION');\n }\n\n if (isset($hash['EXTERNAL'])) {\n $directive->external = preg_split('/\\s*,\\s*/', trim($hash->offsetGet('EXTERNAL')));\n }\n\n $interchange->addDirective($directive);\n }", "label": 1, "label_name": "safe"} -{"code": "static void postParse(HttpRoute *route)\n{\n Http *http;\n HttpHost *host;\n HttpRoute *rp;\n MprJson *mappings, *client;\n int nextHost, nextRoute;\n\n if (route->error) {\n return;\n }\n http = route->http;\n route->mode = mprGetJson(route->config, \"app.mode\");\n\n /*\n Create a subset, optimized configuration to send to the client\n */\n if ((mappings = mprGetJsonObj(route->config, \"app.client.mappings\")) != 0) {\n client = mprCreateJson(MPR_JSON_OBJ);\n clientCopy(route, client, mappings);\n mprSetJson(client, \"prefix\", route->prefix);\n route->client = mprJsonToString(client, MPR_JSON_QUOTES);\n }\n httpAddHostToEndpoints(route->host);\n\n /*\n Ensure the host home directory is set and the file handler is defined\n Propagate the HttpRoute.client to all child routes.\n */\n for (nextHost = 0; (host = mprGetNextItem(http->hosts, &nextHost)) != 0; ) {\n for (nextRoute = 0; (rp = mprGetNextItem(host->routes, &nextRoute)) != 0; ) {\n if (!mprLookupKey(rp->extensions, \"\")) {\n if (!rp->handler) {\n httpAddRouteHandler(rp, \"fileHandler\", \"\");\n httpAddRouteIndex(rp, \"index.html\");\n }\n }\n if (rp->parent == route) {\n rp->client = route->client;\n }\n }\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "mxCellRenderer.prototype.destroy=function(u){D.apply(this,arguments);null!=u.secondLabel&&(u.secondLabel.destroy(),u.secondLabel=null)};mxCellRenderer.prototype.getShapesForState=function(u){return[u.shape,u.text,u.secondLabel,u.control]};var G=mxGraphView.prototype.resetValidationState;mxGraphView.prototype.resetValidationState=function(){G.apply(this,arguments);this.enumerationState=0};var P=mxGraphView.prototype.stateValidated;mxGraphView.prototype.stateValidated=function(u){null!=u.shape&&this.redrawEnumerationState(u);", "label": 0, "label_name": "vulnerable"} -{"code": " def set_workflow\n Log.add_info(request, params.inspect)\n\n @item = Item.find(params[:id])\n\n orders_hash = params.dup\n orders_hash.reject! { |key, value|\n key.index(/order-/) != 0\n }\n orders_hash.sort_by { |key, value|\n key.split('-').last.to_i\n }\n\n orders = []\n orders_hash.each do |key, value|\n\n orders << '|' + value.split(',').join('|') + '|'\n end\n @item.workflow.update_attribute(:users, orders.join(','))\n\n render(:partial => 'ajax_item_workflow', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n\n render(:partial => 'ajax_item_workflow', :layout => false)\n end", "label": 0, "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 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, "label_name": "safe"} -{"code": " public SAXReader(String xmlReaderClassName) throws SAXException {\n if (xmlReaderClassName != null) {\n this.xmlReader = XMLReaderFactory\n .createXMLReader(xmlReaderClassName);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function preFilter($html, $config, $context)\n {\n return $html;\n }", "label": 1, "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' + content + '
';\n\t\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " public function testResponsesQueue()\n {\n $mock = new HTTP_Request2_Adapter_Mock();\n $mock->addResponse(\n \"HTTP/1.1 301 Over there\\r\\n\" .\n \"Location: http://www.example.com/newpage.html\\r\\n\" .\n \"\\r\\n\" .\n \"The document is over there\"\n );\n $mock->addResponse(\n \"HTTP/1.1 200 OK\\r\\n\" .\n \"Content-Type: text/plain; charset=iso-8859-1\\r\\n\" .\n \"\\r\\n\" .\n \"This is a string\"\n );\n\n $req = new HTTP_Request2('http://www.example.com/');\n $req->setAdapter($mock);\n $this->assertEquals(301, $req->send()->getStatus());\n $this->assertEquals(200, $req->send()->getStatus());\n $this->assertEquals(400, $req->send()->getStatus());\n }", "label": 0, "label_name": "vulnerable"} -{"code": "d.setSize(\"height\",b.height-310):d&&d.setSize(\"height\",b.height-220))});CKEDITOR.on(\"dialogDefinition\",function(b){var c=b.data.definition;a.onLoadOverlay=new q({opacity:\"1\",background:\"#fff\",target:c.dialog.parts.tabs.getParent().$});a.onLoadOverlay.setEnable();c.dialog.on(\"show\",function(){});c.dialog.on(\"cancel\",function(){c.dialog.getParentEditor().config.wsc_onClose.call(this.document.getWindow().getFrame());a.div_overlay.setDisable();return!1},this,null,-1)})})();", "label": 1, "label_name": "safe"} -{"code": " it 'should fail parsing when auth_method is not valid' do\n expect {subject}.to raise_error(Puppet::Error,\n /The auth_method you specified \\[invalid\\] must be one of/)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function testPostParameters()\n {\n $data = array(\n 'bar' => array(\n 'key' => 'some other value'\n ),\n 'baz' => array(\n 'key1' => array(\n 'key2' => 'yet another value'\n )\n ),\n 'foo' => 'some value',\n 'indexed' => array('first', 'second')\n );\n $events = array(\n 'sentHeaders', 'sentBodyPart', 'sentBody', 'receivedHeaders', 'receivedBodyPart', 'receivedBody'\n );\n $observer = new EventSequenceObserver($events);\n\n $this->request->setMethod(HTTP_Request2::METHOD_POST)\n ->setHeader('Accept-Encoding', 'identity')\n ->addPostParameter($data)\n ->attach($observer);\n\n $response = $this->request->send();\n $this->assertEquals(serialize($data), $response->getBody());\n $this->assertEquals($events, $observer->sequence);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " user: expect.objectContaining({ email: firstEmail }),\n })\n )\n\n expect(sendVerificationRequest).toHaveBeenCalledWith(\n expect.objectContaining({ identifier: firstEmail })\n )\n})", "label": 1, "label_name": "safe"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link = $this->getTaskLink();\n\n $this->response->html($this->template->render('task_internal_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $body = str_replace(array(\"\\n\"), \"
\", $body);\n } else {\n // It's going elsewhere (doesn't like quoted-printable)\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\n }\n $title = $items[$i]->title;\n\n $msg .= \"BEGIN:VEVENT\\n\";\n $msg .= $dtstart . $dtend;\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\n if ($title) {\n $msg .= \"SUMMARY:$title\\n\";\n }\n if ($body) {\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\n }\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\n if (!empty($this->config['usecategories'])) {\n if (!empty($items[$i]->expCat[0]->title)) {\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\n } else {\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\n }\n }\n $msg .= \"END:VEVENT\\n\";\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " protected function assertSigFig($n, $sigfigs)\n {\n $converter = new HTMLPurifier_UnitConverter();\n $result = $converter->getSigFigs($n);\n $this->assertIdentical($result, $sigfigs);\n }", "label": 1, "label_name": "safe"} -{"code": " $count += $db->dropTable($basename);\n }\n\n flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');\n expHistory::back();\n }", "label": 1, "label_name": "safe"} -{"code": "static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_rng rrng;\n\n\tstrncpy(rrng.type, \"rng\", sizeof(rrng.type));\n\n\trrng.seedsize = alg->cra_rng.seedsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_RNG,\n\t\t sizeof(struct crypto_report_rng), &rrng))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label": 1, "label_name": "safe"} -{"code": "(G.height=H+J-G.y,G.y=Math.min(G.y,H+J));var S=(G.x-F)/P*100;P=100-(G.x+G.width-F)/P*100;F=(G.y-H)/J*100;G=100-(G.y+G.height-H)/J*100;return\"inset(\"+mxUtils.format(F)+\"% \"+mxUtils.format(P)+\"% \"+mxUtils.format(G)+\"% \"+mxUtils.format(S)+\"%\"+(C?\" round \"+q+\"%\":E?\" round 50%\":\"\")+\")\"}function n(C){null!=l&&(!0!==C&&(l.model.setGeometry(x,p.clone()),q=5,t.value=q),l.model.setStyle(x,y+m()),l.selectAll(),O.style.visibility=B.checked?\"visible\":\"hidden\")}var v=document.createElement(\"div\"),d=document.createElement(\"div\");", "label": 1, "label_name": "safe"} -{"code": "AspectDialog.prototype.createPageItem=function(b,f,l){var d=document.createElement(\"div\");d.className=\"geAspectDlgListItem\";d.setAttribute(\"data-page-id\",b);d.innerHTML='
'+mxUtils.htmlEntities(f)+\"
\";this.pagesContainer.appendChild(d);var t=this.createViewer(d.childNodes[0],l);f=mxUtils.bind(this,function(){null!=this.selectedItem&&(this.selectedItem.className=\"geAspectDlgListItem\");this.selectedItem=d;\nthis.selectedPage=b;d.className+=\" geAspectDlgListItemSelected\";this.layersContainer.innerHTML=\"\";this.selectedLayers={};this.okBtn.setAttribute(\"disabled\",\"disabled\");var u=t.model;u=u.getChildCells(u.getRoot());for(var E=0;E 'jsmith', :password => 'jsmith', :back_url => back_url\n assert_redirected_to '/my/page'\n end\n ensure\n Redmine::Utils.relative_url_root = @relative_url_root\n end", "label": 0, "label_name": "vulnerable"} -{"code": "this.graph.getTooltip(c,d,e,f);this.show(k,e,f);this.state=c;this.node=d;this.stateSource=g}}),this.delay)}};mxTooltipHandler.prototype.hide=function(){this.resetTimer();this.hideTooltip()};mxTooltipHandler.prototype.hideTooltip=function(){null!=this.div&&(this.div.style.visibility=\"hidden\",this.div.innerHTML=\"\")};", "label": 0, "label_name": "vulnerable"} -{"code": "\"1\":null},G.getVerticesAndEdges())},{install:function(J){this.listener=function(){J(Editor.sketchMode)};F.addListener(\"sketchModeChanged\",this.listener)},destroy:function(){F.removeListener(this.listener)}});B.appendChild(N)}return B};var n=Menus.prototype.init;Menus.prototype.init=function(){n.apply(this,arguments);var B=this.editorUi,F=B.editor.graph;B.actions.get(\"editDiagram\").label=mxResources.get(\"formatXml\")+\"...\";B.actions.get(\"createShape\").label=mxResources.get(\"shape\")+\"...\";B.actions.get(\"outline\").label=", "label": 1, "label_name": "safe"} -{"code": "func matchLimit(str, pattern string) bool {\n\tmatched, _ := match.MatchLimit(str, pattern, 10000)\n\treturn matched\n}", "label": 1, "label_name": "safe"} -{"code": "void HttpIntegrationTest::testLargeRequestTrailers(uint32_t size, uint32_t max_size) {\n // `size` parameter is the size of the trailer that will be added to the\n // request. The actual request byte size will exceed `size` due to keys\n // and other headers.\n\n config_helper_.addConfigModifier(\n [&](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm)\n -> void { hcm.mutable_max_request_headers_kb()->set_value(max_size); });\n max_request_headers_kb_ = max_size;\n Http::TestHeaderMapImpl request_trailers{{\"trailer\", \"trailer\"}};\n request_trailers.addCopy(\"big\", std::string(size * 1024, 'a'));\n\n initialize();\n\n codec_client_ = makeHttpConnection(lookupPort(\"http\"));\n fake_upstreams_[0]->set_allow_unexpected_disconnects(true);\n\n auto encoder_decoder = codec_client_->startRequest(default_request_headers_);\n request_encoder_ = &encoder_decoder.first;\n auto response = std::move(encoder_decoder.second);\n codec_client_->sendData(*request_encoder_, 10, false);\n codec_client_->sendTrailers(*request_encoder_, request_trailers);\n\n if (size >= max_size && downstream_protocol_ == Http::CodecClient::Type::HTTP2) {\n // For HTTP/2, expect a stream reset when the size of the trailers is larger than the maximum\n // limit.\n response->waitForReset();\n codec_client_->close();\n EXPECT_FALSE(response->complete());\n\n } else {\n waitForNextUpstreamRequest();\n upstream_request_->encodeHeaders(default_response_headers_, true);\n response->waitForEndStream();\n EXPECT_TRUE(response->complete());\n }\n}", "label": 1, "label_name": "safe"} -{"code": "def table_xchange_author_title():\n vals = request.get_json().get('xchange')\n edited_books_id = False\n if vals:\n for val in vals:\n modify_date = False\n book = calibre_db.get_book(val)\n authors = book.title\n book.authors = calibre_db.order_authors([book])\n author_names = []\n for authr in book.authors:\n author_names.append(authr.name.replace('|', ','))\n\n title_change = handle_title_on_edit(book, \" \".join(author_names))\n input_authors, authorchange, renamed = handle_author_on_edit(book, authors)\n if authorchange or title_change:\n edited_books_id = book.id\n modify_date = True\n\n if config.config_use_google_drive:\n gdriveutils.updateGdriveCalibreFromLocal()\n\n if edited_books_id:\n helper.update_dir_structure(edited_books_id, config.config_calibre_dir, input_authors[0],\n renamed_author=renamed)\n if modify_date:\n book.last_modified = datetime.utcnow()\n try:\n calibre_db.session.commit()\n except (OperationalError, IntegrityError) as e:\n calibre_db.session.rollback()\n log.error_or_exception(\"Database error: %s\", e)\n return json.dumps({'success': False})\n\n if config.config_use_google_drive:\n gdriveutils.updateGdriveCalibreFromLocal()\n return json.dumps({'success': True})\n return \"\"", "label": 1, "label_name": "safe"} -{"code": "OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)\n{\n static const char module[]=\"OJPEGDecode\";\n\tOJPEGState* sp=(OJPEGState*)tif->tif_data;\n\t(void)s;\n if( !sp->decoder_ok )\n {\n TIFFErrorExt(tif->tif_clientdata,module,\"Cannot decode: decoder not correctly initialized\");\n return 0;\n }\n\tif (sp->libjpeg_jpeg_query_style==0)\n\t{\n\t\tif (OJPEGDecodeRaw(tif,buf,cc)==0)\n\t\t\treturn(0);\n\t}\n\telse\n\t{\n\t\tif (OJPEGDecodeScanlines(tif,buf,cc)==0)\n\t\t\treturn(0);\n\t}\n\treturn(1);\n}", "label": 1, "label_name": "safe"} -{"code": "fa,la,ra){R.addItem(la,null,mxUtils.bind(this,function(){var u=new CreateGraphDialog(O,la,ra);O.showDialog(u.container,620,420,!0,!1);u.init()}),fa)};this.put(\"insertLayout\",new Menu(mxUtils.bind(this,function(R,fa){for(var la=0;lawriteElement('alias', $alias->toString());\n }", "label": 1, "label_name": "safe"} -{"code": " async def actset(self, ctx):\r\n \"\"\"\r\n Configure various settings for the act cog.\r\n \"\"\"\r", "label": 0, "label_name": "vulnerable"} -{"code": "jQuery&&function(a){a.extend(a.fn,{uploadify:function(e){a(this).each(function(){settings=a.extend({id:a(this).attr(\"id\"),uploader:\"uploadify.swf\",script:\"uploadify.php\",expressInstall:null,folder:\"\",height:30,width:110,cancelImg:\"cancel.png\",wmode:\"opaque\",scriptAccess:\"sameDomain\",fileDataName:\"Filedata\",method:\"POST\",queueSizeLimit:999,simUploadLimit:1,queueID:!1,displayData:\"percentage\",onInit:function(){},onSelect:function(){},onQueueFull:function(){},onCheck:function(){},onCancel:function(){},", "label": 1, "label_name": "safe"} -{"code": " class func nameColor(for accentColor: ZMAccentColor, variant: ColorSchemeVariant) -> UIColor {\n let accentColor = AccentColor(ZMAccentColor: accentColor) ?? .strongBlue\n let coefficientsArray = variant == .dark ? accentColorNameColorBlendingCoefficientsDark : accentColorNameColorBlendingCoefficientsLight\n let coefficient = coefficientsArray[Int(accentColor.rawValue)]\n let background: UIColor = variant == .dark ? .black : .white\n return background.mix(UIColor(for: accentColor), amount: coefficient)\n }", "label": 1, "label_name": "safe"} -{"code": " constructor(str, range, input, replaceDefaultBoolean) {\n super();\n Error.captureStackTrace(this, ERR_OUT_OF_RANGE);\n\n assert(range, 'Missing \"range\" argument');\n let msg = (replaceDefaultBoolean\n ? str\n : `The value of \"${str}\" is out of range.`);\n let received;\n if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) {\n received = addNumericalSeparator(String(input));\n } else if (typeof input === 'bigint') {\n received = String(input);\n if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT)\n received = addNumericalSeparator(received);\n received += 'n';\n } else {\n received = inspect(input);\n }\n msg += ` It must be ${range}. Received ${received}`;\n\n this.message = msg;\n }", "label": 1, "label_name": "safe"} -{"code": "this.useCanvasForExport||\".png\"!=z||(z=\".drawio\"),\".svg\"===z||\".xml\"===z||\".html\"===z||\".png\"===z||\".drawio\"===z)&&(x=A+z)}v=new LocalFile(this,v,null!=urlParams.title?decodeURIComponent(urlParams.title):x,!0);v.getHash=function(){return b};this.fileLoaded(v,!0)?null!=d&&d():m()||this.handleError({message:mxResources.get(\"fileNotFound\")},mxResources.get(\"errorLoadingFile\"))}else m()||this.handleError({message:mxResources.get(\"fileNotFound\")},mxResources.get(\"errorLoadingFile\"))}),mxUtils.bind(this,", "label": 0, "label_name": "vulnerable"} -{"code": " it { should contain_class('composer::params') }", "label": 0, "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, "label_name": "vulnerable"} -{"code": "function(u,D,K,T,N,Q,R,Y,ba,ea){if(null!=K&&null==mxMarker.markers[K]){var Z=this.getPackageForType(K);null!=Z&&mxStencilRegistry.getStencil(Z)}return V.apply(this,arguments)};var M=mxStencil.prototype.drawShape;mxStencil.prototype.drawShape=function(u,D,K,T,N,Q){\"1\"==mxUtils.getValue(D.style,\"lineShape\",null)&&u.setFillColor(mxUtils.getValue(D.style,mxConstants.STYLE_STROKECOLOR,this.stroke));return M.apply(this,arguments)};PrintDialog.prototype.create=function(u,D){function K(){aa.value=Math.max(1,", "label": 1, "label_name": "safe"} -{"code": "static long madvise_willneed(struct vm_area_struct *vma,\n\t\t\t struct vm_area_struct **prev,\n\t\t\t unsigned long start, unsigned long end)\n{\n\tstruct file *file = vma->vm_file;\n\n#ifdef CONFIG_SWAP\n\tif (!file) {\n\t\t*prev = vma;\n\t\tforce_swapin_readahead(vma, start, end);\n\t\treturn 0;\n\t}\n\n\tif (shmem_mapping(file->f_mapping)) {\n\t\t*prev = vma;\n\t\tforce_shm_swapin_readahead(vma, start, end,\n\t\t\t\t\tfile->f_mapping);\n\t\treturn 0;\n\t}\n#else\n\tif (!file)\n\t\treturn -EBADF;\n#endif\n\n\tif (IS_DAX(file_inode(file))) {\n\t\t/* no bad return value, but ignore advice */\n\t\treturn 0;\n\t}\n\n\t*prev = vma;\n\tstart = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;\n\tif (end > vma->vm_end)\n\t\tend = vma->vm_end;\n\tend = ((end - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;\n\n\tforce_page_cache_readahead(file->f_mapping, file, start, end - start);\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tprop: function( elem, value, type, i, name ) {\n\t\t// Handle executable functions\n\t\tif ( jQuery.isFunction( value ) )\n\t\t\tvalue = value.call( elem, i );\n\n\t\t// Handle passing in a number to a CSS property\n\t\treturn typeof value === \"number\" && type == \"curCSS\" && !exclude.test( name ) ?\n\t\t\tvalue + \"px\" :\n\t\t\tvalue;\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": " def create\n command = ['install']\n # Yes Symbols instead of Booleans because we get Symbols from Puppet when\n # we use the force or resource parameters. This is madness!\n if resource[:keep] == :true\n command.push('--keep')\n end\n if resource[:name].split('-').last == 'debug'\n command.push('--debug')\n command.push(resource[:name].split('-')[0..-1])\n else\n command.push(resource[:name])\n end\n notice(\"Going to build #{resource[:name]}. This may take some time...\")\n pyenv(command)\n @property_hash[:ensure] = :present\n pyenv('rehash')\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function testFilterEmptyPath()\n {\n $this->assertFiltering('?q=s#frag', 'http://example.com/foo/bar.html?q=s#frag');\n }", "label": 1, "label_name": "safe"} -{"code": " public function autocomplete() {\n return;\n global $db;\n\n $model = $this->params['model'];\n $mod = new $model();\n $srchcol = explode(\",\",$this->params['searchoncol']);\n /*for ($i=0; $i=1) $sql .= \" OR \";\n $sql .= $srchcol[$i].' LIKE \\'%'.$this->params['query'].'%\\'';\n }*/\n // $sql .= ' AND parent_id=0';\n //eDebug($sql);\n\n //$res = $mod->find('all',$sql,'id',25);\n $sql = \"select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from \".$db->prefix.\"product as p INNER JOIN \".$db->prefix.\"content_expfiles as cef ON p.id=cef.content_id INNER JOIN \".$db->prefix.\"expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"') desc LIMIT 25\";\n //$res = $db->selectObjectsBySql($sql);\n //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');\n\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label": 1, "label_name": "safe"} -{"code": " if ($v !== true) $this->error('must be a lookup array');\n }\n return $this;\n }", "label": 1, "label_name": "safe"} -{"code": " public function validate() {\n global $db;\n // check for an sef url field. If it exists make sure it's valid and not a duplicate\n //this needs to check for SEF URLS being turned on also: TODO\n\n if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {\n if (empty($this->sef_url)) $this->makeSefUrl();\n if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();\n if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url'] = array();\n }\n\n // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router\n // mapped view and src hasn't been passed in via link to the form \n if (isset($this->id) && empty($this->location_data)) {\n $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);\n if (!empty($loc)) $this->location_data = $loc;\n }\n\n // run the validation as defined in the models\n if (!isset($this->validates)) return true;\n $messages = array();\n $post = empty($_POST) ? array() : expString::sanitize($_POST);\n foreach ($this->validates as $validation=> $field) {\n foreach ($field as $key=> $value) {\n $fieldname = is_numeric($key) ? $value : $key;\n $opts = is_numeric($key) ? array() : $value;\n $ret = expValidator::$validation($fieldname, $this, $opts);\n if (!is_bool($ret)) {\n $messages[] = $ret;\n expValidator::setErrorField($fieldname);\n unset($post[$fieldname]);\n }\n }\n }\n\n if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function selectArraysBySql($sql) { \n $res = @mysqli_query($this->connection, $this->injectProof($sql));\n if ($res == null)\n return array();\n $arrays = array();\n for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)\n $arrays[] = mysqli_fetch_assoc($res);\n return $arrays;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "!0,0,mxUtils.bind(this,function(e){this.hsplitPosition=e;this.refresh()})))};EditorUi.prototype.createStatusContainer=function(){var b=document.createElement(\"a\");b.className=\"geItem geStatus\";return b};EditorUi.prototype.setStatusText=function(b){this.statusContainer.innerHTML=b;0==this.statusContainer.getElementsByTagName(\"div\").length&&(this.statusContainer.innerText=\"\",b=this.createStatusDiv(b),this.statusContainer.appendChild(b))};", "label": 1, "label_name": "safe"} -{"code": " it 'should install oracle-jdk' do\n pp = <<-EOS\n class { 'java':\n distribution => 'oracle-jdk',\n }\n EOS\n\n apply_manifest(pp, :expect_failures => true)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "function(d){var f=\"\";if(\"1\"!=urlParams.offline&&\"1\"!=urlParams.demo&&null!=d&&0mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+\"=\"+urlParams[m],g=\"&\")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0mxUtils.indexOf(g,m)&&(d=0==f?d+\"?\":d+\"&\",null!=urlParams[m]&&(d+=m+\"=\"+urlParams[m],f++))}return d};EditorUi.prototype.showLinkDialog=function(d,f,g,m,q){d=new LinkDialog(this,d,f,g,!0,m,q);this.showDialog(d.container,560,130,!0,!0);d.init()};EditorUi.prototype.getServiceCount=function(d){var f=1;null==this.drive&&\"function\"!==typeof window.DriveClient||f++;null==this.dropbox&&\"function\"!==typeof window.DropboxClient||f++;null==this.oneDrive&&\"function\"!==typeof window.OneDriveClient||", "label": 0, "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": 1, "label_name": "safe"} -{"code": " ipBlacklist() {\n const instance = Template.instance();\n return instance.ipBlacklist.get();\n },", "label": 1, "label_name": "safe"} -{"code": "func (mr *MockAuthorizeResponderMockRecorder) AddFragment(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddFragment\", reflect.TypeOf((*MockAuthorizeResponder)(nil).AddFragment), arg0, arg1)\n}", "label": 1, "label_name": "safe"} -{"code": " public boolean check(String pArg) {\n if (patterns == null || patterns.size() == 0) {\n return true;\n }\n for (Pattern pattern : patterns) {\n if (pattern.matcher(pArg).matches()) {\n return true;\n }\n }\n return false;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getSchemeObj($config, $context)\n {\n $registry = HTMLPurifier_URISchemeRegistry::instance();\n if ($this->scheme !== null) {\n $scheme_obj = $registry->getScheme($this->scheme, $config, $context);\n if (!$scheme_obj) {\n return false;\n } // invalid scheme, clean it out\n } else {\n // no scheme: retrieve the default one\n $def = $config->getDefinition('URI');\n $scheme_obj = $def->getDefaultScheme($config, $context);\n if (!$scheme_obj) {\n // something funky happened to the default scheme object\n trigger_error(\n 'Default scheme object \"' . $def->defaultScheme . '\" was not readable',\n E_USER_WARNING\n );\n return false;\n }\n }\n return $scheme_obj;\n }", "label": 1, "label_name": "safe"} -{"code": " public static function getRequested()\n {\n if (!isset($_SERVER['REQUEST_METHOD'])) {\n // ALERT - no current URL\n throw new Exception('Script was not called through a webserver');\n }\n\n // Begin with a relative URL\n $url = new self($_SERVER['REQUEST_URI']);\n $url->_scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';\n // Set host and possibly port\n $url->setAuthority($_SERVER['HTTP_HOST']);\n return $url;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "(z=2);return z};var I=mxVertexHandler.prototype.getSelectionBorderBounds;mxVertexHandler.prototype.getSelectionBorderBounds=function(){return I.apply(this,arguments).grow(-this.getSelectionBorderInset())};var V=null,Q=mxVertexHandler.prototype.createCustomHandles;mxVertexHandler.prototype.createCustomHandles=function(){null==V&&(V=mxCellRenderer.defaultShapes.tableLine);var z=Q.apply(this,arguments);if(this.graph.isTable(this.state.cell)){var L=function(Sa,za,wa){for(var Ea=[],Da=0;Dalock);\n\tspool->count = 1;\n\tspool->max_hpages = nr_blocks;\n\tspool->used_hpages = 0;\n\n\treturn spool;\n}", "label": 1, "label_name": "safe"} -{"code": " from: globalDb.getServerTitle() + \" <\" + returnAddress + \">\",\n subject: \"Testing your Sandstorm's SMTP setting\",\n text: \"Success! Your outgoing SMTP is working.\",\n smtpConfig: restConfig,\n });\n } catch (e) {\n // Attempt to give more accurate error messages for a variety of known failure modes,\n // and the actual exception data in the event a user hits a new failure mode.\n if (e.syscall === \"getaddrinfo\") {\n if (e.code === \"EIO\" || e.code === \"ENOTFOUND\") {\n throw new Meteor.Error(\"getaddrinfo \" + e.code, \"Couldn't resolve \\\"\" + smtpConfig.hostname + \"\\\" - check for typos or broken DNS.\");\n }\n } else if (e.syscall === \"connect\") {\n if (e.code === \"ECONNREFUSED\") {\n throw new Meteor.Error(\"connect ECONNREFUSED\", \"Server at \" + smtpConfig.hostname + \":\" + smtpConfig.port + \" refused connection. Check your settings, firewall rules, and that your mail server is up.\");\n }\n } else if (e.name === \"AuthError\") {\n throw new Meteor.Error(\"auth error\", \"Authentication failed. Check your credentials. Message from \" +\n smtpConfig.hostname + \": \" + e.data);\n }\n\n throw new Meteor.Error(\"other-email-sending-error\", \"Error while trying to send test email: \" + JSON.stringify(e));\n }\n },", "label": 0, "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 (newName != null && newName.matches(\".*[&<>\\\"`']+.*\")) {\n throw new ServletException(\"Group ID must not contain any HTML markup.\");\n }\n\n if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {\n m_groupRepository.renameGroup(oldName, newName);\n }\n \n return listGroups(request, response);\n }", "label": 1, "label_name": "safe"} -{"code": " public function handle($request, Closure $next)\n {\n\n $checkCart = cart_get_items_count();\n\n if (!$checkCart) {\n //$shop_page = get_content('single=true&content_type=page&is_shop=1');\n $shop_page = app()->content_repository->getFirstShopPage();\n\n $redir = site_url();\n if ($shop_page and isset($shop_page['id'])) {\n $link = content_link($shop_page['id']);\n if ($link) {\n $redir = $link;\n }\n\n }\n\n return redirect($redir);\n }\n\n $requiresRegistration = get_option('shop_require_registration', 'website') == '1';\n if ($requiresRegistration and is_logged() == false) {\n return redirect(route('checkout.login'));\n }\n\n return $next($request);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static int proc_dmesg_restrict(struct ctl_table *table, int write,\n\t\t\t\tvoid __user *buffer, size_t *lenp, loff_t *ppos)\n{\n\tif (write && !capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\treturn proc_dointvec_minmax(table, write, buffer, lenp, ppos);\n}", "label": 1, "label_name": "safe"} -{"code": "exports.getPadRaw = function(padId, callback){\n async.waterfall([\n function(cb){\n\n // Get the Pad\n db.findKeys(\"pad:\"+padId, null, function(err,padcontent){\n if(!err){\n cb(err, padcontent);\n }\n })\n },\n function(padcontent,cb){\n\n // Get the Pad available content keys\n db.findKeys(\"pad:\"+padId+\":*\", null, function(err,records){\n if(!err){\n for (var key in padcontent) { records.push(padcontent[key]);}\n cb(err, records);\n }\n })\n },\n function(records, cb){\n var data = {};\n\n async.forEachSeries(Object.keys(records), function(key, r){\n\n // For each piece of info about a pad.\n db.get(records[key], function(err, entry){\n data[records[key]] = entry;\n\n // Get the Pad Authors\n if(entry.pool && entry.pool.numToAttrib){\n var authors = entry.pool.numToAttrib;\n async.forEachSeries(Object.keys(authors), function(k, c){\n if(authors[k][0] === \"author\"){\n var authorId = authors[k][1];\n\n // Get the author info\n db.get(\"globalAuthor:\"+authorId, function(e, authorEntry){\n if(authorEntry && authorEntry.padIDs) authorEntry.padIDs = padId;\n if(!e) data[\"globalAuthor:\"+authorId] = authorEntry;\n });\n\n }\n // console.log(\"authorsK\", authors[k]);\n c(null);\n });\n }\n r(null); // callback;\n });\n }, function(err){ \n cb(err, data);\n })\n }\n ], function(err, data){\n callback(null, data);\n });\n}", "label": 1, "label_name": "safe"} -{"code": "\tpublic EnhancedXStream(boolean export) {\n\t\tsuper();\n\n\t\tif (export) {\n\t\t\taddDefaultImplementation(PersistentList.class, List.class);\n\t\t\taddDefaultImplementation(PersistentBag.class, List.class);\n\t\t\taddDefaultImplementation(PersistentMap.class, Map.class);\n\t\t\taddDefaultImplementation(PersistentSortedMap.class, Map.class);\n\t\t\taddDefaultImplementation(PersistentSet.class, Set.class);\n\t\t\taddDefaultImplementation(PersistentSortedSet.class, Set.class);\n\t\t\taddDefaultImplementation(ArrayList.class, List.class);\n\n\t\t\tregisterConverter(new CollectionConverter(getMapper()) {\n\t\t\t\t@Override\n\t\t\t\tpublic boolean canConvert(@SuppressWarnings(\"rawtypes\") Class type) {\n\t\t\t\t\treturn PersistentList.class == type || PersistentBag.class == type;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tregisterConverter(new MapConverter(getMapper()) {\n\t\t\t\t@Override\n\t\t\t\tpublic boolean canConvert(@SuppressWarnings(\"rawtypes\") Class type) {\n\t\t\t\t\treturn PersistentMap.class == type;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "\tprotected function sort(&$rowsKey, $sortColumn) {\n\t\t$sortMethod = $this->getTableSortMethod();\n\t\n\t\tif ($sortColumn < 0) {\n\t\t\tswitch ($sortMethod) {\n\t\t\t\tcase 'natural':\n\t\t\t\t\t// Reverse natsort()\n uasort($rowsKey, function($first, $second) {\n \treturn strnatcmp($second, $first);\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'standard':\n\t\t\t\tdefault:\n\t\t\t\t\tarsort($rowsKey);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tswitch ($sortMethod) {\n\t\t\t\tcase 'natural':\n\t\t\t\tnatsort($rowsKey);\n\t\t\t\tbreak;\n\t\t\tcase 'standard':\n\t\t\tdefault:\n\t\t\t\tasort($rowsKey);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,\n int *got_frame, uint8_t *data_start,\n unsigned int data_size)\n{\n WebPContext *s = avctx->priv_data;\n AVPacket pkt;\n int ret;\n\n if (!s->initialized) {\n ff_vp8_decode_init(avctx);\n s->initialized = 1;\n if (s->has_alpha)\n avctx->pix_fmt = AV_PIX_FMT_YUVA420P;\n }\n s->lossless = 0;\n\n if (data_size > INT_MAX) {\n av_log(avctx, AV_LOG_ERROR, \"unsupported chunk size\\n\");\n return AVERROR_PATCHWELCOME;\n }\n\n av_init_packet(&pkt);\n pkt.data = data_start;\n pkt.size = data_size;\n\n ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt);\n if (ret < 0)\n return ret;\n\n update_canvas_size(avctx, avctx->width, avctx->height);\n\n if (s->has_alpha) {\n ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data,\n s->alpha_data_size);\n if (ret < 0)\n return ret;\n }\n return ret;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "export function getConfig(section: string, uri?: vscode.Uri) {\n if (!uri) {\n if (vscode.window.activeTextEditor) {\n uri = vscode.window.activeTextEditor.document.uri;\n } else {\n uri = null;\n }\n }\n return defaultConfig.get(section, uri);\n}", "label": 1, "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, "label_name": "safe"} -{"code": "function removeFromFilesRail(index) {\n fileobj.splice(index, 1);\n\n printFilesRail();\n}", "label": 1, "label_name": "safe"} -{"code": " public function render($ns, $directive, $value, $name, $config) {\n if (is_array($config) && isset($config[0])) {\n $gen_config = $config[0];\n $config = $config[1];\n } else {\n $gen_config = $config;\n }\n $this->prepareGenerator($gen_config);\n\n $ret = '';\n $ret .= $this->start('label', array('for' => \"$name:Null_$ns.$directive\"));\n $ret .= $this->element('span', \"$ns.$directive:\", array('class' => 'verbose'));\n $ret .= $this->text(' Null/Disabled');\n $ret .= $this->end('label');\n $attr = array(\n 'type' => 'checkbox',\n 'value' => '1',\n 'class' => 'null-toggle',\n 'name' => \"$name\".\"[Null_$ns.$directive]\",\n 'id' => \"$name:Null_$ns.$directive\",\n 'onclick' => \"toggleWriteability('$name:$ns.$directive',checked)\" // INLINE JAVASCRIPT!!!!\n );\n if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) {\n // modify inline javascript slightly\n $attr['onclick'] = \"toggleWriteability('$name:Yes_$ns.$directive',checked);toggleWriteability('$name:No_$ns.$directive',checked)\";\n }\n if ($value === null) $attr['checked'] = 'checked';\n $ret .= $this->elementEmpty('input', $attr);\n $ret .= $this->text(' or ');\n $ret .= $this->elementEmpty('br');\n $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config));\n return $ret;\n }", "label": 1, "label_name": "safe"} -{"code": " protected function _compileRegex()\n {\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, "label_name": "safe"} -{"code": "a.sInfoThousands&&(a.sThousands=a.sInfoThousands);(a=a.sDecimal)&&db(a)}function eb(a){A(a,\"ordering\",\"bSort\");A(a,\"orderMulti\",\"bSortMulti\");A(a,\"orderClasses\",\"bSortClasses\");A(a,\"orderCellsTop\",\"bSortCellsTop\");A(a,\"order\",\"aaSorting\");A(a,\"orderFixed\",\"aaSortingFixed\");A(a,\"paging\",\"bPaginate\");A(a,\"pagingType\",\"sPaginationType\");A(a,\"pageLength\",\"iDisplayLength\");A(a,\"searching\",\"bFilter\");\"boolean\"===typeof a.sScrollX&&(a.sScrollX=a.sScrollX?\"100%\":\"\");\"boolean\"===typeof a.scrollX&&(a.scrollX=\na.scrollX?\"100%\":\"\");if(a=a.aoSearchCols)for(var b=0,c=a.length;b\").css({position:\"fixed\",top:0,left:0,height:1,width:1,overflow:\"hidden\"}).append(h(\"
\").css({position:\"absolute\",top:1,left:1,", "label": 0, "label_name": "vulnerable"} -{"code": " private function getOAuthBaseParams() {\n $params['oauth_version'] = '1.0';\n $params['oauth_signature_method'] = 'HMAC-SHA1';\n\n $params['oauth_consumer_key'] = $this->consumerKey;\n $tokens = $this->getToken();\n if (isset($tokens['token']) && $tokens['token']) {\n $params['oauth_token'] = $tokens['token'];\n }\n $params['oauth_timestamp'] = time();\n $params['oauth_nonce'] = md5(microtime() . mt_rand());\n return $params;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "void mobi_buffer_move(MOBIBuffer *buf, const int offset, const size_t len) {\n size_t aoffset = (size_t) abs(offset);\n unsigned char *source = buf->data + buf->offset;\n if (offset >= 0) {\n if (buf->offset + aoffset + len > buf->maxlen) {\n debug_print(\"%s\", \"End of buffer\\n\");\n buf->error = MOBI_BUFFER_END;\n return;\n }\n source += aoffset;\n } else {\n if ( (buf->offset < aoffset) || (buf->offset + len > buf->maxlen) ) {\n debug_print(\"%s\", \"Beyond start/end of buffer\\n\");\n buf->error = MOBI_BUFFER_END;\n return;\n }\n source -= aoffset;\n }\n memmove(buf->data + buf->offset, source, len);\n buf->offset += len;\n}", "label": 1, "label_name": "safe"} -{"code": "\tpublic function setLoggerChannel($channel = 'Organizr', $username = null)\n\t{\n\t\tif ($this->hasDB()) {\n\t\t\t$setLogger = false;\n\t\t\tif ($username) {\n\t\t\t\t$username = htmlspecialchars($username);\n\t\t\t}\n\t\t\tif ($this->logger) {\n\t\t\t\tif ($channel) {\n\t\t\t\t\tif (strtolower($this->logger->getChannel()) !== strtolower($channel)) {\n\t\t\t\t\t\t$setLogger = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ($username) {\n\t\t\t\t\tif (strtolower($this->logger->getTraceId()) !== strtolower($channel)) {\n\t\t\t\t\t\t$setLogger = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$setLogger = true;\n\t\t\t}\n\t\t\tif ($setLogger) {\n\t\t\t\t$channel = $channel ?: 'Organizr';\n\t\t\t\treturn $this->setupLogger($channel, $username);\n\t\t\t} else {\n\t\t\t\treturn $this->logger;\n\t\t\t}\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " private function generateTempFileData()\n {\n return [\n 'name' => md5(mt_rand()),\n 'tmp_name' => tempnam(sys_get_temp_dir(), ''),\n 'type' => 'image/jpeg',\n 'size' => mt_rand(1000, 10000),\n 'error' => '0',\n ];\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it 'applies cleanly' do\n apply_manifest(pp, :catch_failures => true) do |r|\n expect(r.stderr).to eq(\"\")\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it \"includes the command return value\" do\n expect {\n subject.call ['', '/cant/run/this']\n }.to raise_error Puppet::ParseError, /returned 1\\b/\n end", "label": 0, "label_name": "vulnerable"} -{"code": " protected function getColumn(array $project)\n {\n $column = $this->columnModel->getById($this->request->getIntegerParam('column_id'));\n\n if (empty($column)) {\n throw new PageNotFoundException();\n }\n\n if ($column['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n return $column;\n }", "label": 1, "label_name": "safe"} -{"code": "void luaD_shrinkstack (lua_State *L) {\n int inuse = stackinuse(L);\n int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;\n if (goodsize > LUAI_MAXSTACK)\n goodsize = LUAI_MAXSTACK; /* respect stack limit */\n /* if thread is currently not handling a stack overflow and its\n good size is smaller than current size, shrink its stack */\n if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) &&\n goodsize < L->stacksize)\n luaD_reallocstack(L, goodsize, 0); /* ok if that fails */\n else /* don't change stack */\n condmovestack(L,{},{}); /* (change only for debugging) */\n luaE_shrinkCI(L); /* shrink CI list */\n}", "label": 0, "label_name": "vulnerable"} -{"code": "if(m||p){var O=[],V=null,U=null,Y=null,n=function(ea){W.setAttribute(\"disabled\",\"disabled\");for(var ta=0;ta(parent)) {\n verticalLayout->setMargin(4);\n }\n type->addItem(tr(\"Samba Share\"), (int)Type_Samba);\n type->addItem(tr(\"Samba Share (Auto-discover host and port)\"), (int)Type_SambaAvahi);\n type->addItem(tr(\"Secure Shell (sshfs)\"), (int)Type_SshFs);\n type->addItem(tr(\"Locally Mounted Folder\"), (int)Type_File);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\toptions.create = function() {\n\t\t\t\tcheckbox = $('');\n\t\t\t\t$(this).next().children().before($('').prepend(checkbox));\n\t\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": " foreach($value_arr['ENROLLMENT_INFO'] as $eid=>$ed)\n {\n echo '';\n echo ''.htmlentities($ed['SCHOOL_ID']).'';\n echo ''.htmlentities($ed['CALENDAR']).'';\n echo ''.htmlentities($ed['GRADE']).'';\n echo '
'.htmlentities($ed['SECTION']).'
';\n echo ''.htmlentities($ed['START_DATE']).'';\n echo ''.htmlentities($ed['DROP_DATE']).'';\n echo ''.htmlentities($ed['ENROLLMENT_CODE']).'';\n echo ''.htmlentities($ed['DROP_CODE']).'';\n echo '
';\n \n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " it \"should check for the directory\" do\n expects_directory?(true, resource.value(:path))\n expects_directory?(true, File.join(resource.value(:path), '.svn'))\n provider.exists?\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it \"prints the failure message on error\" do\n expect {\n subject.call ['', '/bin/false', 'failure message!']\n }.to raise_error Puppet::ParseError, /failure message!/\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\"_length\"){e=a.getAttribute(h)||\"\";if(h==\"style\")a:{d=c[h];typeof d==\"string\"&&(d=CKEDITOR.tools.parseCssText(d));typeof e==\"string\"&&(e=CKEDITOR.tools.parseCssText(e,true));g=void 0;for(g in d)if(!(g in e&&(e[g]==d[g]||d[g]==\"inherit\"||e[g]==\"inherit\"))){d=false;break a}d=true}else d=c[h]==e;if(d){if(!b)return true}else if(b)return false}if(b)return true}else return true}return false},checkElementRemovable:function(a,b){if(this.checkElementMatch(a,b))return true;var c=k(this)[a.getName()];if(c){var d;\nif(!(c=c.attributes))return true;for(var e=0;e\",a||b.name,\"\");return c.join(\"\")},getDefinition:function(){return this._.definition}};", "label": 1, "label_name": "safe"} -{"code": " Object.keys(data).forEach((key) => {\n obj.add(deserializer(data[key], baseType) as T);\n });", "label": 0, "label_name": "vulnerable"} -{"code": "func (m *MockHasher) Hash(arg0 context.Context, arg1 []byte) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Hash\", arg0, arg1)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "label": 1, "label_name": "safe"} -{"code": " function sessionValidThru()\n {\n if (!isset($this->session['idle'])) {\n return 0;\n }\n if ($this->idle == 0) {\n return 0;\n }\n return ($this->session['idle'] + $this->idle);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function close($is_user)\n {\n // Send message about closing\n if ($is_user) {\n $this->postMessage(\n self::KIND_EVENTS,\n getlocal(\n \"Visitor {0} left the chat\",\n array(safe_htmlspecialchars($this->userName)),\n $this->locale,\n true\n )\n );\n } else {\n if ($this->state == self::STATE_INVITED) {\n $this->postMessage(\n self::KIND_FOR_AGENT,\n getlocal(\n 'Operator canceled invitation',\n null,\n $this->locale,\n true\n )\n );\n } else {\n $this->postMessage(\n self::KIND_EVENTS,\n getlocal(\n \"Operator {0} left the chat\",\n array(safe_htmlspecialchars($this->agentName)),\n $this->locale,\n true\n )\n );\n }\n }\n\n // Get messages count\n $db = Database::getInstance();\n\n list($message_count) = $db->query(\n (\"SELECT COUNT(*) FROM {message} \"\n . \"WHERE {message}.threadid = :threadid AND ikind = :kind_user\"),\n array(\n ':threadid' => $this->id,\n ':kind_user' => Thread::KIND_USER,\n ),\n array(\n 'return_rows' => Database::RETURN_ONE_ROW,\n 'fetch_type' => Database::FETCH_NUM,\n )\n );\n\n // Close thread if it's not already closed\n if ($this->state != self::STATE_CLOSED) {\n $this->state = self::STATE_CLOSED;\n $this->closed = time();\n $this->messageCount = $message_count;\n $this->save();\n\n $args = array('thread' => $this);\n EventDispatcher::getInstance()->triggerEvent(Events::THREAD_CLOSE, $args);\n }\n }", "label": 1, "label_name": "safe"} -{"code": "static void clear_evtchn_to_irq_row(unsigned row)\n{\n\tunsigned col;\n\n\tfor (col = 0; col < EVTCHN_PER_ROW; col++)\n\t\tWRITE_ONCE(evtchn_to_irq[row][col], -1);\n}", "label": 1, "label_name": "safe"} -{"code": "int rose_parse_facilities(unsigned char *p,\n\tstruct rose_facilities_struct *facilities)\n{\n\tint facilities_len, len;\n\n\tfacilities_len = *p++;\n\n\tif (facilities_len == 0)\n\t\treturn 0;\n\n\twhile (facilities_len > 0) {\n\t\tif (*p == 0x00) {\n\t\t\tfacilities_len--;\n\t\t\tp++;\n\n\t\t\tswitch (*p) {\n\t\t\tcase FAC_NATIONAL:\t\t/* National */\n\t\t\t\tlen = rose_parse_national(p + 1, facilities, facilities_len - 1);\n\t\t\t\tif (len < 0)\n\t\t\t\t\treturn 0;\n\t\t\t\tfacilities_len -= len + 1;\n\t\t\t\tp += len + 1;\n\t\t\t\tbreak;\n\n\t\t\tcase FAC_CCITT:\t\t/* CCITT */\n\t\t\t\tlen = rose_parse_ccitt(p + 1, facilities, facilities_len - 1);\n\t\t\t\tif (len < 0)\n\t\t\t\t\treturn 0;\n\t\t\t\tfacilities_len -= len + 1;\n\t\t\t\tp += len + 1;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tprintk(KERN_DEBUG \"ROSE: rose_parse_facilities - unknown facilities family %02X\\n\", *p);\n\t\t\t\tfacilities_len--;\n\t\t\t\tp++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else\n\t\t\tbreak;\t/* Error in facilities format */\n\t}\n\n\treturn 1;\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "dump_keywords(vector_t *keydump, int level, FILE *fp)\n{\n\tunsigned int i;\n\tkeyword_t *keyword_vec;\n\tchar file_name[21];\n\n\tif (!level) {\n\t\tsnprintf(file_name, sizeof(file_name), \"/tmp/keywords.%d\", getpid());\n\t\tfp = fopen(file_name, \"w\");\n\t\tif (!fp)\n\t\t\treturn;\n\t}\n\n\tfor (i = 0; i < vector_size(keydump); i++) {\n\t\tkeyword_vec = vector_slot(keydump, i);\n\t\tfprintf(fp, \"%*sKeyword : %s (%s)\\n\", level * 2, \"\", keyword_vec->string, keyword_vec->active ? \"active\": \"disabled\");\n\t\tif (keyword_vec->sub)\n\t\t\tdump_keywords(keyword_vec->sub, level + 1, fp);\n\t}\n\n\tif (!level)\n\t\tfclose(fp);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function down(RuleGroup $ruleGroup)\n {\n $maxOrder = $this->repository->maxOrder();\n $order = (int)$ruleGroup->order;\n if ($order < $maxOrder) {\n $newOrder = $order + 1;\n $this->repository->setOrder($ruleGroup, $newOrder);\n }\n\n return redirect(route('rules.index'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "TEST(DefaultCertValidatorTest, TestMultiLevelMatch) {\n // san_multiple_dns_cert matches *.example.com\n bssl::UniquePtr cert = readCertFromFile(TestEnvironment::substitute(\n \"{{ test_rundir \"\n \"}}/test/extensions/transport_sockets/tls/test_data/san_multiple_dns_cert.pem\"));\n envoy::type::matcher::v3::StringMatcher matcher;\n matcher.set_exact(\"foo.api.example.com\");\n std::vector subject_alt_name_matchers;\n subject_alt_name_matchers.push_back(\n SanMatcherPtr{std::make_unique(GEN_DNS, matcher)});\n EXPECT_FALSE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers));\n}", "label": 1, "label_name": "safe"} -{"code": "z,mxUtils.bind(this,function(){var D=null;if(!t){D=parseInt(H.value);var K=parseInt(V.value);D=J.checked||D==G&&K==G?null:{from:Math.max(0,Math.min(E-1,D-1)),to:Math.max(0,Math.min(E-1,K-1))}}c.downloadFile(\"pdf\",null,null,!M.checked,t?!0:!J.checked&&null==D,!W.checked,null!=X&&X.checked,null,null,U.checked,null!=u&&u.checked,D)}),null,mxResources.get(\"export\"));c.showDialog(z.container,300,L,!0,!0)}else c.showDialog((new PrintDialog(c,mxResources.get(\"formatPdf\"))).container,360,null!=c.pages&&1<", "label": 1, "label_name": "safe"} -{"code": " public function test_extractBody_useLastBody()\n {\n $this->assertExtractBody('foobar', 'foobar');\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function __construct( Parameters $parameters, Parser $parser ) {\n\t\tparent::__construct( $parameters, $parser );\n\n\t\t$this->textSeparator = $parameters->getParameter( 'inlinetext' );\n\t\t$listSeparators = $parameters->getParameter( 'listseparators' );\n\n\t\tif ( isset( $listSeparators[0] ) ) {\n\t\t\t$this->listStart = $listSeparators[0];\n\t\t}\n\n\t\tif ( isset( $listSeparators[1] ) ) {\n\t\t\t$this->itemStart = $listSeparators[1];\n\t\t}\n\n\t\tif ( isset( $listSeparators[2] ) ) {\n\t\t\t$this->itemEnd = $listSeparators[2];\n\t\t}\n\n\t\tif ( isset( $listSeparators[3] ) ) {\n\t\t\t$this->listEnd = $listSeparators[3];\n\t\t}\n\t}", "label": 1, "label_name": "safe"} -{"code": " public function validate() {\n global $db;\n // check for an sef url field. If it exists make sure it's valid and not a duplicate\n //this needs to check for SEF URLS being turned on also: TODO\n\n if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {\n if (empty($this->sef_url)) $this->makeSefUrl();\n if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();\n if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url'] = array();\n }\n\n // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router\n // mapped view and src hasn't been passed in via link to the form \n if (isset($this->id) && empty($this->location_data)) {\n $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);\n if (!empty($loc)) $this->location_data = $loc;\n }\n\n // run the validation as defined in the models\n if (!isset($this->validates)) return true;\n $messages = array();\n $post = empty($_POST) ? array() : expString::sanitize($_POST);\n foreach ($this->validates as $validation=> $field) {\n foreach ($field as $key=> $value) {\n $fieldname = is_numeric($key) ? $value : $key;\n $opts = is_numeric($key) ? array() : $value;\n $ret = expValidator::$validation($fieldname, $this, $opts);\n if (!is_bool($ret)) {\n $messages[] = $ret;\n expValidator::setErrorField($fieldname);\n unset($post[$fieldname]);\n }\n }\n }\n\n if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"drops the index\" do\n indexes.create name: 1\n indexes.drop(name: 1).should be_true\n end", "label": 1, "label_name": "safe"} -{"code": " labels: templateInstance.topTasks.get().map((task) => $('').text(task._id).html()),\n datasets: [{\n values: templateInstance.topTasks.get().map((task) => task.count),\n }],\n },\n tooltipOptions: {\n },\n })\n }\n })\n })\n }", "label": 1, "label_name": "safe"} -{"code": " public function onParserError(Exception $exception)\n {\n $this->reporter->paintException($exception);\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct($config, $context)\n {\n $this->config = $config;\n $this->context = $context;\n }", "label": 1, "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, "label_name": "safe"} -{"code": "function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void {\n const response = new ResponseClass({\n responseHeader: { serviceResult: statusCode }\n });\n return channel.send_response(\"MSG\", response, message);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_PY_LONG_LONG(unsigned PY_LONG_LONG value) {\n const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG) ((unsigned PY_LONG_LONG) 0 - (unsigned PY_LONG_LONG) 1), const_zero = (unsigned PY_LONG_LONG) 0;\n const int is_unsigned = neg_one > const_zero;\n if (is_unsigned) {\n if (sizeof(unsigned PY_LONG_LONG) < sizeof(long)) {\n return PyInt_FromLong((long) value);\n } else if (sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long)) {\n return PyLong_FromUnsignedLong((unsigned long) value);\n#ifdef HAVE_LONG_LONG\n } else if (sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned PY_LONG_LONG)) {\n return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);\n#endif\n }\n } else {\n if (sizeof(unsigned PY_LONG_LONG) <= sizeof(long)) {\n return PyInt_FromLong((long) value);\n#ifdef HAVE_LONG_LONG\n } else if (sizeof(unsigned PY_LONG_LONG) <= sizeof(PY_LONG_LONG)) {\n return PyLong_FromLongLong((PY_LONG_LONG) value);\n#endif\n }\n }\n {\n int one = 1; int little = (int)*(unsigned char *)&one;\n unsigned char *bytes = (unsigned char *)&value;\n return _PyLong_FromByteArray(bytes, sizeof(unsigned PY_LONG_LONG),\n little, !is_unsigned);\n }\n}", "label": 1, "label_name": "safe"} -{"code": "struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask)\n{\n\tstruct crypto_alg *alg;\n\n\tif (!name)\n\t\treturn ERR_PTR(-ENOENT);\n\n\tmask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);\n\ttype &= mask;\n\n\talg = crypto_alg_lookup(name, type, mask);\n\tif (!alg) {\n\t\trequest_module(\"%s\", name);\n\n\t\tif (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &\n\t\t CRYPTO_ALG_NEED_FALLBACK))\n\t\t\trequest_module(\"%s-all\", name);\n\n\t\talg = crypto_alg_lookup(name, type, mask);\n\t}\n\n\tif (alg)\n\t\treturn crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg;\n\n\treturn crypto_larval_add(name, type, mask);\n}", "label": 0, "label_name": "vulnerable"} -{"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)}),L,mxResources.get(\"changeUser\"),mxUtils.bind(this,function(){function u(){G.innerText=\"\";for(var N=0;N\");I.setAttribute(\"disabled\",\"disabled\");G.appendChild(I)}I=document.createElement(\"option\");mxUtils.write(I,mxResources.get(\"addAccount\"));I.value=D.length;G.appendChild(I)}var D=this.drive.getUsersList(),B=document.createElement(\"div\"),C=document.createElement(\"span\");C.style.marginTop=\"6px\";mxUtils.write(C,mxResources.get(\"changeUser\")+\": \");B.appendChild(C);var G=document.createElement(\"select\");G.style.width=\"200px\";u();mxEvent.addListener(G,\"change\",mxUtils.bind(this,", "label": 1, "label_name": "safe"} -{"code": "void Mounter::mountResult(int st)\n{\n QProcess *proc=dynamic_cast(sender());\n qWarning() << \"MOUNT RESULT\" << st << (void *)proc;\n if (proc) {\n procCount--;\n proc->close();\n proc->deleteLater();\n if (tempFiles.contains(proc)) {\n tempFiles[proc]->close();\n tempFiles[proc]->deleteLater();\n tempFiles.remove(proc);\n }\n emit mountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n }\n startTimer();\n}", "label": 0, "label_name": "vulnerable"} -{"code": "R_API ut8 *r_bin_java_get_attr_buf(RBinJavaObj *bin, ut64 sz, const ut64 offset, const ut8 *buf, const ut64 len) {\n\t// XXX this pending is wrong and too expensive\n\tint pending = len - offset;\n\tconst ut8 *a_buf = offset + buf;\n\tut8 *attr_buf = (ut8 *) calloc (pending + 1, 1);\n\tif (!attr_buf) {\n\t\teprintf (\"Unable to allocate enough bytes (0x%04\"PFMT64x\n\t\t\t\") to read in the attribute.\\n\", sz);\n\t\treturn attr_buf;\n\t}\n\tmemcpy (attr_buf, a_buf, pending); // sz+1);\n\treturn attr_buf;\n}", "label": 1, "label_name": "safe"} -{"code": " public static function desc($vars){\n if(!empty($vars)){\n $desc = substr(strip_tags(htmlspecialchars_decode($vars).\". \".self::$desc),0,150);\n }else{\n $desc = substr(self::$desc,0,150);\n }\n \n return $desc;\n }", "label": 1, "label_name": "safe"} -{"code": " protected function getCategory(array $project)\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n if ($category['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n return $category;\n }", "label": 1, "label_name": "safe"} -{"code": "\tprotected function cacheDir($path) {\n\t\t$this->dirsCache[$path] = array();\n\n\t\tif (preg_match('/\\'|\\\"/', $path)) {\n\t\t\tforeach (ftp_nlist($this->connect, $path) as $p) {\n\t\t\t\tif (($stat = $this->_stat($p)) &&empty($stat['hidden'])) {\n\t\t\t\t\t// $files[] = $stat;\n\t\t\t\t\t$this->dirsCache[$path][] = $p;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tforeach (ftp_rawlist($this->connect, $path) as $raw) {\n\t\t\tif (($stat = $this->parseRaw($raw))) {\n\t\t\t\t$p = $path.DIRECTORY_SEPARATOR.$stat['name'];\n\t\t\t\t\t// $files[] = $stat;\n\t\t\t\t\t$this->dirsCache[$path][] = $p;\n\t\t\t\t\t//$stat['name'] = $p;\n\t\t\t\t\t$this->filesCache[$p] = $stat;\n\t\t\t}\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "function replaceInfo (arg) {\n const isArray = Array.isArray(arg)\n const isString = typeof arg === 'string'\n\n if (!isArray && !isString) return arg\n\n const args = isString ? arg.split(' ') : arg\n const info = args.map(arg => {\n try {\n const url = new URL(arg)\n return url.password === '' ? arg : arg.replace(url.password, '***')\n } catch (e) { return arg }\n })\n\n return isString ? info.join(' ') : info\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "func TestWrapHandler(t *testing.T) {\n\trouter := http.NewServeMux()\n\n\trouter.Handle(\"/\", Handler(DocExpansion(\"none\"), DomID(\"#swagger-ui\")))\n\n\tw1 := performRequest(\"GET\", \"/index.html\", router)\n\tassert.Equal(t, 200, w1.Code)\n\tassert.Equal(t, w1.Header()[\"Content-Type\"][0], \"text/html; charset=utf-8\")\n\n\tw2 := performRequest(\"GET\", \"/doc.json\", router)\n\tassert.Equal(t, 500, w2.Code)\n\n\tswag.Register(swag.Name, &mockedSwag{})\n\tw2 = performRequest(\"GET\", \"/doc.json\", router)\n\tassert.Equal(t, 200, w2.Code)\n\tassert.Equal(t, \"application/json; charset=utf-8\", w2.Header().Get(\"content-type\"))\n\n\tw3 := performRequest(\"GET\", \"/favicon-16x16.png\", router)\n\tassert.Equal(t, 200, w3.Code)\n\tassert.Equal(t, w3.Header()[\"Content-Type\"][0], \"image/png\")\n\n\tw4 := performRequest(\"GET\", \"/swagger-ui.css\", router)\n\tassert.Equal(t, 200, w4.Code)\n\tassert.Equal(t, w4.Header()[\"Content-Type\"][0], \"text/css; charset=utf-8\")\n\n\tw5 := performRequest(\"GET\", \"/swagger-ui-bundle.js\", router)\n\tassert.Equal(t, 200, w5.Code)\n\tassert.Equal(t, w5.Header()[\"Content-Type\"][0], \"application/javascript\")\n\n\tw6 := performRequest(\"GET\", \"/notfound\", router)\n\tassert.Equal(t, 404, w6.Code)\n\n\tw7 := performRequest(\"GET\", \"/\", router)\n\tassert.Equal(t, 301, w7.Code)\n}", "label": 0, "label_name": "vulnerable"} -{"code": "module.exports = function(grunt) {\n // Project configuration.\n grunt.initConfig({\n eslint: {\n all: ['index.js', 'lib/**/*.js', 'test/**/*.js', 'examples/**/*.js', 'Gruntfile.js']\n },\n\n mochaTest: {\n all: {\n options: {\n reporter: 'spec'\n },\n src: ['test/**/*-test.js']\n }\n }\n });\n\n // Load the plugin(s)\n grunt.loadNpmTasks('grunt-eslint');\n grunt.loadNpmTasks('grunt-mocha-test');\n\n // Tasks\n grunt.registerTask('default', ['eslint', 'mochaTest']);\n};", "label": 0, "label_name": "vulnerable"} -{"code": " } elseif ($token instanceof HTMLPurifier_Token_Empty) {\n if ($this->_flashCompat && $token->name == \"param\" && !empty($this->_flashStack)) {\n $this->_flashStack[count($this->_flashStack)-1]->param[$token->attr['name']] = $token->attr['value'];\n }\n $attr = $this->generateAttributes($token->attr, $token->name);\n return '<' . $token->name . ($attr ? ' ' : '') . $attr .", "label": 1, "label_name": "safe"} -{"code": " public function testPreserveRecognizedElements()\n {\n $this->assertResult('This is bold text.');\n }", "label": 1, "label_name": "safe"} -{"code": " public function build(ContainerBuilder $container)\n {\n // auto-tag GDPR data providers\n $container\n ->registerForAutoconfiguration(DataProviderInterface::class)\n ->addTag('pimcore.gdpr.data-provider');\n\n $container->addCompilerPass(new SerializerPass());\n $container->addCompilerPass(new GDPRDataProviderPass());\n $container->addCompilerPass(new ImportExportLocatorsPass());\n $container->addCompilerPass(new TranslationServicesPass());\n $container->addCompilerPass(new ContentSecurityPolicyUrlsPass());\n\n /** @var SecurityExtension $extension */\n $extension = $container->getExtension('security');\n $extension->addSecurityListenerFactory(new PreAuthenticatedAdminSessionFactory());\n }", "label": 1, "label_name": "safe"} -{"code": "t.toDataURL();if(z.lengthtranslator\n ->expects($this->once())\n ->method('setLocale')\n ->with($this->equalTo('fr'));\n\n $event = new GetResponseEvent($this->createHttpKernel(), $this->createRequest('fr'), HttpKernelInterface::MASTER_REQUEST);\n $this->listener->onKernelRequest($event);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "zfs_groupmember(zfsvfs_t *zfsvfs, uint64_t id, cred_t *cr)\n{\n#ifdef HAVE_KSID\n\tksid_t\t\t*ksid = crgetsid(cr, KSID_GROUP);\n\tksidlist_t\t*ksidlist = crgetsidlist(cr);\n\tuid_t\t\tgid;\n\n\tif (ksid && ksidlist) {\n\t\tint\t\ti;\n\t\tksid_t\t\t*ksid_groups;\n\t\tuint32_t\tidx = FUID_INDEX(id);\n\t\tuint32_t\trid = FUID_RID(id);\n\n\t\tksid_groups = ksidlist->ksl_sids;\n\n\t\tfor (i = 0; i != ksidlist->ksl_nsid; i++) {\n\t\t\tif (idx == 0) {\n\t\t\t\tif (id != IDMAP_WK_CREATOR_GROUP_GID &&\n\t\t\t\t id == ksid_groups[i].ks_id) {\n\t\t\t\t\treturn (B_TRUE);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst char *domain;\n\n\t\t\t\tdomain = zfs_fuid_find_by_idx(zfsvfs, idx);\n\t\t\t\tASSERT(domain != NULL);\n\n\t\t\t\tif (strcmp(domain,\n\t\t\t\t IDMAP_WK_CREATOR_SID_AUTHORITY) == 0)\n\t\t\t\t\treturn (B_FALSE);\n\n\t\t\t\tif ((strcmp(domain,\n\t\t\t\t ksid_groups[i].ks_domain->kd_name) == 0) &&\n\t\t\t\t rid == ksid_groups[i].ks_rid)\n\t\t\t\t\treturn (B_TRUE);\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * Not found in ksidlist, check posix groups\n\t */\n\tgid = zfs_fuid_map_id(zfsvfs, id, cr, ZFS_GROUP);\n\treturn (groupmember(gid, cr));\n#else\n\treturn (B_TRUE);\n#endif\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should pass the provided CSR as the CSR\" do\n Puppet::SSL::CertificateFactory.expects(:build).with do |*args|\n args[1] == @request\n end.returns \"my real cert\"\n @ca.sign(@name, :ca, @request)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label": 0, "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": 1, "label_name": "safe"} -{"code": " private function persistRequest(Request $request)\n {\n return $request->headers->all();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function find($ip, $url, $limit, $method, $start, $end)\n {\n return $this->storage->find($ip, $url, $limit, $method, $this->getTimestamp($start), $this->getTimestamp($end));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function addCC($address, $name = '')\n {\n return $this->addAnAddress('cc', $address, $name);\n }", "label": 0, "label_name": "vulnerable"} -{"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(E){f.saveLevel=9;if(E||null==W)U(E);else{var J=!0,T=null;try{T=window.setTimeout(mxUtils.bind(this,function(){J=!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": 0, "label_name": "vulnerable"} -{"code": "static cJSON *cJSON_New_Item( void )\n{\n\tcJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) );\n\tif ( node )\n\t\tmemset( node, 0, sizeof(cJSON) );\n\treturn node;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "local block_state deflate_huff(s, flush)\n deflate_state *s;\n int flush;\n{\n int bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s->lookahead == 0) {\n fill_window(s);\n if (s->lookahead == 0) {\n if (flush == Z_NO_FLUSH)\n return need_more;\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s->match_length = 0;\n Tracevv((stderr,\"%c\", s->window[s->strstart]));\n _tr_tally_lit (s, s->window[s->strstart], bflush);\n s->lookahead--;\n s->strstart++;\n if (bflush) FLUSH_BLOCK(s, 0);\n }\n s->insert = 0;\n if (flush == Z_FINISH) {\n FLUSH_BLOCK(s, 1);\n return finish_done;\n }\n if (s->sym_next)\n FLUSH_BLOCK(s, 0);\n return block_done;\n}", "label": 1, "label_name": "safe"} -{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "T.appendChild(T.importNode(u[0],!0)),T=T.documentElement));return T};Editor.getDiagramNodeXml=function(u){var E=mxUtils.getTextContent(u),J=null;0mnt_opts, &mntflags, &mntdata) < 0) {\n\t\tfree(mntdata);\n\t\treturn -1;\n\t}\n\n\tret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type,\n\t\t\t mntflags, mntdata, optional);\n\n\tfree(mntdata);\n\n\treturn ret;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function setup_node_links() {\n Ember.debug(\"Setup node links\");\n $(\"#node_start\").click(function() {\n node_link_action(\n \"#node_start\", get_cluster_remote_url() + \"cluster_start\", \"start\"\n );\n });\n $(\"#node_stop\").click(function() {\n var node = $.trim($(\"#node_info_header_title_name\").text());\n fade_in_out(\"#node_stop\");\n node_stop(node, false);\n });\n $(\"#node_restart\").click(function() {\n node_link_action(\n \"#node_restart\", get_cluster_remote_url() + \"node_restart\", \"restart\"\n );\n });\n $(\"#node_standby\").click(function() {\n node_link_action(\n \"#node_standby\", get_cluster_remote_url() + \"node_standby\", \"standby\"\n );\n });\n $(\"#node_unstandby\").click(function() {\n node_link_action(\n \"#node_unstandby\",\n get_cluster_remote_url() + \"node_unstandby\",\n \"unstandby\"\n );\n });\n}", "label": 1, "label_name": "safe"} -{"code": "inline int MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));\n return std::min(shape1.Dims(index1), shape2.Dims(index2));\n}", "label": 1, "label_name": "safe"} -{"code": "static ssize_t driver_override_store(struct device *dev,\n\t\t\t\t struct device_attribute *attr,\n\t\t\t\t const char *buf, size_t count)\n{\n\tstruct platform_device *pdev = to_platform_device(dev);\n\tchar *driver_override, *old = pdev->driver_override, *cp;\n\n\tif (count > PATH_MAX)\n\t\treturn -EINVAL;\n\n\tdriver_override = kstrndup(buf, count, GFP_KERNEL);\n\tif (!driver_override)\n\t\treturn -ENOMEM;\n\n\tcp = strchr(driver_override, '\\n');\n\tif (cp)\n\t\t*cp = '\\0';\n\n\tif (strlen(driver_override)) {\n\t\tpdev->driver_override = driver_override;\n\t} else {\n\t\tkfree(driver_override);\n\t\tpdev->driver_override = NULL;\n\t}\n\n\tkfree(old);\n\n\treturn count;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " setStringInputSource(ThreadContext context, IRubyObject data, IRubyObject url)\n {\n source = new InputSource();\n ParserContext.setUrl(context, source, url);\n\n Ruby ruby = context.getRuntime();\n\n if (!(data instanceof RubyString)) {\n throw ruby.newTypeError(\"must be kind_of String\");\n }\n\n RubyString stringData = (RubyString) data;\n\n if (stringData.encoding(context) != null) {\n RubyString stringEncoding = stringData.encoding(context).asString();\n String encName = NokogiriHelpers.getValidEncodingOrNull(stringEncoding);\n if (encName != null) {\n java_encoding = encName;\n }\n }\n\n ByteList bytes = stringData.getByteList();\n\n stringDataSize = bytes.length() - bytes.begin();\n ByteArrayInputStream stream = new ByteArrayInputStream(bytes.unsafeBytes(), bytes.begin(), bytes.length());\n source.setByteStream(stream);\n source.setEncoding(java_encoding);\n }", "label": 1, "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, "label_name": "safe"} -{"code": "fp_setreadl(struct tok_state *tok, const char* enc)\n{\n PyObject *readline, *io, *stream;\n _Py_IDENTIFIER(open);\n _Py_IDENTIFIER(readline);\n int fd;\n long pos;\n\n fd = fileno(tok->fp);\n /* Due to buffering the file offset for fd can be different from the file\n * position of tok->fp. If tok->fp was opened in text mode on Windows,\n * its file position counts CRLF as one char and can't be directly mapped\n * to the file offset for fd. Instead we step back one byte and read to\n * the end of line.*/\n pos = ftell(tok->fp);\n if (pos == -1 ||\n lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) {\n PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL);\n return 0;\n }\n\n io = PyImport_ImportModuleNoBlock(\"io\");\n if (io == NULL)\n return 0;\n\n stream = _PyObject_CallMethodId(io, &PyId_open, \"isisOOO\",\n fd, \"r\", -1, enc, Py_None, Py_None, Py_False);\n Py_DECREF(io);\n if (stream == NULL)\n return 0;\n\n readline = _PyObject_GetAttrId(stream, &PyId_readline);\n Py_DECREF(stream);\n if (readline == NULL)\n return 0;\n Py_XSETREF(tok->decoding_readline, readline);\n\n if (pos > 0) {\n PyObject *bufobj = _PyObject_CallNoArg(readline);\n if (bufobj == NULL)\n return 0;\n Py_DECREF(bufobj);\n }\n\n return 1;\n}", "label": 1, "label_name": "safe"} -{"code": " it 'should remove Mysql_User[@myhost.mydomain]' do\n should contain_mysql_user('@myhost.mydomain').with_ensure('absent')\n end", "label": 0, "label_name": "vulnerable"} -{"code": " function searchByModelForm() {\n // get the search terms\n $terms = expString::escape($this->params['search_string']);\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "var O=mxText.prototype.redraw;mxText.prototype.redraw=function(){O.apply(this,arguments);null!=this.node&&\"DIV\"==this.node.nodeName&&Graph.processFontAttributes(this.node)};Graph.prototype.createTagsDialog=function(t,E,K){function T(){for(var ma=S.getSelectionCells(),Aa=[],Da=0;DaisAdmin()) {\n expHistory::back();\n } else {\n foreach ($user->groups as $g) {\n if (!empty($g->redirect)) {\n $url = URL_FULL.$g->redirect;\n break;\n }\n }\n if (isset($url)) {\n header(\"Location: \".$url);\n } else {\n expHistory::back();\n }\n }\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public void translate(ServerExplosionPacket packet, GeyserSession session) {\n for (ExplodedBlockRecord record : packet.getExploded()) {\n Vector3f pos = Vector3f.from(packet.getX() + record.getX(), packet.getY() + record.getY(), packet.getZ() + record.getZ());\n ChunkUtils.updateBlock(session, BlockStateValues.JAVA_AIR_ID, pos.toInt());\n }\n\n Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n // Since bedrock does not play an explosion sound and particles sound, we have to manually do so\n LevelEventPacket levelEventPacket = new LevelEventPacket();\n levelEventPacket.setType(packet.getRadius() >= 2.0f ? LevelEventType.PARTICLE_HUGE_EXPLODE : LevelEventType.PARTICLE_EXPLOSION);\n levelEventPacket.setData(0);\n levelEventPacket.setPosition(pos.toFloat());\n session.sendUpstreamPacket(levelEventPacket);\n\n LevelSoundEventPacket levelSoundEventPacket = new LevelSoundEventPacket();\n levelSoundEventPacket.setRelativeVolumeDisabled(false);\n levelSoundEventPacket.setBabySound(false);\n levelSoundEventPacket.setExtraData(-1);\n levelSoundEventPacket.setSound(SoundEvent.EXPLODE);\n levelSoundEventPacket.setIdentifier(\":\");\n levelSoundEventPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));\n session.sendUpstreamPacket(levelSoundEventPacket);\n\n if (packet.getPushX() > 0f || packet.getPushY() > 0f || packet.getPushZ() > 0f) {\n SetEntityMotionPacket motionPacket = new SetEntityMotionPacket();\n motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());\n motionPacket.setMotion(Vector3f.from(packet.getPushX(), packet.getPushY(), packet.getPushZ()));\n session.sendUpstreamPacket(motionPacket);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function IsMail() {\n $this->Mailer = 'mail';\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function(u,D,K,T){for(var N=0;NcheckCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->enable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " private static function restoreIniSettings () {\n foreach (self::$_savedIniSettings as $setting => $val) { \n if ($val !== null) { \n ini_set ($setting, $val);\n }\n }\n }", "label": 1, "label_name": "safe"} -{"code": " const res = (result) => {\n let val = '';\n if (!pattern || ((typeof pattern !== 'object') && (typeof pattern !== 'string') && typeof pattern !== 'function')) {\n val = String(pattern);\n } else if (pattern.constructor === JpvObject) {\n val = `operator \"${pattern.type}\": ${JSON.stringify(pattern.value)}`;\n } else {\n JSON.stringify(pattern);\n }\n\n if (typeof pattern === 'function') {\n val = pattern.toString();\n }\n if (!result && options && options.debug) {\n options.logger(`error - the value of: {${options.deepLog.join('.')}: ` +\n `${String(value)}} not matched with: ${val}`);\n }\n return result;\n };", "label": 1, "label_name": "safe"} -{"code": "static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)\n{\n struct ipddp_route __user *rt = ifr->ifr_data;\n struct ipddp_route rcp, rcp2, *rp;\n\n if(!capable(CAP_NET_ADMIN))\n return -EPERM;\n\n\tif(copy_from_user(&rcp, rt, sizeof(rcp)))\n\t\treturn -EFAULT;\n\n switch(cmd)\n {\n\t\tcase SIOCADDIPDDPRT:\n return ipddp_create(&rcp);\n\n case SIOCFINDIPDDPRT:\n\t\t\tspin_lock_bh(&ipddp_route_lock);\n\t\t\trp = __ipddp_find_route(&rcp);\n\t\t\tif (rp)\n\t\t\t\tmemcpy(&rcp2, rp, sizeof(rcp2));\n\t\t\tspin_unlock_bh(&ipddp_route_lock);\n\n\t\t\tif (rp) {\n\t\t\t\tif (copy_to_user(rt, &rcp2,\n\t\t\t\t\t\t sizeof(struct ipddp_route)))\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\treturn 0;\n\t\t\t} else\n\t\t\t\treturn -ENOENT;\n\n case SIOCDELIPDDPRT:\n return ipddp_delete(&rcp);\n\n default:\n return -EINVAL;\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "test_compare_files (const char* tgt, const char *rec)\n{\n FILE *orig, *recons;\n static uint8_t obuf[TESTBUFSIZE], rbuf[TESTBUFSIZE];\n xoff_t offset = 0;\n size_t i;\n size_t oc, rc;\n xoff_t diffs = 0;\n\n if ((orig = fopen (tgt, \"r\")) == NULL)\n {\n XPR(NT \"open %s failed\\n\", tgt);\n return get_errno ();\n }\n\n if ((recons = fopen (rec, \"r\")) == NULL)\n {\n XPR(NT \"open %s failed\\n\", rec);\n return get_errno ();\n }\n\n for (;;)\n {\n oc = fread (obuf, 1, TESTBUFSIZE, orig);\n rc = fread (rbuf, 1, TESTBUFSIZE, recons);\n\n if (oc != rc)\n\t{\n\t return XD3_INTERNAL;\n\t}\n\n if (oc == 0)\n\t{\n\t break;\n\t}\n\n for (i = 0; i < oc; i += 1)\n\t{\n\t if (obuf[i] != rbuf[i])\n \t {\n\t XPR(NT \"byte %u (read %u @ %\"Q\"u) %d != %d\\n\", \n\t\t (int)i, (int)oc, offset, obuf[i], rbuf[i]);\n\t diffs++;\n\t return XD3_INTERNAL;\n\t }\n\t}\n\n offset += oc;\n }\n\n fclose (orig);\n fclose (recons);\n if (diffs != 0) \n {\n\treturn XD3_INTERNAL;\n }\n return 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testWrapInlineElements()\n {\n $this->assertResult(\n '

Do not

'.'Wrap',\n '

Do not

Wrap

'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " function removeUser($username)\n {\n $this->log('Auth_Container::removeUser() called.', AUTH_LOG_DEBUG);\n return AUTH_METHOD_NOT_SUPPORTED;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "var b=a.getHead();if(b.getCustomData(\"stylesheet\")){var c=a.getCustomData(\"stylesheet_ref\");if(--c)a.setCustomData(\"stylesheet_ref\",c);else{a.removeCustomData(\"stylesheet_ref\");b.removeCustomData(\"stylesheet\").remove()}}this.editor.fire(\"contentDomUnload\");delete this.editor}}});CKEDITOR.editor.prototype.editable=function(a){var b=this._.editable;if(b&&a)return 0;if(arguments.length)b=this._.editable=a?a instanceof CKEDITOR.editable?a:new CKEDITOR.editable(this,a):(b&&b.detach(),null);return b};var j=", "label": 1, "label_name": "safe"} -{"code": " private ModelAndView addGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { \n \n String groupName = request.getParameter(\"groupName\");\n String groupComment = request.getParameter(\"groupComment\");\n if (groupComment == null) {\n groupComment = \"\";\n }\n\n if (groupName != null && groupName.matches(\".*[&<>\\\"`']+.*\")) {\n throw new ServletException(\"Group ID must not contain any HTML markup.\");\n }\n\n if (groupComment != null && groupComment.matches(\".*[&<>\\\"`']+.*\")) {\n throw new ServletException(\"Group comment must not contain any HTML markup.\");\n }\n\n boolean hasGroup = false;\n try {\n hasGroup = m_groupRepository.groupExists(groupName);\n } catch (Throwable e) {\n throw new ServletException(\"Can't determine if group \" + groupName + \" already exists in groups.xml.\", e);\n }\n \n if (hasGroup) {\n return new ModelAndView(\"admin/userGroupView/groups/newGroup\", \"action\", \"redo\"); \n } else {\n WebGroup newGroup = new WebGroup();\n newGroup.setName(groupName);\n newGroup.setComments(groupComment);\n \n return editGroup(request, newGroup);\n }\n }", "label": 1, "label_name": "safe"} -{"code": " def test_list_entrance_exam_instructor_with_invalid_exam_key(self):\n \"\"\" Test list task history for entrance exam failure if course has invalid exam. \"\"\"\n url = reverse('list_entrance_exam_instructor_tasks',\n kwargs={'course_id': unicode(self.course_with_invalid_ee.id)})\n response = self.client.post(url, {\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 400)", "label": 1, "label_name": "safe"} -{"code": " def test_attr_wrapper\n assert_equal(\"

\\n\", render(\"%p{ :strange => 'attrs'}\", :attr_wrapper => '*'))\n assert_equal(\"

\\n\", render(\"%p{ :escaped => 'quo\\\"te'}\", :attr_wrapper => '\"'))\n assert_equal(\"

\\n\", render(\"%p{ :escaped => 'quo\\\\'te'}\", :attr_wrapper => '\"'))\n assert_equal(\"

\\n\", render(\"%p{ :escaped => 'q\\\\'uo\\\"te'}\", :attr_wrapper => '\"'))\n assert_equal(\"\\n\", render(\"!!! XML\", :attr_wrapper => '\"', :format => :xhtml))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it \"removes the stored credentials\" do\n cluster.logout :admin\n cluster.auth.should be_empty\n end", "label": 0, "label_name": "vulnerable"} -{"code": "\tprotected function _mkdir($path, $name) {\n\t\t$path = $this->_joinPath($path, $name);\n\t\tif (ftp_mkdir($this->connect, $path) === false) {\n\t\t\treturn false;\n\t\t} \n\t\t\n\t\t$this->options['dirMode'] && @ftp_chmod($this->connect, $this->options['dirMode'], $path);\n\t\treturn $path;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static List GetChildProcesses(this Process process)\r\n {\r\n try\r\n {\r\n var mos = new ManagementObjectSearcher(\r\n $\"Select * From Win32_Process Where ParentProcessID={process.Id}\");\r\n return (from ManagementObject mo in mos.Get()\r\n select Process.GetProcessById(Convert.ToInt32(mo[\"ProcessID\"]))).ToList();\r\n }\r\n catch (Exception)\r\n {\r\n return null;\r\n }\r\n }\r", "label": 1, "label_name": "safe"} -{"code": " it \"should exist\" do\n expect(Puppet::Parser::Functions.function(\"shuffle\")).to eq(\"function_shuffle\")\n end", "label": 0, "label_name": "vulnerable"} -{"code": "a.type==CKEDITOR.NODE_ELEMENT&&a.$}function p(a){if(!m(a))return!1;var c;if(!(c=X(a)))m(a)?(c={left:1,right:1,center:1},c=!(!c[a.getComputedStyle(\"float\")]&&!c[a.getAttribute(\"align\")])):c=!1;return c}function X(a){return!!{absolute:1,fixed:1}[a.getComputedStyle(\"position\")]}function G(a,c){return m(c)?c.is(a.triggers):null}function W(a,c){if(!c)return!1;for(var d=c.getParents(1),b=d.length;b--;)for(var e=a.tabuList.length;e--;)if(d[b].hasAttribute(a.tabuList[e]))return!0;return!1}function ja(a,c,\nd){c=c[d?\"getLast\":\"getFirst\"](function(b){return a.isRelevant(b)&&!b.is(ka)});if(!c)return!1;o(a,c);return d?c.size.top>a.mouse.y:c.size.bottom(a.inInlineMode?b.editable.top+b.editable.height/2:Math.min(b.editable.height,b.pane.height)/2),c=c[f?\"getLast\":\"getFirst\"](function(a){return!(z(a)||A(a))});if(!c)return null;v(a,c)&&(c=a.line.wrap[f?\"getPrevious\":\"getNext\"](function(a){return!(z(a)||A(a))}));if(!m(c)||", "label": 1, "label_name": "safe"} -{"code": "null!=na){ca=ia.getAttribute(\"section\");aa=ia.getAttribute(\"subsection\");if(null==ca&&(la=na.indexOf(\"/\"),ca=na.substring(0,la),null==aa)){var qa=na.indexOf(\"/\",la+1);-1loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\n\t\t$gc = new geoCountry();\n $countries = $gc->find('all');\n\n $gr = new geoRegion();\n $regions = $gr->find('all',null,'rank asc,name asc');\n assign_to_template(array(\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''\n ));\n\t }", "label": 1, "label_name": "safe"} -{"code": " public function testDestroy()\n {\n $collection = $this->createMongoCollectionMock();\n\n $this->mongo->expects($this->once())\n ->method('selectCollection')\n ->with($this->options['database'], $this->options['collection'])\n ->will($this->returnValue($collection));\n\n $collection->expects($this->once())\n ->method('remove')\n ->with(array($this->options['id_field'] => 'foo'));\n\n $this->assertTrue($this->storage->destroy('foo'));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static function muteErrorHandler()\n {\n }", "label": 1, "label_name": "safe"} -{"code": "def job_log(request, client_id, project_name, spider_name, job_id):\n \"\"\"\n get log of jog\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :param spider_name: spider name\n :param job_id: job id\n :return: log of job\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n # get log url\n url = log_url(client.ip, client.port, project_name, spider_name, job_id)\n try:\n # get last 1000 bytes of log\n response = requests.get(url, timeout=5, headers={\n 'Range': 'bytes=-1000'\n }, auth=(client.username, client.password) if client.auth else None)\n # Get encoding\n encoding = response.apparent_encoding\n # log not found\n if response.status_code == 404:\n return JsonResponse({'message': 'Log Not Found'}, status=404)\n # bytes to string\n text = response.content.decode(encoding, errors='replace')\n return HttpResponse(text)\n except requests.ConnectionError:\n return JsonResponse({'message': 'Load Log Error'}, status=500)", "label": 0, "label_name": "vulnerable"} -{"code": "R=0;Rschemes[$scheme] = $scheme_obj;\n }", "label": 1, "label_name": "safe"} -{"code": "module.exports = async function(path) {\n\tif (!path || typeof path !== 'string') {\n\t\tthrow new TypeError(`string was expected, instead got ${path}`);\n\t}\n\n\tconst absolute = resolve(path);\n\n\tif (!(await exist(absolute))) {\n\t\tthrow new Error(`Could not find file at path \"${absolute}\"`);\n\t}\n\n\tconst ts = await spawn(`log -1 --format=\"%at\" -- ${path}`);\n\n\treturn new Date(Number(ts) * 1000);\n};", "label": 1, "label_name": "safe"} -{"code": "def has_normalized!(hash, key)\n return true if hash.has_key?( key )\n return false unless key.match(/-|_/)\n other_key = key.include?('-') ? key.gsub( '-', '_' ) : key.gsub( '_', '-' )\n return false unless hash.has_key?( other_key )\n hash[key] = hash.delete( other_key )\n return true;\nend", "label": 0, "label_name": "vulnerable"} -{"code": " public function testKeepValidData()\n {\n $this->assertResult(\n '',\n ''\n );\n }", "label": 1, "label_name": "safe"} -{"code": "\"plantUmlData\",JSON.stringify({data:F,format:K.format}))}finally{g.getModel().endUpdate()}},function(H){d.handleError(H)})},null,null,400,220);d.showDialog(G.container,420,300,!0,!0);G.init()};g.cellEditor.editMermaidData=function(D,G,P){var K=JSON.parse(P);G=new TextareaDialog(d,mxResources.get(\"mermaid\")+\":\",K.data,function(F){null!=F&&d.spinner.spin(document.body,mxResources.get(\"inserting\"))&&d.generateMermaidImage(F,K.config,function(H,S,V){d.spinner.stop();g.getModel().beginUpdate();try{g.setCellStyles(\"image\",", "label": 0, "label_name": "vulnerable"} -{"code": " def test_list_email_content_error(self, task_history_request):\n \"\"\" Test handling of error retrieving email \"\"\"\n invalid_task = FakeContentTask(0, 0, 0, 'test')\n invalid_task.make_invalid_input()\n task_history_request.return_value = [invalid_task]\n url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {})\n self.assertEqual(response.status_code, 200)\n\n self.assertTrue(task_history_request.called)\n returned_email_info = json.loads(response.content)['emails']\n self.assertEqual(len(returned_email_info), 1)\n returned_info = returned_email_info[0]\n for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']:\n self.assertEqual(returned_info[info], None)", "label": 0, "label_name": "vulnerable"} -{"code": "int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)\n{\n\tunsigned int 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\t\tunsigned int len;\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\tlen = ipv6_optlen(exthdr);\n\t\tif (len + offset >= IPV6_MAXPLEN)\n\t\t\treturn -EINVAL;\n\t\toffset += len;\n\t\t*nexthdr = &exthdr->nexthdr;\n\t}\n\n\treturn -EINVAL;\n}", "label": 1, "label_name": "safe"} -{"code": "ikev1_attrmap_print(netdissect_options *ndo,\n\t\t const u_char *p, const u_char *ep,\n\t\t const struct attrmap *map, size_t nmap)\n{\n\tint totlen;\n\tuint32_t t, v;\n\n\tif (p[0] & 0x80)\n\t\ttotlen = 4;\n\telse\n\t\ttotlen = 4 + EXTRACT_16BITS(&p[2]);\n\tif (ep < p + totlen) {\n\t\tND_PRINT((ndo,\"[|attr]\"));\n\t\treturn ep + 1;\n\t}\n\n\tND_PRINT((ndo,\"(\"));\n\tt = EXTRACT_16BITS(&p[0]) & 0x7fff;\n\tif (map && t < nmap && map[t].type)\n\t\tND_PRINT((ndo,\"type=%s \", map[t].type));\n\telse\n\t\tND_PRINT((ndo,\"type=#%d \", t));\n\tif (p[0] & 0x80) {\n\t\tND_PRINT((ndo,\"value=\"));\n\t\tv = EXTRACT_16BITS(&p[2]);\n\t\tif (map && t < nmap && v < map[t].nvalue && map[t].value[v])\n\t\t\tND_PRINT((ndo,\"%s\", map[t].value[v]));\n\t\telse\n\t\t\trawprint(ndo, (const uint8_t *)&p[2], 2);\n\t} else {\n\t\tND_PRINT((ndo,\"len=%d value=\", EXTRACT_16BITS(&p[2])));\n\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));\n\t}\n\tND_PRINT((ndo,\")\"));\n\treturn p + totlen;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static char* get_private_subtags(const char* loc_name)\n{\n\tchar* \tresult =NULL;\n\tint \tsingletonPos = 0;\n\tint \tlen =0; \n\tconst char* \tmod_loc_name =NULL;\n\n\tif( loc_name && (len = strlen(loc_name)>0 ) ){\n\t\tmod_loc_name = loc_name ; \n\t\tlen = strlen(mod_loc_name);\n\t\twhile( (singletonPos = getSingletonPos(mod_loc_name))!= -1){\n\n\t\t\tif( singletonPos!=-1){ \n\t\t\t\tif( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){\t\t\n\t\t\t\t\t/* private subtag start found */\n\t\t\t\t\tif( singletonPos + 2 == len){\n\t\t\t\t\t\t/* loc_name ends with '-x-' ; return NULL */\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\t/* result = mod_loc_name + singletonPos +2; */\n\t\t\t\t\t\tresult = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) );\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif( singletonPos + 1 >= len){\n\t\t\t\t\t\t/* String end */\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* singleton found but not a private subtag , hence check further in the string for the private subtag */\n\t\t\t\t\t\tmod_loc_name = mod_loc_name + singletonPos +1;\n\t\t\t\t\t\tlen = strlen(mod_loc_name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} /* end of while */\n\t}\n\t\n\treturn result;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "Ja);null==C&&(K(ca),n(Pa,\"geTempDlgDiagramTileActive\",fa[qa]));Ra=document.createElement(\"div\");Ra.className=\"geTempDlgDiagramTileImg geTempDlgDiagramTileImgLoading\";var Qa=document.createElement(\"img\");Qa.style.display=\"none\";(function(La,Ta,Ua){Qa.onload=function(){Ta.className=\"geTempDlgDiagramTileImg\";La.style.display=\"\"};Qa.onerror=function(){this.src!=Ua?this.src=Ua:Ta.className=\"geTempDlgDiagramTileImg geTempDlgDiagramTileImgError\"}})(Qa,Ra,Ga?Ga.replace(\".drawio.xml\",\"\").replace(\".drawio\",", "label": 1, "label_name": "safe"} -{"code": " public function __construct($arguments)\n {\n $this->arguments = $arguments;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d);\n // compare the given digest to the decrypted one\n return digest === obj.value[1].value;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected function generateVerifyCode()\n {\n if ($this->minLength > $this->maxLength) {\n $this->maxLength = $this->minLength;\n }\n if ($this->minLength < 3) {\n $this->minLength = 3;\n }\n if ($this->maxLength > 20) {\n $this->maxLength = 20;\n }\n $length = mt_rand($this->minLength, $this->maxLength);\n\n $letters = 'bcdfghjklmnpqrstvwxyz';\n $vowels = 'aeiou';\n $code = '';\n for ($i = 0; $i < $length; ++$i) {\n if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {\n $code .= $vowels[mt_rand(0, 4)];\n } else {\n $code .= $letters[mt_rand(0, 20)];\n }\n }\n\n return $code;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tprivate static async Task ResponseRedeem(EAccess access, string botNames, string keysText, ulong steamID = 0, ERedeemFlags redeemFlags = ERedeemFlags.None) {\n\t\tif (!Enum.IsDefined(access)) {\n\t\t\tthrow new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(botNames)) {\n\t\t\tthrow new ArgumentNullException(nameof(botNames));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(keysText)) {\n\t\t\tthrow new ArgumentNullException(nameof(keysText));\n\t\t}\n\n\t\tHashSet? bots = Bot.GetBots(botNames);\n\n\t\tif ((bots == null) || (bots.Count == 0)) {\n\t\t\treturn access >= EAccess.Owner ? FormatStaticResponse(string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)) : null;\n\t\t}\n\n\t\tIList results = await Utilities.InParallel(bots.Select(bot => bot.Commands.ResponseRedeem(access, keysText, steamID, redeemFlags))).ConfigureAwait(false);\n\n\t\tList responses = new(results.Where(static result => !string.IsNullOrEmpty(result))!);\n\n\t\treturn responses.Count > 0 ? string.Join(Environment.NewLine, responses) : null;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic static function loadFromInfo($fileInfo)\n\t{\n\t\t$instance = new self();\n\t\tforeach ($fileInfo as $key => $value) {\n\t\t\t$instance->{$key} = $fileInfo[$key];\n\t\t}\n\t\tif (isset($instance->name)) {\n\t\t\t$instance->name = trim(\\App\\Purifier::purify($instance->name));\n\t\t}\n\t\treturn $instance;\n\t}", "label": 1, "label_name": "safe"} -{"code": "r=g.isEventsEnabled();g.setEventsEnabled(!1);var q=this.graph.isEnabled();this.graph.setEnabled(!1);var t=g.getTranslate();g.translate=new mxPoint(a,b);var u=this.graph.cellRenderer.redraw,x=g.states;a=g.scale;if(this.clipping){var A=new mxRectangle((f.x+t.x)*a,(f.y+t.y)*a,f.width*a/p,f.height*a/p),E=this;this.graph.cellRenderer.redraw=function(D,B,v){if(null!=D){var y=x.get(D.cell);if(null!=y&&(y=g.getBoundingBox(y,!1),null!=y&&0consumerKey;\n $tokens = $this->getToken();\n if (isset($tokens['token']) && $tokens['token']) {\n $params['oauth_token'] = $tokens['token'];\n }\n $params['oauth_timestamp'] = time();\n $params['oauth_nonce'] = md5(microtime() . mt_rand());\n return $params;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)\n{\n PyObject *fnames, *result;\n int i;\n fnames = PyTuple_New(num_fields);\n if (!fnames) return NULL;\n for (i = 0; i < num_fields; i++) {\n PyObject *field = PyUnicode_FromString(fields[i]);\n if (!field) {\n Py_DECREF(fnames);\n return NULL;\n }\n PyTuple_SET_ITEM(fnames, i, field);\n }\n result = PyObject_CallFunction((PyObject*)&PyType_Type, \"s(O){sOss}\",\n type, base, \"_fields\", fnames, \"__module__\", \"_ast3\");\n Py_DECREF(fnames);\n return (PyTypeObject*)result;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def _create(self):\n url = urljoin(recurly.base_uri(), self.collection_path)\n return self.post(url)", "label": 0, "label_name": "vulnerable"} -{"code": "def feed_categoryindex():\n return render_element_index(db.Tags.name, db.books_tags_link, 'opds.feed_letter_category')", "label": 1, "label_name": "safe"} -{"code": "func (err ErrInvalidCloneAddr) Error() string {\n\treturn fmt.Sprintf(\"invalid clone address [is_url_error: %v, is_invalid_path: %v, is_permission_denied: %v, is_blocked_local_address: %v]\",\n\t\terr.IsURLError, err.IsInvalidPath, err.IsPermissionDenied, err.IsBlockedLocalAddress)\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "Array.prototype.push.apply(P.shape.customProperties,Editor.commonEdgeProperties)),T(P.shape.customProperties));p=p.getAttribute(\"customProperties\");if(null!=p)try{T(JSON.parse(p))}catch(O){}}};var v=StyleFormatPanel.prototype.init;StyleFormatPanel.prototype.init=function(){var p=this.editorUi.getSelectionState();\"image\"!=p.style.shape&&!p.containsLabel&&0escapeHtml($item[1]));\n } elseif ('null' === $item[0]) {", "label": 0, "label_name": "vulnerable"} -{"code": "v.apply(this,arguments)};m.getLinkForCell=function(){return null};var x=m.view.getState(q);k=m.getAllConnectionConstraints(x);for(var A=0;null!=k&&A {\n clientCfg.host = 'localhost';\n clientCfg.port = server.address().port;\n client.connect(clientCfg);\n }));\n\n server.on('connection', mustCall((conn) => {\n conn.on('authentication', mustCall((ctx) => {\n ctx.accept();\n })).on('ready', onReady);\n })).on('close', onClose);\n client.on('ready', mustCall(() => {\n onReady();\n if (reconnect) {\n client.end();\n } else {\n reconnect = true;\n client.connect(clientCfg);\n }\n })).on('close', onClose);\n }),", "label": 1, "label_name": "safe"} -{"code": "\tprivate UStroke getStroke(Style style) {\n\t\treturn style.getStroke();\n\t}", "label": 1, "label_name": "safe"} -{"code": " function update_optiongroup_master() {\n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $og = new optiongroup_master($id);\n $oldtitle = $og->title;\n $og->update($this->params);\n\n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $og->title) {\n $db->sql('UPDATE '.$db->prefix.'optiongroup SET title=\"'.$og->title.'\" WHERE title=\"'.$oldtitle.'\"');\n }\n\n expHistory::back();\n }", "label": 1, "label_name": "safe"} -{"code": "void AnnotatePCQGet(const char *file, int line,\n const volatile void *pcq){}", "label": 0, "label_name": "vulnerable"} -{"code": " public String accessToken(String username) {\n Algorithm algorithm = Algorithm.HMAC256(SECRET);\n\n return JWT.create()\n .withExpiresAt(new Date(new Date().getTime() + ACCESS_EXPIRE_TIME))\n .withIssuer(ISSUER)\n .withClaim(\"username\", username)\n .sign(algorithm);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);\r\n if (!$view) {\r\n// unset($navs[$i]); //FIXME this breaks jstree if we remove a parent and not the child\r\n $attr = new stdClass();\r\n $attr->class = 'hidden'; // bs3 class to hide elements\r\n $navs[$i]->li_attr = $attr;\r\n }\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "\tthis.exec = function(hashes) {\n\t\tvar fm = this.fm,\n\t\t\tbase = fm.options.url,\n\t\t\tfiles = filter(hashes),\n\t\t\tdfrd = $.Deferred(),\n\t\t\tiframes = '',\n\t\t\tcdata = '',\n\t\t\ti, url;\n\t\t\t\n\t\tif (this.disabled()) {\n\t\t\treturn dfrd.reject();\n\t\t}\n\t\t\t\n\t\tif (fm.oldAPI) {\n\t\t\tfm.error('errCmdNoSupport');\n\t\t\treturn dfrd.reject();\n\t\t}\n\t\t\n\t\tcdata = $.param(fm.options.customData || {});\n\t\tif (cdata) {\n\t\t\tcdata = '&' + cdata;\n\t\t}\n\t\t\n\t\tbase += base.indexOf('?') === -1 ? '?' : '&';\n\t\t\n\t\tfor (i = 0; i < files.length; i++) {\n\t\t\tiframes += '');return b.join(\"\")})}},fileButton:function(b,a,d){if(!(3>arguments.length)){i.call(this,a);var e=this;a.validate&&(this.validate=a.validate);var c=CKEDITOR.tools.extend({},a),f=c.onClick;c.className=(c.className?c.className+\" \":\"\")+\"cke_dialog_ui_button\";c.onClick=function(c){var d=\na[\"for\"];if(!f||f.call(this,c)!==false){b.getContentElement(d[0],d[1]).submit();this.disable()}};b.on(\"load\",function(){b.getContentElement(a[\"for\"][0],a[\"for\"][1])._.buttons.push(e)});CKEDITOR.ui.dialog.button.call(this,b,c,d)}},html:function(){var b=/^\\s*<[\\w:]+\\s+([^>]*)?>/,a=/^(\\s*<[\\w:]+(?:\\s+[^>]*)?)((?:.|\\r|\\n)+)$/,d=/\\/$/;return function(e,c,f){if(!(3>arguments.length)){var h=[],g=c.html;\"<\"!=g.charAt(0)&&(g=\"\"+g+\"\");var k=c.focus;if(k){var j=this.focus;this.focus=function(){(\"function\"==", "label": 1, "label_name": "safe"} -{"code": " foreach ($allowedFolders as $folder) {\n if ('/' . $folder === substr($uri, 0, 1 + strlen($folder))) {\n header('Content-Type: ' . $this->getMime($filePath));\n readfile($filePath);\n return true;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "parse_memory(VALUE klass, VALUE data, VALUE encoding)\n{\n htmlParserCtxtPtr ctxt;\n\n if (NIL_P(data)) {\n rb_raise(rb_eArgError, \"data cannot be nil\");\n }\n if (!(int)RSTRING_LEN(data)) {\n rb_raise(rb_eRuntimeError, \"data cannot be empty\");\n }\n\n ctxt = htmlCreateMemoryParserCtxt(StringValuePtr(data),\n (int)RSTRING_LEN(data));\n if (ctxt->sax) {\n xmlFree(ctxt->sax);\n ctxt->sax = NULL;\n }\n\n if (RTEST(encoding)) {\n xmlCharEncodingHandlerPtr enc = xmlFindCharEncodingHandler(StringValueCStr(encoding));\n if (enc != NULL) {\n xmlSwitchToEncoding(ctxt, enc);\n if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {\n rb_raise(rb_eRuntimeError, \"Unsupported encoding %s\",\n StringValueCStr(encoding));\n }\n }\n }\n\n return Data_Wrap_Struct(klass, NULL, deallocate, ctxt);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "action:\"size_\"+file.size})}catch(m){}};EditorUi.prototype.isResampleImageSize=function(c,e){e=null!=e?e:this.resampleThreshold;return c>e};EditorUi.prototype.resizeImage=function(c,e,g,k,m,q,v){m=null!=m?m:this.maxImageSize;var x=Math.max(1,c.width),A=Math.max(1,c.height);if(k&&this.isResampleImageSize(null!=v?v:e.length,q))try{var z=Math.max(x/m,A/m);if(1repeat = true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testRemoveCurlAuthorizationOptionsOnRedirectCrossPort($auth)\n {\n if (!defined('\\CURLOPT_HTTPAUTH')) {\n self::markTestSkipped('ext-curl is required for this test');\n }\n\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://example.com:81/']),\n static function (RequestInterface $request, $options) {\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_HTTPAUTH]),\n 'curl options still contain CURLOPT_HTTPAUTH entry'\n );\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_USERPWD]),\n 'curl options still contain CURLOPT_USERPWD entry'\n );\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);\n }", "label": 1, "label_name": "safe"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "l,x,p,v){l=Math.min(p,v/2);c.moveTo(0,0);c.lineTo(p-l,0);c.quadTo(p,0,p,v/2);c.quadTo(p,v,p-l,v);c.lineTo(0,v);c.close();c.end()};mxCellRenderer.registerShape(\"delay\",Ta);mxUtils.extend(za,mxActor);za.prototype.size=.2;za.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(v,p);var A=Math.max(0,Math.min(l,l*parseFloat(mxUtils.getValue(this.style,\"size\",this.size))));l=(v-A)/2;x=l+A;var B=(p-A)/2;A=B+A;c.moveTo(0,l);c.lineTo(B,l);c.lineTo(B,0);c.lineTo(A,0);c.lineTo(A,l);c.lineTo(p,l);c.lineTo(p,x);\nc.lineTo(A,x);c.lineTo(A,v);c.lineTo(B,v);c.lineTo(B,x);c.lineTo(0,x);c.close();c.end()};mxCellRenderer.registerShape(\"cross\",za);mxUtils.extend(wa,mxActor);wa.prototype.size=.25;wa.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(p,v/2);x=Math.min(p-l,Math.max(0,parseFloat(mxUtils.getValue(this.style,\"size\",this.size)))*p);c.moveTo(0,v/2);c.lineTo(x,0);c.lineTo(p-l,0);c.quadTo(p,0,p,v/2);c.quadTo(p,v,p-l,v);c.lineTo(x,v);c.close();c.end()};mxCellRenderer.registerShape(\"display\",wa);mxUtils.extend(Ea,", "label": 0, "label_name": "vulnerable"} -{"code": "png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length)\n{\n png_alloc_size_t limit = PNG_UINT_31_MAX;\n\n# ifdef PNG_SET_USER_LIMITS_SUPPORTED\n if (png_ptr->user_chunk_malloc_max > 0 &&\n png_ptr->user_chunk_malloc_max < limit)\n limit = png_ptr->user_chunk_malloc_max;\n# elif PNG_USER_CHUNK_MALLOC_MAX > 0\n if (PNG_USER_CHUNK_MALLOC_MAX < limit)\n limit = PNG_USER_CHUNK_MALLOC_MAX;\n# endif\n if (png_ptr->chunk_name == png_IDAT)\n {\n png_alloc_size_t idat_limit = PNG_UINT_31_MAX;\n size_t row_factor =\n (size_t)png_ptr->width\n * (size_t)png_ptr->channels\n * (png_ptr->bit_depth > 8? 2: 1)\n + 1\n + (png_ptr->interlaced? 6: 0);\n if (png_ptr->height > PNG_UINT_32_MAX/row_factor)\n idat_limit = PNG_UINT_31_MAX;\n else\n idat_limit = png_ptr->height * row_factor;\n row_factor = row_factor > 32566? 32566 : row_factor;\n idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */\n idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX;\n limit = limit < idat_limit? idat_limit : limit;\n }\n\n if (length > limit)\n {\n png_debug2(0,\" length = %lu, limit = %lu\",\n (unsigned long)length,(unsigned long)limit);\n png_chunk_error(png_ptr, \"chunk data is too large\");\n }\n}", "label": 1, "label_name": "safe"} -{"code": "mcs_parse_domain_params(STREAM s)\n{\n\tuint32 length;\n\tstruct stream packet = *s;\n\n\tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n\n\tif (!s_check_rem(s, length))\n\t{\n\t\trdp_protocol_error(\"mcs_parse_domain_params(), consume domain params from stream would overrun\", &packet);\n\t}\n\n\tin_uint8s(s, length);\n\n\treturn s_check(s);\n}", "label": 1, "label_name": "safe"} -{"code": " public void failingExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new FailingExample())))\n .containsExactlyInAnyOrder(FAILED_RESULT);\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def wf_issue\n Log.add_info(request, params.inspect)\n\n begin\n @item = Item.find(params[:id])\n @workflow = @item.workflow\n rescue => evar\n Log.add_error(request, evar)\n end\n \n attrs = ActionController::Parameters.new({status: Workflow::STATUS_ACTIVE, issued_at: Time.now})\n @workflow.update_attributes(attrs.permit(Workflow::PERMIT_BASE))\n\n @orders = @workflow.get_orders\n\n render(:partial => 'ajax_workflow', :layout => false)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " success:function(data){\n if (data === 'failure') return;\n lastEventId=data[0];\n if(data[1]){\n var text=data[1];\n if($(\"#activity-feed .items .empty\").html()){\n $(\"#activity-feed .items\").html(\n \"
\");\n }\n if($(\"#new-events\").is(\":hidden\")){\n $(\"#new-events\").show();\n }\n $.each($(\".list-view\"), function(){\n if(typeof $.fn.yiiListView.settings[\"'\"+$(this).attr(\"id\")+\"'\"] ===\n \"undefined\")\n $(this).yiiListView();\n });\n that.DEBUG && console.log ('hiding ' + text);\n $newElem = $(text).hide().prependTo(\"#new-events\");\n that.makePostExpandable ($newElem.find ('.event-text-box').children ('.event-text'));\n $newElem.fadeIn(1000);\n }\n if(data[2]){\n var comments=data[2];\n $.each(comments,function(key,value){\n $(\"#\"+key+\"-comment-count\").html(\"\"+value+\"\");\n });\n if(data[3]>lastEventId)\n lastEventId=data[3];\n if(data[4]>lastTimestamp)\n lastTimestamp=data[4];\n }\n var t=setTimeout(function(){updateFeed();},5000);\n }", "label": 1, "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, "label_name": "safe"} -{"code": " var sanitize_stylesheets = function (html, tagPolicy) {\n /**\n * sanitize just the css in style tags in a block of html\n * called by sanitize_html, if allow_css is true\n */\n var h = $(\"
\").append(html);\n var style_tags = h.find(\"style\");\n if (!style_tags.length) {\n // no style tags to sanitize\n return html;\n }\n style_tags.each(function(i, style) {\n style.innerHTML = sanitize_css(style.innerHTML, tagPolicy);\n });\n return h.html();\n };", "label": 0, "label_name": "vulnerable"} -{"code": "Ka=U.actions.get(\"zoomOut\"),bb=U.actions.get(\"resetView\");u=U.actions.get(\"fullscreen\");var Ua=U.actions.get(\"undo\"),$a=U.actions.get(\"redo\"),z=X(\"\",Ua.funct,null,mxResources.get(\"undo\")+\" (\"+Ua.shortcut+\")\",Ua,Editor.undoImage),L=X(\"\",$a.funct,null,mxResources.get(\"redo\")+\" (\"+$a.shortcut+\")\",$a,Editor.redoImage),M=X(\"\",u.funct,null,mxResources.get(\"fullscreen\"),u,Editor.fullscreenImage);if(null!=W){J=function(){ma.style.display=null!=U.pages&&(\"0\"!=urlParams.pages||1tfm);\n\tu8 *buf = dctx->buffer;\n\n\tif (!ctx->gf128)\n\t\treturn -ENOKEY;\n\n\tghash_flush(ctx, dctx);\n\tmemcpy(dst, buf, GHASH_BLOCK_SIZE);\n\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": "\tthis.update = function(s, v) {\n\t\tvar state = this.state,\n\t\t\tvalue = this.value;\n\n\t\tif (this._disabled) {\n\t\t\tthis.state = -1;\n\t\t} else {\n\t\t\tthis.state = s !== void(0) ? s : this.getstate();\n\t\t}\n\n\t\tthis.value = v;\n\t\t\n\t\tif (state != this.state || value != this.value) {\n\t\t\tthis.change();\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " private Path getFilePath(String path) {\n return baseDirPath.map(dir -> dir.resolve(path)).orElseGet(() -> Paths.get(path));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"raises an error if the first argument is not an array\" do\n expect {\n scope.function_suffix([Object.new])\n }.to raise_error(Puppet::ParseError, /expected first argument to be an Array/)\n end", "label": 0, "label_name": "vulnerable"} -{"code": "elFinder.prototype.commands.back = function() {\n\tthis.alwaysEnabled = true;\n\tthis.updateOnSelect = false;\n\tthis.shortcuts = [{\n\t\tpattern : 'ctrl+left backspace'\n\t}];\n\t\n\tthis.getstate = function() {\n\t\treturn this.fm.history.canBack() ? 0 : -1;\n\t}\n\t\n\tthis.exec = function() {\n\t\treturn this.fm.history.back();\n\t}\n\n}", "label": 0, "label_name": "vulnerable"} -{"code": "- (void) _filterComponent: (iCalEntityObject *) component\n{\n NSString *type, *summary, *tag;\n NSArray *children;\n\n int classification, i;\n\n type = @\"vtodo\";\n classification = 0;\n\n if ([component isKindOfClass: [iCalEvent class]])\n type = @\"vevent\";\n \n if ([component symbolicAccessClass] == iCalAccessPrivate)\n classification = 1;\n else if ([component symbolicAccessClass] == iCalAccessConfidential)\n classification = 2;\n\n summary = [self labelForKey: [NSString stringWithFormat: @\"%@_class%d\",\n type, classification]\n inContext: context];\n [component setSummary: summary];\n [component setComment: @\"\"];\n [component setUserComment: @\"\"];\n [component setLocation: @\"\"];\n [component setCategories: [NSArray array]];\n [component setUrl: @\"\"];\n [component setOrganizer: nil];\n [component removeAllAttendees];\n [component removeAllAlarms];\n\n // We strip all X- tags\n children = [component children];\n\n for (i = 0; i < [children count]; i++)\n {\n tag = [[children objectAtIndex: i] tag];\n if ([[tag uppercaseString] hasPrefix: @\"X-\"])\n [component removeChild: [children objectAtIndex: i]];\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "bool MemoryManager::validate_user_read(const Process& process, VirtualAddress vaddr) const\n{\n auto* region = region_from_vaddr(process, vaddr);\n return region && region->is_readable();\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function(){g({message:JSON.parse(n.result).Message})},n.readAsText(L.response))}catch(y){g({})}});L.send(v)}else try{this.doImportVisio(c,e,g,k)}catch(M){g(M)}}else this.spinner.stop(),this.handleError({message:mxResources.get(\"serviceUnavailableOrBlocked\")})});this.doImportVisio||this.loadingExtensions||this.isOffline(!0)?q():(this.loadingExtensions=!0,mxscript(\"js/extensions.min.js\",q))};EditorUi.prototype.importGraphML=function(c,e,g){g=null!=g?g:mxUtils.bind(this,function(m){this.handleError(m)});", "label": 0, "label_name": "vulnerable"} -{"code": "def _get_obj_absolute_path(obj_path):\n return os.path.join(DATAROOT, obj_path)", "label": 0, "label_name": "vulnerable"} -{"code": "J&&E(Editor.svgBrokenImage.src)});else{var N=new Image;this.crossOriginImages&&(N.crossOrigin=\"anonymous\");N.onload=function(){window.clearTimeout(T);if(J)try{var Q=document.createElement(\"canvas\"),R=Q.getContext(\"2d\");Q.height=N.height;Q.width=N.width;R.drawImage(N,0,0);E(Q.toDataURL())}catch(Y){E(Editor.svgBrokenImage.src)}};N.onerror=function(){window.clearTimeout(T);J&&E(Editor.svgBrokenImage.src)};N.src=u}}catch(Q){E(Editor.svgBrokenImage.src)}};Editor.prototype.convertImages=function(u,E,J,", "label": 0, "label_name": "vulnerable"} -{"code": "int ras_validate(jas_stream_t *in)\n{\n\tjas_uchar buf[RAS_MAGICLEN];\n\tint i;\n\tint n;\n\tuint_fast32_t magic;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\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\n\t/* Did we read enough data? */\n\tif (n < RAS_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\tmagic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |\n\t (JAS_CAST(uint_fast32_t, buf[1]) << 16) |\n\t (JAS_CAST(uint_fast32_t, buf[2]) << 8) |\n\t buf[3];\n\n\t/* Is the signature correct for the Sun Rasterfile format? */\n\tif (magic != RAS_MAGIC) {\n\t\treturn -1;\n\t}\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": " public function testRemoveJavaScriptWithEmbeddedLink()\n {\n // credits: NykO18\n $this->setBase('http://www.example.com/');\n $this->assertFiltering('javascript: window.location = \\'http://www.example.com\\';', false);\n }", "label": 1, "label_name": "safe"} -{"code": " protected function getSubtask()\n {\n $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));\n\n if (empty($subtask)) {\n throw new PageNotFoundException();\n }\n\n return $subtask;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tprotected void ShowHelp()\n\t\t{\n\t\t\tString helpText = ResourceHelper.GetHelpFileText(helpKey);\n\n\t\t\tif (helpText == String.Empty)\n\t\t\t{\n\t\t\t\thelpText = WebUser.IsAdminOrContentAdmin ?\n\t\t\t\t\tString.Format(Resource.HelpNoHelpAvailableAdminUser, helpKey) :\n\t\t\t\t\tResource.HelpNoHelpAvailable;\n\t\t\t}\n\n\t\t\tlitHelp.Text = helpText;\n\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testMungeIgnoreSameDomain()\n {\n $this->setMunge('http://example.com/%s');\n $this->assertFiltering('http://example.com/foobar');\n }", "label": 1, "label_name": "safe"} -{"code": " it 'should accept a replica set name' do\n @replset[:name].should == 'test'\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function checkForReassign($operator)\n {\n $operator_name = ($this->locale == get_home_locale())\n ? $operator['vclocalename']\n : $operator['vccommonname'];\n\n $is_operator_correct = $this->nextAgent == $operator['operatorid']\n || $this->agentId == $operator['operatorid'];\n\n if ($this->state == self::STATE_WAITING && $is_operator_correct) {\n // Prepare message\n if ($this->nextAgent == $operator['operatorid']) {\n $message_to_post = getlocal(\n \"Operator {0} changed operator {1}\",\n array($operator_name, $this->agentName),\n $this->locale,\n true\n );\n } else {\n $message_to_post = getlocal(\n \"Operator {0} is back\",\n array($operator_name),\n $this->locale,\n true\n );\n }\n\n // Update thread info\n $this->state = self::STATE_CHATTING;\n $this->nextAgent = 0;\n $this->agentId = $operator['operatorid'];\n $this->agentName = $operator_name;\n $this->save();\n\n // Send messages\n $this->postMessage(self::KIND_EVENTS, $message_to_post);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function actionGetItems(){\n $model = X2Model::model ($this->modelClass);\n if (isset ($model)) {\n list ($accessCond, $params) = $model->getAccessSQLCondition ();\n $tableName = $model->tableName ();\n $sql = \n 'SELECT id, fileName as value\n FROM '.$tableName.' \n WHERE associationType!=\"theme\" and fileName LIKE :qterm AND '.$accessCond.' AND\n (uploadedBy=:username OR private=0 OR private=NULL)\n ORDER BY fileName ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $params[':qterm'] = $qterm;\n $params[':username'] = Yii::app()->user->getName ();\n $result = $command->queryAll(true, $params);\n echo CJSON::encode($result);\n }\n Yii::app()->end();\n }", "label": 1, "label_name": "safe"} -{"code": "static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char *print_buffer;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n curl_free(print_buffer);\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function setParent($plist)\n {\n $this->parent = $plist;\n }", "label": 1, "label_name": "safe"} -{"code": "static int tiocgetd(struct tty_struct *tty, int __user *p)\n{\n\tstruct tty_ldisc *ld;\n\tint ret;\n\n\tld = tty_ldisc_ref_wait(tty);\n\tret = put_user(ld->ops->num, p);\n\ttty_ldisc_deref(ld);\n\treturn ret;\n}", "label": 1, "label_name": "safe"} -{"code": "int mif_validate(jas_stream_t *in)\n{\n\tjas_uchar buf[MIF_MAGICLEN];\n\tuint_fast32_t magic;\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= MIF_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, MIF_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\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\n\t/* Was enough data read? */\n\tif (n < MIF_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\t/* Compute the signature value. */\n\tmagic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |\n\t (JAS_CAST(uint_fast32_t, buf[1]) << 16) |\n\t (JAS_CAST(uint_fast32_t, buf[2]) << 8) |\n\t buf[3];\n\n\t/* Ensure that the signature is correct for this format. */\n\tif (magic != MIF_MAGIC) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": " it \"should exist\" do\n Puppet::Parser::Functions.function(\"staging_parse\").should == \"function_staging_parse\"\n end", "label": 0, "label_name": "vulnerable"} -{"code": " url: get_cluster_remote_url() + 'cluster_stop',\n data: data,\n timeout: pcs_timeout,\n success: function() {\n },\n error: function(xhr, status, error) {\n if ((status == \"timeout\") || ($.trim(error) == \"timeout\")) {\n /*\n We are not interested in timeout because:\n - it can take minutes to stop a node (resources running on it have\n to be stopped/moved and we do not need to wait for that)\n - if pcs is not able to stop a node it returns an (forceable) error\n immediatelly\n */\n return;\n }\n var message = \"Unable to stop node '\" + node + \"' \" + ajax_simple_error(\n xhr, status, error\n );\n if (message.indexOf('--force') == -1) {\n alert(message);\n }\n else {\n message = message.replace(', use --force to override', '');\n if (confirm(message + \"\\n\\nDo you want to force the operation?\")) {\n node_stop(node, true);\n }\n }\n }\n });\n}", "label": 1, "label_name": "safe"} -{"code": " foreach ($module->info_attr_transform_post as $k => $v) {\n if ($v === false) {\n unset($this->info_attr_transform_post[$k]);\n } else {\n $this->info_attr_transform_post[$k] = $v;\n }\n }", "label": 1, "label_name": "safe"} -{"code": "func LoadAll(basedir string) ([]*Plugin, error) {\n\tplugins := []*Plugin{}\n\t// We want basedir/*/plugin.yaml\n\tscanpath := filepath.Join(basedir, \"*\", PluginFileName)\n\tmatches, err := filepath.Glob(scanpath)\n\tif err != nil {\n\t\treturn plugins, err\n\t}\n\n\tif matches == nil {\n\t\treturn plugins, nil\n\t}\n\n\tfor _, yaml := range matches {\n\t\tdir := filepath.Dir(yaml)\n\t\tp, err := LoadDir(dir)\n\t\tif err != nil {\n\t\t\treturn plugins, err\n\t\t}\n\t\tplugins = append(plugins, p)\n\t}\n\treturn plugins, nil\n}", "label": 0, "label_name": "vulnerable"} -{"code": " private void HandleMouseDown()\n {\n if (ScreenShareService.Streams.ContainsKey(_authClient))\n {\n if (RunningAsService)\n {\n AgentClient.HandleLeftMouseDown();\n }\n else\n\n {\n new InputSimulator().Mouse.LeftButtonDown();\n }\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function edit_freeform() {\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\n if ($section->parent == -1) {\n notfoundController::handle_not_found();\n exit;\n } // doesn't work for standalone pages\n if (empty($section->id)) {\n $section->public = 1;\n if (!isset($section->parent)) {\n // This is another precaution. The parent attribute\n // should ALWAYS be set by the caller.\n //FJD - if that's the case, then we should die.\n notfoundController::handle_not_authorized();\n exit;\n //$section->parent = 0;\n }\n }\n assign_to_template(array(\n 'section' => $section,\n 'glyphs' => self::get_glyphs(),\n ));\n }", "label": 1, "label_name": "safe"} -{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);\n expHistory::back();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " Contacts::model()->deleteAll($criteria);\n }\n }\n echo $model->id;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def get_mail_attachment\n Log.add_info(request, params.inspect)\n\n attached_id = params[:id].to_i\n begin\n mail_attach = MailAttachment.find(attached_id)\n rescue => evar\n end\n\n if mail_attach.nil?\n redirect_to(THETIS_RELATIVE_URL_ROOT + '/404.html')\n return\n end\n\n begin\n email = Email.find(mail_attach.email_id)\n rescue => evar\n end\n if email.nil? or email.user_id != @login_user.id\n render(:text => '')\n return\n end\n\n mail_attach_name = mail_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 mail_attach_name = CGI::escape(mail_attach_name) unless ie_ver.nil?\n end\n\n filepath = mail_attach.get_path\n if FileTest.exist?(filepath)\n send_file(filepath, :filename => mail_attach_name, :stream => true, :disposition => 'attachment')\n else\n send_data('', :type => 'application/octet-stream;', :disposition => 'attachment;filename=\"'+mail_attach_name+'\"')\n end\n end", "label": 1, "label_name": "safe"} -{"code": " public static function remove_spam()\r\n {\r\n global $DB;\r\n global $website;\r\n\r\n $count = $DB->query_single(\r\n\t 'count(*) as total',\r\n\t 'nv_comments',\r\n\t 'website = '.intval($website->id).' AND status = 3'\r\n );\r\n\r\n $ok = $DB->execute('\r\n\t\t\tDELETE FROM nv_comments\r\n WHERE website = '.intval($website->id).'\r\n AND status = 3\r\n ');\r\n\r\n if($ok)\r\n return $count;\r\n }\r", "label": 1, "label_name": "safe"} -{"code": " public static function name($id)\n {\n $id = sprintf('%d', $id);\n if (isset($id)) {\n $cat = Db::result(\"SELECT `name` FROM `cat`\n WHERE `id` = '{$id}' LIMIT 1\");\n //print_r($cat);\n if (isset($cat['error'])) {\n return '';\n } else {\n return $cat[0]->name;\n }\n } else {\n echo 'No ID Selected';\n }\n\n //print_r($cat);\n }", "label": 1, "label_name": "safe"} -{"code": "mxCodecRegistry.register(function(){var a=new mxObjectCodec(new mxCell,[\"children\",\"edges\",\"overlays\",\"mxTransient\"],[\"parent\",\"source\",\"target\"]);a.isCellCodec=function(){return!0};a.isNumericAttribute=function(b,c,d){return\"value\"!==c.nodeName&&mxObjectCodec.prototype.isNumericAttribute.apply(this,arguments)};a.isExcluded=function(b,c,d,e){return mxObjectCodec.prototype.isExcluded.apply(this,arguments)||e&&\"value\"==c&&d.nodeType==mxConstants.NODETYPE_ELEMENT};a.afterEncode=function(b,c,d){if(null!=\nc.value&&c.value.nodeType==mxConstants.NODETYPE_ELEMENT){var e=d;d=mxUtils.importNode(b.document,c.value,!0);d.appendChild(e);b=e.getAttribute(\"id\");d.setAttribute(\"id\",b);e.removeAttribute(\"id\")}return d};a.beforeDecode=function(b,c,d){var e=c.cloneNode(!0),f=this.getName();c.nodeName!=f?(e=c.getElementsByTagName(f)[0],null!=e&&e.parentNode==c?(mxUtils.removeWhitespace(e,!0),mxUtils.removeWhitespace(e,!1),e.parentNode.removeChild(e)):e=null,d.value=c.cloneNode(!0),c=d.value.getAttribute(\"id\"),null!=", "label": 0, "label_name": "vulnerable"} -{"code": " public function getHex($prefix = '')\n {\n return sprintf('%s%02x%02x%02x', $prefix, $this->r, $this->g, $this->b);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function addOrderBy( $orderBy ) {\n\t\tif ( empty( $orderBy ) ) {\n\t\t\tthrow new MWException( __METHOD__ . ': An empty order by clause was passed.' );\n\t\t}\n\n\t\t$this->orderBy[] = $orderBy;\n\n\t\treturn true;\n\t}", "label": 1, "label_name": "safe"} -{"code": "def _resolve_lazy_url(url):\n if callable(url):\n return url()\n return url", "label": 1, "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, "label_name": "safe"} -{"code": " public function withUri(UriInterface $uri, $preserveHost = false)\n {\n if ($uri === $this->uri) {\n return $this;\n }\n\n $new = clone $this;\n $new->uri = $uri;\n\n if (!$preserveHost) {\n if ($host = $uri->getHost()) {\n $new->updateHostFromUri($host);\n }\n }\n\n return $new;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {\n $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);\n $config = HTMLPurifier_Config::create($ret, $schema);\n return $config;\n }", "label": 1, "label_name": "safe"} -{"code": "parse_ranges(struct client *clt, char *str, size_t file_sz)\n{\n\tint\t\t\t i = 0;\n\tchar\t\t\t*p, *q;\n\tstruct range_data\t*r = &clt->clt_ranges;\n\n\tmemset(r, 0, sizeof(*r));\n\n\t/* Extract range unit */\n\tif ((p = strchr(str, '=')) == NULL)\n\t\treturn (-1);\n\n\t*p++ = '\\0';\n\t/* Check if it's a bytes range spec */\n\tif (strcmp(str, \"bytes\") != 0)\n\t\treturn (-1);\n\n\twhile ((q = strchr(p, ',')) != NULL) {\n\t\t*q++ = '\\0';\n\n\t\t/* Extract start and end positions */\n\t\tif (parse_range_spec(p, file_sz, &r->range[i]) == 0)\n\t\t\tcontinue;\n\n\t\ti++;\n\t\tif (i == SERVER_MAX_RANGES)\n\t\t\treturn (-1);\n\n\t\tp = q;\n\t}\n\n\tif (parse_range_spec(p, file_sz, &r->range[i]) != 0)\n\t\ti++;\n\n\tr->range_total = file_sz;\n\tr->range_count = i;\n\treturn (i);\n}", "label": 1, "label_name": "safe"} -{"code": " public function rules() {\n // NOTE: you should only define rules for those attributes that\n // will receive user inputs.\n return array(\n array ('tag', 'validateTag'),\n array('type, itemId, taggedBy, tag', 'required'),\n array('itemId, timestamp', 'numerical', 'integerOnly'=>true),\n array('type, taggedBy', 'length', 'max'=>50),\n array('tag, itemName', 'length', 'max'=>250),\n array(\n 'tag', \n 'application.extensions.unique-attributes-validator.UniqueAttributesValidator', \n 'with'=>'tag,type,itemId'\n ),\n // The following rule is used by search().\n // Please remove those attributes that should not be searched.\n array('id, type, itemId, taggedBy, tag, timestamp, itemName', 'safe', 'on'=>'search'),\n );\n }", "label": 1, "label_name": "safe"} -{"code": "\tfunction GetTransactionStateCodeMessage($Code)\n\t{\n\t\treturn $this -> TransactionStateCodes[$Code];\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function replace($def, $config)\n {\n $status = parent::replace($def, $config);\n if (!$status) {\n parent::cleanup($config);\n }\n return $status;\n }", "label": 1, "label_name": "safe"} -{"code": "static unsigned long mmap_legacy_base(unsigned long rnd)\n{\n\tif (mmap_is_ia32())\n\t\treturn TASK_UNMAPPED_BASE;\n\telse\n\t\treturn TASK_UNMAPPED_BASE + rnd;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "func (svc *Service) GetGlobalScheduledQueries(ctx context.Context, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgp, err := svc.ds.EnsureGlobalPack(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts)\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\ttext : fm.i18n('confirmUnmount', drive.name),\n\t\t\t\taccept : {\n\t\t\t\t\tlabel : 'btnUnmount',\n\t\t\t\t\tcallback : function() { \n\t\t\t\t\t\tvar chDrive = (fm.root() == drive.hash),\n\t\t\t\t\t\t\tbase = $('#'+fm.navHash2Id(drive.hash)).parent(),\n\t\t\t\t\t\t\tnavTo = (base.next().length? base.next() : base.prev()).find('.elfinder-navbar-root');\n\t\t\t\t\t\tfm.request({\n\t\t\t\t\t\t\tdata : {cmd : 'netmount', protocol : 'netunmount', host: drive.netkey, user : drive.hash, pass : 'dum'}, \n\t\t\t\t\t\t\tnotify : {type : 'netunmount', cnt : 1, hideCnt : true},\n\t\t\t\t\t\t\tpreventFail : true\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.fail(function(error) {\n\t\t\t\t\t\t\tdfrd.reject(error);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.done(function(data) {\n\t\t\t\t\t\t\tvar open = fm.root();\n\t\t\t\t\t\t\tif (chDrive) {\n\t\t\t\t\t\t\t\tif (navTo.length) {\n\t\t\t\t\t\t\t\t\topen = fm.navId2Hash(navTo[0].id);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tvar files = fm.files();\n\t\t\t\t\t\t\t\t\tfor (var i in files) {\n\t\t\t\t\t\t\t\t\t\tif (fm.file(i).mime == 'directory') {\n\t\t\t\t\t\t\t\t\t\t\topen = i;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\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}\n\t\t\t\t\t\t\t\tfm.exec('open', open);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdfrd.resolve();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tcancel : {\n\t\t\t\t\tlabel : 'btnCancel',\n\t\t\t\t\tcallback : function() { dfrd.reject(); }\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\t\n\t\treturn dfrd;\n\t};", "label": 1, "label_name": "safe"} -{"code": " public function edit_discount() {\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $discount = new discounts($id);\n\n //grab all user groups\n $group = new group();\n\n //create two 'default' groups:\n $groups = array(\n -1 => 'ALL LOGGED IN USERS',\n -2 => 'ALL NON-LOGGED IN USERS'\n );\n //loop our groups and append them to the array\n // foreach ($group->find() as $g){\n //this is a workaround for older code. Use the previous line if possible:\n $allGroups = group::getAllGroups();\n if (count($allGroups))\n {\n foreach ($allGroups as $g)\n {\n $groups[$g->id] = $g->name;\n };\n }\n //find our selected groups for this discount already\n // eDebug($discount);\n $selected_groups = array();\n if (!empty($discount->group_ids))\n {\n $selected_groups = expUnserialize($discount->group_ids);\n }\n\n if ($discount->minimum_order_amount == \"\") $discount->minimum_order_amount = 0;\n if ($discount->discount_amount == \"\") $discount->discount_amount = 0;\n if ($discount->discount_percent == \"\") $discount->discount_percent = 0;\n\n // get the shipping options and their methods\n $shipping_services = array();\n $shipping_methods = array();\n// $shipping = new shipping();\n foreach (shipping::listAvailableCalculators() as $calcid=>$name) {\n if (class_exists($name)) {\n $calc = new $name($calcid);\n $shipping_services[$calcid] = $calc->title;\n $shipping_methods[$calcid] = $calc->availableMethods();\n }\n }\n\n assign_to_template(array(\n 'discount'=>$discount,\n 'groups'=>$groups,\n 'selected_groups'=>$selected_groups,\n 'shipping_services'=>$shipping_services,\n 'shipping_methods'=>$shipping_methods\n ));\n }", "label": 1, "label_name": "safe"} -{"code": " public function isOld($key, $config) {\n if (substr_count($key, ',') < 2) return true;\n list($version, $hash, $revision) = explode(',', $key, 3);\n $compare = version_compare($version, $config->version);\n // version mismatch, is always old\n if ($compare != 0) return true;\n // versions match, ids match, check revision number\n if (\n $hash == $config->getBatchSerial($this->type) &&\n $revision < $config->get($this->type . '.DefinitionRev')\n ) return true;\n return false;\n }", "label": 1, "label_name": "safe"} -{"code": " public function getTags()\n {\n return $this->tags;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def test_from_data(self, mocker):\n from openapi_python_client.parser.openapi import Endpoint\n\n path = mocker.MagicMock()\n method = mocker.MagicMock()\n _add_parameters = mocker.patch.object(Endpoint, \"_add_parameters\")\n _add_responses = mocker.patch.object(Endpoint, \"_add_responses\")\n _add_body = mocker.patch.object(Endpoint, \"_add_body\")\n data = oai.Operation.construct(\n description=mocker.MagicMock(),\n operationId=mocker.MagicMock(),\n security={\"blah\": \"bloo\"},\n responses=mocker.MagicMock(),\n )\n\n mocker.patch(\"openapi_python_client.utils.remove_string_escapes\", return_value=data.description)\n\n endpoint = Endpoint.from_data(data=data, path=path, method=method, tag=\"default\")\n\n assert endpoint == _add_body.return_value\n\n _add_parameters.assert_called_once_with(\n Endpoint(\n path=path,\n method=method,\n description=data.description,\n name=data.operationId,\n requires_security=True,\n tag=\"default\",\n ),\n data,\n )\n _add_responses.assert_called_once_with(_add_parameters.return_value, data.responses)\n _add_body.assert_called_once_with(_add_responses.return_value, data)\n\n data.security = None\n _add_parameters.reset_mock()\n\n Endpoint.from_data(data=data, path=path, method=method, tag=\"a\")\n\n _add_parameters.assert_called_once_with(\n Endpoint(\n path=path,\n method=method,\n description=data.description,\n name=data.operationId,\n requires_security=False,\n tag=\"a\",\n ),\n data,\n )\n\n data.operationId = None\n assert Endpoint.from_data(data=data, path=path, method=method, tag=\"a\") == ParseError(\n data=data, detail=\"Path operations with operationId are not yet supported\"\n )", "label": 1, "label_name": "safe"} -{"code": "PlayerGeneric::~PlayerGeneric()\n{\n\tif (mixer)\n\t\tdelete mixer;\n\n\tif (player)\n\t{\n\t\tif (mixer->isActive() && !mixer->isDeviceRemoved(player))\n\t\t\tmixer->removeDevice(player);\n\t\tdelete player;\n\t}\n\n\tdelete[] audioDriverName;\n\t\n\tdelete listener;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static int au1200fb_fb_mmap(struct fb_info *info, struct vm_area_struct *vma)\n{\n\tstruct au1200fb_device *fbdev = info->par;\n\n\tvma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);\n\tpgprot_val(vma->vm_page_prot) |= _CACHE_MASK; /* CCA=7 */\n\n\treturn vm_iomap_memory(vma, fbdev->fb_phys, fbdev->fb_len);\n}", "label": 1, "label_name": "safe"} -{"code": " public function getDisplayName ($plural=true) {\n $moduleName = X2Model::getModuleName (get_class ($this));\n return Modules::displayName ($plural, $moduleName);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic static void writeObject(XStream xStream, OutputStream os, Object obj) {\n\t\ttry(OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {\n\t\t\tString data = xStream.toXML(obj);\n\t\t\tdata = \"\\n\"\n\t\t\t\t\t+ data; // give a decent header with the encoding used\n\t\t\tosw.write(data);\n\t\t\tosw.flush();\n\t\t} catch (Exception e) {\n\t\t\tthrow new OLATRuntimeException(XStreamHelper.class, \"Could not write object to stream.\", e);\n\t\t}\n\t}", "label": 1, "label_name": "safe"} -{"code": " $this->beforeHead(array(\n 'name' => 'head',\n 'type' => HTML5::STARTTAG,\n 'attr' => array()\n ));", "label": 1, "label_name": "safe"} -{"code": " function delete_option_master() {\n global $db;\n\n $masteroption = new option_master($this->params['id']);\n \n // delete any implementations of this option master\n $db->delete('option', 'option_master_id='.$masteroption->id);\n $masteroption->delete('optiongroup_master_id=' . $masteroption->optiongroup_master_id);\n //eDebug($masteroption);\n expHistory::back();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "void set_task_blockstep(struct task_struct *task, bool on)\n{\n\tunsigned long debugctl;\n\n\t/*\n\t * Ensure irq/preemption can't change debugctl in between.\n\t * Note also that both TIF_BLOCKSTEP and debugctl should\n\t * be changed atomically wrt preemption.\n\t * FIXME: this means that set/clear TIF_BLOCKSTEP is simply\n\t * wrong if task != current, SIGKILL can wakeup the stopped\n\t * tracee and set/clear can play with the running task, this\n\t * can confuse the next __switch_to_xtra().\n\t */\n\tlocal_irq_disable();\n\tdebugctl = get_debugctlmsr();\n\tif (on) {\n\t\tdebugctl |= DEBUGCTLMSR_BTF;\n\t\tset_tsk_thread_flag(task, TIF_BLOCKSTEP);\n\t} else {\n\t\tdebugctl &= ~DEBUGCTLMSR_BTF;\n\t\tclear_tsk_thread_flag(task, TIF_BLOCKSTEP);\n\t}\n\tif (task == current)\n\t\tupdate_debugctlmsr(debugctl);\n\tlocal_irq_enable();\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function pa(){mxEllipse.call(this)}function ua(){mxEllipse.call(this)}function ya(){mxRhombus.call(this)}function Fa(){mxEllipse.call(this)}function Ma(){mxEllipse.call(this)}function Oa(){mxEllipse.call(this)}function Pa(){mxEllipse.call(this)}function Sa(){mxActor.call(this)}function za(){mxActor.call(this)}function wa(){mxActor.call(this)}function Ea(c,l,x,p){mxShape.call(this);this.bounds=c;this.fill=l;this.stroke=x;this.strokewidth=null!=p?p:1;this.rectStyle=\"square\";this.size=10;this.absoluteCornerSize=", "label": 1, "label_name": "safe"} -{"code": "function duplicateRule(e) {\n let box = $(e.currentTarget);\n var ruleId = box.data('id');\n $.post(duplicateRuleUrl, {_token: token, id: ruleId}).then(function () {\n location.reload();\n }).fail(function() {\n alert('I failed :(');\n });\n\n return false;\n}", "label": 1, "label_name": "safe"} -{"code": " public ActionResult GetHlsPlaylistLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string playlistId)\n {\n var file = playlistId + Path.GetExtension(Request.Path);\n var transcodePath = _serverConfigurationManager.GetTranscodePath();\n file = Path.GetFullPath(Path.Combine(transcodePath, file));\n var fileDir = Path.GetDirectoryName(file);\n if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath) || Path.GetExtension(file) != \".m3u8\")\n {\n return BadRequest(\"Invalid segment.\");\n }\n\n return GetFileResult(file, file);\n }", "label": 1, "label_name": "safe"} -{"code": "static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) {\n\tint i;\n\tstruct minidump_directory entry;\n\n\tsdb_num_set (obj->kv, \"mdmp_directory.offset\",\n\t\t\tobj->hdr->stream_directory_rva, 0);\n\tsdb_set (obj->kv, \"mdmp_directory.format\", \"[4]E? \"\n\t\t\t\"(mdmp_stream_type)StreamType \"\n\t\t\t\"(mdmp_location_descriptor)Location\", 0);\n\n\t/* Parse each entry in the directory */\n\tut64 rvadir = obj->hdr->stream_directory_rva;\n\tfor (i = 0; i < (int)obj->hdr->number_of_streams; i++) {\n\t\tut32 delta = i * sizeof (struct minidump_directory);\n\t\tint r = r_buf_read_at (obj->b, rvadir + delta, (ut8*) &entry, sizeof (struct minidump_directory));\n\t\tif (r) {\n\t\t\tr_bin_mdmp_init_directory_entry (obj, &entry);\n\t\t}\n\t}\n\n\treturn true;\n}", "label": 1, "label_name": "safe"} -{"code": "def get_cc_columns(filter_config_custom_read=False):\n tmpcc = calibre_db.session.query(db.CustomColumns)\\\n .filter(db.CustomColumns.datatype.notin_(db.cc_exceptions)).all()\n cc = []\n r = None\n if config.config_columns_to_ignore:\n r = re.compile(config.config_columns_to_ignore)\n\n for col in tmpcc:\n if filter_config_custom_read and config.config_read_column and config.config_read_column == col.id:\n continue\n if r and r.match(col.name):\n continue\n cc.append(col)\n\n return cc", "label": 1, "label_name": "safe"} -{"code": " public void requestDestroyed(HttpServletRequest request) {\n if (isRequestDestroyed(request)) {\n return;\n }\n if (nestedInvocationGuardEnabled) {\n Counter counter = nestedInvocationGuard.get();\n if (counter != null) {\n counter.value--;\n if (counter.value > 0) {\n return; // this is a nested invocation, ignore it\n } else {\n nestedInvocationGuard.remove(); // this is the outer invocation\n request.removeAttribute(GUARD_PARAMETER_NAME);\n }\n } else {\n ServletLogger.LOG.guardNotSet();\n return;\n }\n }\n if (ignoreForwards && isForwardedRequest(request)) {\n return;\n }\n if (ignoreIncludes && isIncludedRequest(request)) {\n return;\n }\n if (!contextActivationFilter.accepts(request)) {\n return;\n }\n\n ServletLogger.LOG.requestDestroyed(request);\n\n try {\n conversationContextActivator.deactivateConversationContext(request);\n /*\n * if this request has been switched to async then do not invalidate the context now\n * as it will be invalidated at the end of the async operation.\n */\n if (!servletApi.isAsyncSupported() || !servletApi.isAsyncStarted(request)) {\n getRequestContext().invalidate();\n }\n getRequestContext().deactivate();\n // fire @Destroyed(RequestScoped.class)\n requestDestroyedEvent.fire(request);\n getSessionContext().deactivate();\n // fire @Destroyed(SessionScoped.class)\n if (!getSessionContext().isValid()) {\n sessionDestroyedEvent.fire((HttpSession) request.getAttribute(HTTP_SESSION));\n }\n } finally {\n getRequestContext().dissociate(request);\n\n // WFLY-1533 Underlying HTTP session may be invalid\n try {\n getSessionContext().dissociate(request);\n } catch (Exception e) {\n ServletLogger.LOG.unableToDissociateContext(getSessionContext(), request);\n ServletLogger.LOG.catchingDebug(e);\n }\n // Catch block is inside the activator method so that we're able to log the context\n conversationContextActivator.disassociateConversationContext(request);\n\n SessionHolder.clear();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function addUser(){\n $login_user = $this->checkLogin();\n $this->checkAdmin();\n $username = I(\"post.username\");\n $password = I(\"post.password\");\n $uid = I(\"post.uid\");\n $name = I(\"post.name\");\n if(!$username){\n $this->sendError(10101,'\u7528\u6237\u540d\u4e0d\u5141\u8bb8\u4e3a\u7a7a');\n return ;\n }\n if($uid){\n if($password){\n D(\"User\")->updatePwd($uid, $password);\n }\n if($name){\n D(\"User\")->where(\" uid = '$uid' \")->save(array(\"name\"=>$name));\n }\n $this->sendResult(array());\n }else{\n if (D(\"User\")->isExist($username)) {\n $this->sendError(10101,L('username_exists'));\n return ;\n }\n $new_uid = D(\"User\")->register($username,$password);\n if (!$new_uid) {\n $this->sendError(10101);\n }else{\n if($name){\n D(\"User\")->where(\" uid = '$new_uid' \")->save(array(\"name\"=>$name));\n }\n $this->sendResult($return);\n }\n }\n\n }", "label": 1, "label_name": "safe"} -{"code": "static inline struct sem_array *sem_obtain_lock(struct ipc_namespace *ns,\n\t\t\tint id, struct sembuf *sops, int nsops, int *locknum)\n{\n\tstruct kern_ipc_perm *ipcp;\n\tstruct sem_array *sma;\n\n\trcu_read_lock();\n\tipcp = ipc_obtain_object(&sem_ids(ns), id);\n\tif (IS_ERR(ipcp)) {\n\t\tsma = ERR_CAST(ipcp);\n\t\tgoto err;\n\t}\n\n\tsma = container_of(ipcp, struct sem_array, sem_perm);\n\t*locknum = sem_lock(sma, sops, nsops);\n\n\t/* ipc_rmid() may have already freed the ID while sem_lock\n\t * was spinning: verify that the structure is still valid\n\t */\n\tif (!ipcp->deleted)\n\t\treturn container_of(ipcp, struct sem_array, sem_perm);\n\n\tsem_unlock(sma, *locknum);\n\tsma = ERR_PTR(-EINVAL);\nerr:\n\trcu_read_unlock();\n\treturn sma;\n}", "label": 1, "label_name": "safe"} -{"code": " public static function withQueryValue(UriInterface $uri, $key, $value)\n {\n $current = $uri->getQuery();\n $key = strtr($key, self::$replaceQuery);\n\n if (!$current) {\n $result = [];\n } else {\n $result = [];\n foreach (explode('&', $current) as $part) {\n if (explode('=', $part)[0] !== $key) {\n $result[] = $part;\n };\n }\n }\n\n if ($value !== null) {\n $result[] = $key . '=' . strtr($value, self::$replaceQuery);\n } else {\n $result[] = $key;\n }\n\n return $uri->withQuery(implode('&', $result));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tprivate static void validate(final byte[] iv, final int authTagLength)\n\t\tthrows JOSEException {\n\t\t\n\t\tif (ByteUtils.bitLength(iv) != IV_BIT_LENGTH) {\n\t\t\tthrow new JOSEException(String.format(\"IV length of %d bits is required, got %d\", IV_BIT_LENGTH, ByteUtils.bitLength(iv)));\n\t\t}\n\n\t\tif (authTagLength != AUTH_TAG_BIT_LENGTH) {\n\t\t\tthrow new JOSEException(String.format(\"Authentication tag length of %d bits is required, got %d\", AUTH_TAG_BIT_LENGTH, authTagLength));\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "\tstatic function validUTF($string) {\n\t\tif(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}", "label": 1, "label_name": "safe"} -{"code": "\t\tget: function(elem, computed, extra) {\n\t\t\treturn $(elem).rotate();\n\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_getDefinition()\n {\n $this->schema->add('Cache.DefinitionImpl', null, 'string', true);\n $config = new HTMLPurifier_Config($this->schema);\n $this->expectException(new HTMLPurifier_Exception(\"Definition of Crust type not supported\"));\n $config->getDefinition('Crust');\n }", "label": 1, "label_name": "safe"} -{"code": " public function testHrRemoveInvalidAlign()\n {\n $this->assertResult(\n '
',\n '
'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "unsigned paravirt_patch_jmp(void *insnbuf, const void *target,\n\t\t\t unsigned long addr, unsigned len)\n{\n\tstruct branch *b = insnbuf;\n\tunsigned long delta = (unsigned long)target - (addr+5);\n\n\tif (len < 5) {\n#ifdef CONFIG_RETPOLINE\n\t\tWARN_ONCE(\"Failing to patch indirect JMP in %ps\\n\", (void *)addr);\n#endif\n\t\treturn len;\t/* call too long for patch site */\n\t}\n\n\tb->opcode = 0xe9;\t/* jmp */\n\tb->delta = delta;\n\n\treturn 5;\n}", "label": 1, "label_name": "safe"} -{"code": "function(){g.checked&&(null==e||e.checked)?q.removeAttribute(\"disabled\"):q.setAttribute(\"disabled\",\"disabled\")}));mxUtils.br(c);return{getLink:function(){return g.checked?\"blank\"===q.value?\"_blank\":m:null},getEditInput:function(){return g},getEditSelect:function(){return q}}};EditorUi.prototype.addLinkSection=function(c,e){function g(){var y=document.createElement(\"div\");y.style.width=\"100%\";y.style.height=\"100%\";y.style.boxSizing=\"border-box\";null!=q&&q!=mxConstants.NONE?(y.style.border=\"1px solid black\",\ny.style.backgroundColor=q):(y.style.backgroundPosition=\"center center\",y.style.backgroundRepeat=\"no-repeat\",y.style.backgroundImage=\"url('\"+Dialog.prototype.closeImage+\"')\");v.innerHTML=\"\";v.appendChild(y)}mxUtils.write(c,mxResources.get(\"links\")+\":\");var k=document.createElement(\"select\");k.style.width=\"100px\";k.style.padding=\"0px\";k.style.marginLeft=\"8px\";k.style.marginRight=\"10px\";k.className=\"geBtn\";var m=document.createElement(\"option\");m.setAttribute(\"value\",\"auto\");mxUtils.write(m,mxResources.get(\"automatic\"));", "label": 1, "label_name": "safe"} -{"code": " function selectArraysBySql($sql) {\n $res = @mysqli_query($this->connection, $this->injectProof($sql));\n if ($res == null)\n return array();\n $arrays = array();\n for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)\n $arrays[] = mysqli_fetch_assoc($res);\n return $arrays;\n }", "label": 1, "label_name": "safe"} -{"code": " public float GetGpuTemp(string gpuName)\n {\n try\n {\n var temp = InputChannel.GetGpuTemp(gpuName);\n return temp;\n }\n catch (EndpointNotFoundException)\n {\n return -1;\n }\n catch (CommunicationException)\n {\n return -1;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " \"no extensions\": function(c) { assert.ok(!c.extensions) }", "label": 1, "label_name": "safe"} -{"code": " protected function getEnvParameters()\n {\n $parameters = array();\n foreach ($_SERVER as $key => $value) {\n if (0 === strpos($key, 'SYMFONY__')) {\n $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;\n }\n }\n\n return $parameters;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tcontent: function() {\n\t\t\treturn $( this ).attr( \"title\" );\n\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " public function getAdapter()\n {\n return $this->adapter;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function update()\n {\n $project = $this->getProject();\n $column = $this->getColumn($project);\n\n $values = $this->request->getValues() + array('hide_in_dashboard' => 0);\n $values['project_id'] = $project['id'];\n $values['id'] = $column['id'];\n\n list($valid, $errors) = $this->columnValidator->validateModification($values);\n\n if ($valid) {\n $result = $this->columnModel->update(\n $values['id'],\n $values['title'],\n $values['task_limit'],\n $values['description'],\n $values['hide_in_dashboard']\n );\n\n if ($result) {\n $this->flash->success(t('Board updated successfully.'));\n $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])), true);\n return;\n } else {\n $this->flash->failure(t('Unable to update this board.'));\n }\n }\n\n $this->edit($values, $errors);\n }", "label": 1, "label_name": "safe"} -{"code": " public function __toString()\n {\n return serialize($this->getResource());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testGetAliases()\n {\n $builder = new ContainerBuilder();\n $builder->setAlias('bar', 'foo');\n $builder->setAlias('foobar', 'foo');\n $builder->setAlias('moo', new Alias('foo', false));\n\n $aliases = $builder->getAliases();\n $this->assertEquals('foo', (string) $aliases['bar']);\n $this->assertTrue($aliases['bar']->isPublic());\n $this->assertEquals('foo', (string) $aliases['foobar']);\n $this->assertEquals('foo', (string) $aliases['moo']);\n $this->assertFalse($aliases['moo']->isPublic());\n\n $builder->register('bar', 'stdClass');\n $this->assertFalse($builder->hasAlias('bar'));\n\n $builder->set('foobar', 'stdClass');\n $builder->set('moo', 'stdClass');\n $this->assertCount(0, $builder->getAliases(), '->getAliases() does not return aliased services that have been overridden');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($cf_d as $cfd_i => $cfd_d) {\n if ($cfd_i == 'TYPE') {\n $fc = substr($cfd_d, 0, 1);\n $lc = substr($cfd_d, 1);\n $cfd_d = strtoupper($fc) . $lc;\n $get_schools_cf[$cf_i][$cfd_i] = $cfd_d;\n unset($fc);\n unset($lc);\n }\n if ($cfd_i == 'SELECT_OPTIONS' && $cf_d['TYPE'] != 'text') {\n\n for ($i = 0; $i < strlen($cfd_d); $i++) {\n $char = substr($cfd_d, $i, 1);\n if (ord($char) == '13')\n $char = '
';\n $new_char[] = $char;\n }\n\n $cfd_d = implode('', $new_char);\n $get_schools_cf[$cf_i][$cfd_i] = $cfd_d;\n unset($char);\n unset($new_char);\n }\n if ($cfd_i == 'SYSTEM_FIELD' || $cfd_i == 'REQUIRED') {\n if ($cfd_d == 'N')\n $get_schools_cf[$cf_i][$cfd_i] = 'No';\n if ($cfd_d == 'Y')\n $get_schools_cf[$cf_i][$cfd_i] = 'Yes';\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tvoid testPointWithException() {\n\t\tJsonParser.Defaults.classMetadataName = \"__class\";\n\t\tJsonSerializer.Defaults.classMetadataName = \"__class\";\n\n\t\tJsonParsers.forEachParser(jsonParser -> {\n\t\t\tjsonParser.allowClass(\"notAllowed\");\n\t\t\tfinal String json = new JsonSerializer().serialize(new Point2D.Float(1.0f, 2.0f));\n\t\t\tassertThrows(JsonException.class, () -> {\n\t\t\t\tjsonParser.parse(json);\n\t\t\t});\n\t\t\tjsonParser.allowAllClasses();\n\t\t});\n\t}", "label": 1, "label_name": "safe"} -{"code": "\twp.updates.queueChecker = function() {\n\t\tvar job;\n\n\t\tif ( wp.updates.ajaxLocked || ! wp.updates.queue.length ) {\n\t\t\treturn;\n\t\t}\n\n\t\tjob = wp.updates.queue.shift();\n\n\t\t// Handle a queue job.\n\t\tswitch ( job.action ) {\n\t\t\tcase 'install-plugin':\n\t\t\t\twp.updates.installPlugin( job.data );\n\t\t\t\tbreak;\n\n\t\t\tcase 'update-plugin':\n\t\t\t\twp.updates.updatePlugin( job.data );\n\t\t\t\tbreak;\n\n\t\t\tcase 'delete-plugin':\n\t\t\t\twp.updates.deletePlugin( job.data );\n\t\t\t\tbreak;\n\n\t\t\tcase 'install-theme':\n\t\t\t\twp.updates.installTheme( job.data );\n\t\t\t\tbreak;\n\n\t\t\tcase 'update-theme':\n\t\t\t\twp.updates.updateTheme( job.data );\n\t\t\t\tbreak;\n\n\t\t\tcase 'delete-theme':\n\t\t\t\twp.updates.deleteTheme( job.data );\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\twindow.console.error( 'Failed to execute queued update job.', job );\n\t\t\t\tbreak;\n\t\t}\n\t};", "label": 1, "label_name": "safe"} -{"code": " private static boolean validateChainData(JsonNode data) throws Exception {\n ECPublicKey lastKey = null;\n boolean validChain = false;\n for (JsonNode node : data) {\n JWSObject jwt = JWSObject.parse(node.asText());\n\n if (!validChain) {\n validChain = EncryptionUtils.verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());\n }\n\n if (lastKey != null) {\n if (!EncryptionUtils.verifyJwt(jwt, lastKey)) return false;\n }\n\n JsonNode payloadNode = JSON_MAPPER.readTree(jwt.getPayload().toString());\n JsonNode ipkNode = payloadNode.get(\"identityPublicKey\");\n Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, \"identityPublicKey node is missing in chain\");\n lastKey = EncryptionUtils.generateKey(ipkNode.asText());\n }\n return validChain;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getLastMessageID()\n {\n return $this->lastMessageID;\n }", "label": 1, "label_name": "safe"} -{"code": "\tapiReady: function apiReady() {\n\n\t\tDailyMotionApi.isLoaded = true;\n\t\tDailyMotionApi.isSDKLoaded = true;\n\n\t\twhile (DailyMotionApi.iframeQueue.length > 0) {\n\t\t\tvar settings = DailyMotionApi.iframeQueue.pop();\n\n\t\t\tDM.init({\n\t\t\t\tapiKey: settings.apiKey,\n\t\t\t\tstatus: settings.status,\n\t\t\t\tcookie: settings.cookie\n\t\t\t});\n\n\t\t\tDailyMotionApi.createIframe(settings);\n\t\t}\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": "var search = (module.exports.search = function search(object, path, action) {\n if (typeof path === \"string\") {\n path = path.split(\".\");\n }\n\n if (!(path instanceof Array) || path.length === 0) {\n return;\n }\n\n path = path.slice();\n\n var key = path.shift();\n\n if (typeof object !== \"object\" || object === null) {\n return;\n }\n\n if (key === \"*\") {\n key = \".*\";\n }\n\n if (typeof key === \"string\") {\n key = new RegExp(key);\n }\n\n if (path.length === 0) {\n return Object.keys(object)\n .filter(key.test.bind(key))\n .map(function (k) {\n var value = object[k];\n if (action) {\n action(value, object, k);\n }\n return value;\n });\n } else {\n return Array.prototype.concat.apply(\n [],\n Object.keys(object)\n .filter(key.test.bind(key))\n .map(function (k) {\n return search(object[k], path, action);\n })\n );\n }\n});", "label": 1, "label_name": "safe"} -{"code": " protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)\n {\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n $this->createMessage(Message\\VoidedResponse::class, $gatewayMessage);\n\n ErrorHandling::safeExtend($this->payment, 'onVoid', $serviceResponse);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " add (id, text, commentsData) {\n commentsData.find((item, index) => {\n if (item.id === id) {\n const cmtElement = document.createElement('div')\n cmtElement.setAttribute('data-id', id)\n cmtElement.innerHTML = `
\n${text}
\n
\n\n
`\n cmtElement.value = text\n if (index === 0) {\n document.querySelector('#comments').\n insertAdjacentElement('beforeend', cmtElement)\n } else {\n document.querySelector(\n `#comments div[data-id=\"${commentsData[index - 1].id}\"]`).\n insertAdjacentElement('afterend', cmtElement)\n }\n bindCommentEvent(cmtElement)\n cmtElement.querySelector('input').focus()\n let cmts = localStorage.getItem('cmts')\n if (!cmts) {\n localStorage.setItem('cmts', '[]')\n cmts = []\n } else {\n cmts = JSON.parse(cmts)\n }\n cmts.push({id, text})\n localStorage.setItem('cmts', JSON.stringify(cmts))\n return true\n }\n })\n matchCommentsTop(commentsData)\n },", "label": 1, "label_name": "safe"} -{"code": " public async Task UpdateListByVolume(UpdateReadingListByVolumeDto dto)\n {\n var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());\n var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);\n if (readingList == null) return BadRequest(\"Reading List does not exist\");\n var chapterIdsForVolume =\n (await _unitOfWork.ChapterRepository.GetChaptersAsync(dto.VolumeId)).Select(c => c.Id).ToList();\n\n // If there are adds, tell tracking this has been modified\n if (await AddChaptersToReadingList(dto.SeriesId, chapterIdsForVolume, readingList))\n {\n _unitOfWork.ReadingListRepository.Update(readingList);\n }\n\n try\n {\n if (_unitOfWork.HasChanges())\n {\n await _unitOfWork.CommitAsync();\n return Ok(\"Updated\");\n }\n }\n catch\n {\n await _unitOfWork.RollbackAsync();\n }\n\n return Ok(\"Nothing to do\");\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def match?(name, ip)\n ip? ? pattern.include?(IPAddr.new(ip)) : matchname?(name)\n end", "label": 0, "label_name": "vulnerable"} -{"code": "RawTile KakaduImage::getRegion( int seq, int ang, unsigned int res, int layers, int x, int y, unsigned int w, unsigned int h )\n{\n // Scale up our output bit depth to the nearest factor of 8\n unsigned int obpc = bpc;\n if( bpc <= 16 && bpc > 8 ) obpc = 16;\n else if( bpc <= 8 ) obpc = 8;\n\n#ifdef DEBUG\n Timer timer;\n timer.start();\n#endif\n\n RawTile rawtile( 0, res, seq, ang, w, h, channels, obpc );\n\n if( obpc == 16 ) rawtile.data = new unsigned short[w*h*channels];\n else if( obpc == 8 ) rawtile.data = new unsigned char[w*h*channels];\n else throw file_error( \"Kakadu :: Unsupported number of bits\" );\n\n rawtile.dataLength = w*h*channels*(obpc/8);\n rawtile.filename = getImagePath();\n rawtile.timestamp = timestamp;\n\n process( res, layers, x, y, w, h, rawtile.data );\n\n#ifdef DEBUG\n logfile << \"Kakadu :: getRegion() :: \" << timer.getTime() << \" microseconds\" << endl;\n#endif\n\n return rawtile;\n\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function getURIDefinition($raw = false, $optimized = false)\n {\n return $this->getDefinition('URI', $raw, $optimized);\n }", "label": 1, "label_name": "safe"} -{"code": "typeof ha.getAttribute&&null!=ha.getAttribute(\"title\")&&sa.push({img:ha.getAttribute(\"img\"),libs:ha.getAttribute(\"libs\"),clibs:ha.getAttribute(\"clibs\"),title:ha.getAttribute(\"title\")}),ha=ha.nextSibling;E(sa)}});var ua=function(ha,da,ca){ja.style.display=\"\";Fa.stop();W=!1;if(U)U=!1;else if(da)aa.innerHTML=da;else{ca=ca||{};da=0;for(var la in ca)da+=ca[la].length;0==ha.length&&0==da?aa.innerHTML=mxUtils.htmlEntities(mxResources.get(\"noDiagrams\")):C(ha,!1,Q,0==da?null:ca)}};J(N);var xa=null;mxEvent.addListener(Na,", "label": 1, "label_name": "safe"} -{"code": "function parseUrl(url, normalize = false) {\n if (typeof url !== \"string\" || !url.trim()) {\n throw new Error(\"Invalid url.\")\n }\n if (normalize) {\n if (typeof normalize !== \"object\") {\n normalize = {\n stripHash: false\n }\n }\n url = normalizeUrl(url, normalize)\n }\n const parsed = parsePath(url)\n return parsed;\n}", "label": 0, "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, "label_name": "vulnerable"} -{"code": " public function testProcess()\n {\n $container = new ContainerBuilder();\n $container->register('parent', 'foo')->setArguments(array('moo', 'b'))->setProperty('foo', 'moo');\n $container->setDefinition('child', new DefinitionDecorator('parent'))\n ->replaceArgument(0, 'a')\n ->setProperty('foo', 'bar')\n ->setClass('bar')\n ;\n\n $this->process($container);\n\n $def = $container->getDefinition('child');\n $this->assertNotInstanceOf('Symfony\\Component\\DependencyInjection\\DefinitionDecorator', $def);\n $this->assertEquals('bar', $def->getClass());\n $this->assertEquals(array('a', 'b'), $def->getArguments());\n $this->assertEquals(array('foo' => 'bar'), $def->getProperties());\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\tforeach ($oBlock->getSelectors() as $oSelector) {\n\t\t\t\tif ($sSpecificitySearch === null) {\n\t\t\t\t\t$aResult[] = $oSelector;\n\t\t\t\t} else {\n\t\t\t\t\t$sComparison = \"\\$bRes = {$oSelector->getSpecificity()} $sSpecificitySearch;\";\n\t\t\t\t\teval($sComparison);\n\t\t\t\t\tif ($bRes) {\n\t\t\t\t\t\t$aResult[] = $oSelector;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function confirm() {\n global $db;\n \n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash=\"'.$this->params['key'].'\"');\n if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // activate this users pending subscriptions\n $sub = new stdClass();\n $sub->enabled = 1;\n $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);\n \n // find the users active subscriptions\n $ealerts = expeAlerts::getBySubscriber($id);\n assign_to_template(array(\n 'ealerts'=>$ealerts\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "export default async function email(\n identifier: string,\n options: InternalOptions<\"email\">\n) {\n const { url, adapter, provider, logger, callbackUrl } = options\n\n // Generate token\n const token =\n (await provider.generateVerificationToken?.()) ??", "label": 0, "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, "label_name": "vulnerable"} -{"code": " public static function navtojson() {\r\n return json_encode(self::navhierarchy());\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public static final String getRevision() {\n return \"a\";\n }", "label": 0, "label_name": "vulnerable"} -{"code": "a;return this},removeAttribute:function(){var a=function(a){this.$.removeAttribute(a)};return CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.ie6Compat)?function(a){a==\"class\"?a=\"className\":a==\"tabindex\"?a=\"tabIndex\":a==\"contenteditable\"&&(a=\"contentEditable\");this.$.removeAttribute(a)}:a}(),removeAttributes:function(a){if(CKEDITOR.tools.isArray(a))for(var b=0;btree)\n\t\t\tadd_pending_tree(revs, commit->tree);\n\t\tshow_commit(commit, data);\n\t}\n\tfor (i = 0; i < revs->pending.nr; i++) {\n\t\tstruct object_array_entry *pending = revs->pending.objects + i;\n\t\tstruct object *obj = pending->item;\n\t\tconst char *name = pending->name;\n\t\tconst char *path = pending->path;\n\t\tif (obj->flags & (UNINTERESTING | SEEN))\n\t\t\tcontinue;\n\t\tif (obj->type == OBJ_TAG) {\n\t\t\tobj->flags |= SEEN;\n\t\t\tshow_object(obj, name, data);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!path)\n\t\t\tpath = \"\";\n\t\tif (obj->type == OBJ_TREE) {\n\t\t\tprocess_tree(revs, (struct tree *)obj, show_object,\n\t\t\t\t &base, path, data);\n\t\t\tcontinue;\n\t\t}\n\t\tif (obj->type == OBJ_BLOB) {\n\t\t\tprocess_blob(revs, (struct blob *)obj, show_object,\n\t\t\t\t &base, path, data);\n\t\t\tcontinue;\n\t\t}\n\t\tdie(\"unknown pending object %s (%s)\",\n\t\t oid_to_hex(&obj->oid), name);\n\t}\n\tobject_array_clear(&revs->pending);\n\tstrbuf_release(&base);\n}", "label": 1, "label_name": "safe"} -{"code": "\"setEndAt\"](a,c?CKEDITOR.POSITION_AFTER_START:CKEDITOR.POSITION_BEFORE_END);d=new CKEDITOR.dom.walker(d);d.evaluator=e(c);return d[c?\"checkBackward\":\"checkForward\"]()},checkStartOfBlock:function(){var b=this.startContainer,c=this.startOffset;if(CKEDITOR.env.ie&&c&&b.type==CKEDITOR.NODE_TEXT){b=CKEDITOR.tools.ltrim(b.substring(0,c));m.test(b)&&this.trim(0,1)}this.trim();b=new CKEDITOR.dom.elementPath(this.startContainer,this.root);c=this.clone();c.collapse(true);c.setStartAt(b.block||b.blockLimit,\nCKEDITOR.POSITION_AFTER_START);b=new CKEDITOR.dom.walker(c);b.evaluator=a();return b.checkBackward()},checkEndOfBlock:function(){var b=this.endContainer,c=this.endOffset;if(CKEDITOR.env.ie&&b.type==CKEDITOR.NODE_TEXT){b=CKEDITOR.tools.rtrim(b.substring(c));m.test(b)&&this.trim(1,0)}this.trim();b=new CKEDITOR.dom.elementPath(this.endContainer,this.root);c=this.clone();c.collapse(false);c.setEndAt(b.block||b.blockLimit,CKEDITOR.POSITION_BEFORE_END);b=new CKEDITOR.dom.walker(c);b.evaluator=a();return b.checkForward()},", "label": 1, "label_name": "safe"} -{"code": "\t\t\tupdateDroppable = function() {\n\t\t\t\ttree.find('.'+navdir+':not(.'+droppable+',.elfinder-ro,.elfinder-na)').droppable(droppableopts);\n\t\t\t},", "label": 0, "label_name": "vulnerable"} -{"code": " it 'create lowercase all privs' do\n pp = <<-EOS\n mysql_grant { 'lowercase@localhost/*.*':\n user => 'lowercase@localhost',\n privileges => 'all',\n table => '*.*',\n }\n EOS\n\n expect(apply_manifest(pp, :catch_failures => true).exit_code).to eq(0)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " private static CharSequenceMap toLowercaseMap(Iterator valuesIter,\n int arraySizeHint) {\n final CharSequenceMap result = new CharSequenceMap(arraySizeHint);\n\n while (valuesIter.hasNext()) {\n final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();\n try {\n int index = lowerCased.forEachByte(FIND_COMMA);\n if (index != -1) {\n int start = 0;\n do {\n result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);\n start = index + 1;\n } while (start < lowerCased.length() &&\n (index = lowerCased.forEachByte(start,\n lowerCased.length() - start, FIND_COMMA)) != -1);\n result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);\n } else {\n result.add(lowerCased.trim(), EMPTY_STRING);\n }\n } catch (Exception e) {\n // This is not expect to happen because FIND_COMMA never throws but must be caught\n // because of the ByteProcessor interface.\n throw new IllegalStateException(e);\n }\n }\n return result;\n }", "label": 1, "label_name": "safe"} -{"code": " public static function _date2timestamp( $datetime, $wtz=null ) {\n if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;\n if( !isset( $datetime['min'] )) $datetime['min'] = 0;\n if( !isset( $datetime['sec'] )) $datetime['sec'] = 0;\n if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty( $datetime['tz'] )))\n return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\n $output = $offset = 0;\n if( empty( $wtz )) {\n if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {\n $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;\n $wtz = 'UTC';\n }\n else\n $wtz = $datetime['tz'];\n }\n if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))\n $wtz = 'UTC';\n try {\n $strdate = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );\n $d = new DateTime( $strdate, new DateTimeZone( $wtz ));\n if( 0 != $offset ) // adjust for offset\n $d->modify( $offset.' seconds' );\n $output = $d->format( 'U' );\n unset( $d );\n }\n catch( Exception $e ) {\n $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\n }\n return $output;\n }", "label": 1, "label_name": "safe"} -{"code": " static function isSearchable() { return true; }\r", "label": 0, "label_name": "vulnerable"} -{"code": "static int oidc_session_redirect_parent_window_to_logout(request_rec *r,\n\t\toidc_cfg *c) {\n\n\toidc_debug(r, \"enter\");\n\n\tchar *java_script = apr_psprintf(r->pool,\n\t\t\t\" \\n\", oidc_get_redirect_uri(r, c));\n\n\treturn oidc_util_html_send(r, \"Redirecting...\", java_script, NULL, NULL,\n\t\t\tOK);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "this.graph.getTooltip(c,d,e,f);this.show(k,e,f);this.state=c;this.node=d;this.stateSource=g}}),this.delay)}};mxTooltipHandler.prototype.hide=function(){this.resetTimer();this.hideTooltip()};mxTooltipHandler.prototype.hideTooltip=function(){null!=this.div&&(this.div.style.visibility=\"hidden\",this.div.innerHTML=\"\")};", "label": 0, "label_name": "vulnerable"} -{"code": "func (f *flight4TestMockFlightConn) setLocalEpoch(epoch uint16) {}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public function load($array_of_ids) {\n foreach ($array_of_ids as $id) {\n $this->ids[$id] = true;\n }\n }", "label": 1, "label_name": "safe"} -{"code": " def self.get_for(user_id, date_s)\n\n SqlHelper.validate_token([user_id, date_s])\n begin\n con = \"(user_id=#{user_id.to_i}) and (date='#{date_s}')\"\n return Timecard.where(con).first\n rescue\n end\n return nil\n end", "label": 1, "label_name": "safe"} -{"code": "int generic_permission(struct inode *inode, int mask)\n{\n\tint ret;\n\n\t/*\n\t * Do the basic permission checks.\n\t */\n\tret = acl_permission_check(inode, mask);\n\tif (ret != -EACCES)\n\t\treturn ret;\n\n\tif (S_ISDIR(inode->i_mode)) {\n\t\t/* DACs are overridable for directories */\n\t\tif (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))\n\t\t\treturn 0;\n\t\tif (!(mask & MAY_WRITE))\n\t\t\tif (capable_wrt_inode_uidgid(inode,\n\t\t\t\t\t\t CAP_DAC_READ_SEARCH))\n\t\t\t\treturn 0;\n\t\treturn -EACCES;\n\t}\n\t/*\n\t * Read/write DACs are always overridable.\n\t * Executable DACs are overridable when there is\n\t * at least one exec bit set.\n\t */\n\tif (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))\n\t\tif (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))\n\t\t\treturn 0;\n\n\t/*\n\t * Searching includes executable on directories, else just read.\n\t */\n\tmask &= MAY_READ | MAY_WRITE | MAY_EXEC;\n\tif (mask == MAY_READ)\n\t\tif (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH))\n\t\t\treturn 0;\n\n\treturn -EACCES;\n}", "label": 1, "label_name": "safe"} -{"code": " public TSet readSetBegin() throws TException {\n byte type = readByte();\n int size = readI32();\n ensureContainerHasEnough(size, type);\n return new TSet(type, size);\n }", "label": 1, "label_name": "safe"} -{"code": " from: { name: globalDb.getServerTitle(), address: db.getReturnAddress() },\n subject: subject,\n text: text,\n };\n\n sendEmail(sendOptions);\n};", "label": 1, "label_name": "safe"} -{"code": " def self.on_desktop?(user, xtype, target_id)\n\n return false if user.nil? or xtype.nil? or target_id.nil?\n\n SqlHelper.validate_token([xtype, target_id])\n\n con = \"(user_id=#{user.id}) and (xtype='#{xtype}') and (target_id=#{target_id.to_i})\"\n\n begin\n toy = Toy.where(con).first\n rescue => evar\n Log.add_error(nil, evar)\n end\n\n return (!toy.nil?)\n end", "label": 1, "label_name": "safe"} -{"code": " public function testRemoveNbspExceptionsSpecial()\n {\n $this->config->set('AutoFormat.RemoveEmpty.RemoveNbsp', true);\n $this->config->set('AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions', 'b');\n $this->assertResult(' ', \"\\xC2\\xA0\");\n }", "label": 1, "label_name": "safe"} -{"code": " public function filter(&$uri, $config, $context)\n {\n foreach ($this->blacklist as $blacklisted_host_fragment) {\n if (strpos($uri->host, $blacklisted_host_fragment) !== false) {\n return false;\n }\n }\n return true;\n }", "label": 1, "label_name": "safe"} -{"code": " it \"raises an error when trying to download a local file\" do\n expect { subject.download('/etc/passwd') }.to raise_error(CarrierWave::DownloadError)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " protected function getInternalTaskLink(array $task)\n {\n $link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n if ($link['task_id'] != $task['id']) {\n throw new AccessForbiddenException();\n }\n\n return $link;\n }", "label": 1, "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, "label_name": "safe"} -{"code": "static pj_status_t pjsip_auth_verify( const pjsip_authorization_hdr *hdr,\n\t\t\t\t const pj_str_t *method,\n\t\t\t\t const pjsip_cred_info *cred_info )\n{\n if (pj_stricmp(&hdr->scheme, &pjsip_DIGEST_STR) == 0) {\n\tchar digest_buf[PJSIP_MD5STRLEN];\n\tpj_str_t digest;\n\tpj_status_t status;\n\tconst pjsip_digest_credential *dig = &hdr->credential.digest;\n\n\t/* Check that username and realm match. \n\t * These checks should have been performed before entering this\n\t * function.\n\t */\n\tPJ_ASSERT_RETURN(pj_strcmp(&dig->username, &cred_info->username) == 0,\n\t\t\t PJ_EINVALIDOP);\n\tPJ_ASSERT_RETURN(pj_strcmp(&dig->realm, &cred_info->realm) == 0,\n\t\t\t PJ_EINVALIDOP);\n\n\t/* Prepare for our digest calculation. */\n\tdigest.ptr = digest_buf;\n\tdigest.slen = PJSIP_MD5STRLEN;\n\n\t/* Create digest for comparison. */\n\tstatus = pjsip_auth_create_digest(&digest, \n\t\t\t\t &hdr->credential.digest.nonce,\n\t\t\t\t &hdr->credential.digest.nc, \n\t\t\t\t &hdr->credential.digest.cnonce,\n\t\t\t\t &hdr->credential.digest.qop,\n\t\t\t\t &hdr->credential.digest.uri,\n\t\t\t\t &cred_info->realm,\n\t\t\t\t cred_info, \n\t\t\t\t method );\n\n\tif (status != PJ_SUCCESS)\n\t return status;\n\n\t/* Compare digest. */\n\treturn (pj_stricmp(&digest, &hdr->credential.digest.response) == 0) ?\n\t PJ_SUCCESS : PJSIP_EAUTHINVALIDDIGEST;\n\n } else {\n\tpj_assert(!\"Unsupported authentication scheme\");\n\treturn PJSIP_EINVALIDAUTHSCHEME;\n }\n}", "label": 1, "label_name": "safe"} -{"code": "\"checked\"),M.style.visibility=\"visible\"):A.setAttribute(\"checked\",\"checked\")):l=null}else l=null}catch(I){}v.style=x+(l?l:u());v.vertex=!0;k.addCell(v,null,null,null,null);k.selectAll();k.addListener(mxEvent.CELLS_MOVED,B);k.addListener(mxEvent.CELLS_RESIZED,B);var X=k.graphHandler.mouseUp,p=k.graphHandler.mouseDown;k.graphHandler.mouseUp=function(){X.apply(this,arguments);g.style.backgroundColor=\"#fff9\"};k.graphHandler.mouseDown=function(){p.apply(this,arguments);g.style.backgroundColor=\"\"};k.dblClick=", "label": 0, "label_name": "vulnerable"} -{"code": "test_compressed_stream_overflow (xd3_stream *stream, int ignore)\n{\n int ret;\n int i;\n uint8_t *buf;\n\n if ((buf = (uint8_t*) malloc (TWO_MEGS_AND_DELTA)) == NULL) { return ENOMEM; }\n\n memset (buf, 0, TWO_MEGS_AND_DELTA);\n for (i = 0; i < (2 << 20); i += 256) \n {\n int j;\n int off = mt_random(& static_mtrand) % 10;\n for (j = 0; j < 256; j++) \n\t{\n\t buf[i + j] = j + off;\n\t}\n }\n\n /* Test overflow of a 32-bit file offset. */\n if (SIZEOF_XOFF_T == 4)\n {\n ret = test_streaming (stream, buf, buf + (1 << 20), buf + (2 << 20), (1 << 12) + 1);\n\n if (ret == XD3_INVALID_INPUT && MSG_IS (\"decoder file offset overflow\"))\n\t{\n\t ret = 0;\n\t}\n else\n\t{\n XPR(NT XD3_LIB_ERRMSG (stream, ret));\n\t stream->msg = \"expected overflow condition\";\n\t ret = XD3_INTERNAL;\n\t goto fail;\n\t}\n }\n\n /* Test transfer of exactly 32bits worth of data. */\n if ((ret = test_streaming (stream, \n\t\t\t buf, \n\t\t\t buf + (1 << 20), \n\t\t\t buf + (2 << 20), \n\t\t\t 1 << 12))) \n {\n goto fail;\n }\n fail:\n free (buf);\n return ret;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function getPopular() {\r\n $url = \"http://api.themoviedb.org/3/movie/popular?api_key=\".$this->apikey;\r\n $popular = $this->curl($url);\r\n return $popular;\r\n }\r", "label": 1, "label_name": "safe"} -{"code": "static char *clean_path(char *path)\n{\n\tchar *ch;\n\tchar *ch2;\n\tchar *str;\n\tstr = xmalloc(strlen(path) + 1);\n\tch = path;\n\tch2 = str;\n\twhile (true) {\n\t\t*ch2 = *ch;\n\t\tch++;\n\t\tch2++;\n\t\tif (!*(ch-1))\n\t\t\tbreak;\n\t\twhile (*(ch - 1) == '/' && *ch == '/')\n\t\t\tch++;\n\t}\n\t/* get rid of trailing / characters */\n\twhile ((ch = strrchr(str, '/'))) {\n\t\tif (ch == str)\n\t\t\tbreak;\n\t\tif (!*(ch+1))\n\t\t\t*ch = 0;\n\t\telse\n\t\t\tbreak;\n\t}\n\treturn str;\n}", "label": 1, "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,\ny){q=null!=q?q:!0;var A=document.createElement(\"input\");A.style.marginRight=\"8px\";A.style.marginTop=\"16px\";A.setAttribute(\"type\",x?\"radio\":\"checkbox\");x=\"geCheckbox-\"+Editor.guid();A.id=x;null!=y&&A.setAttribute(\"name\",y);k&&(A.setAttribute(\"checked\",\"checked\"),A.defaultChecked=!0);l&&A.setAttribute(\"disabled\",\"disabled\");q&&(d.appendChild(A),k=document.createElement(\"label\"),mxUtils.write(k,g),k.setAttribute(\"for\",x),d.appendChild(k),p||mxUtils.br(d));return A};EditorUi.prototype.addEditButton=function(d,", "label": 1, "label_name": "safe"} -{"code": "static int snd_seq_ioctl_create_port(struct snd_seq_client *client, void *arg)\n{\n\tstruct snd_seq_port_info *info = arg;\n\tstruct snd_seq_client_port *port;\n\tstruct snd_seq_port_callback *callback;\n\tint port_idx;\n\n\t/* it is not allowed to create the port for an another client */\n\tif (info->addr.client != client->number)\n\t\treturn -EPERM;\n\n\tport = snd_seq_create_port(client, (info->flags & SNDRV_SEQ_PORT_FLG_GIVEN_PORT) ? info->addr.port : -1);\n\tif (port == NULL)\n\t\treturn -ENOMEM;\n\n\tif (client->type == USER_CLIENT && info->kernel) {\n\t\tport_idx = port->addr.port;\n\t\tsnd_seq_port_unlock(port);\n\t\tsnd_seq_delete_port(client, port_idx);\n\t\treturn -EINVAL;\n\t}\n\tif (client->type == KERNEL_CLIENT) {\n\t\tif ((callback = info->kernel) != NULL) {\n\t\t\tif (callback->owner)\n\t\t\t\tport->owner = callback->owner;\n\t\t\tport->private_data = callback->private_data;\n\t\t\tport->private_free = callback->private_free;\n\t\t\tport->event_input = callback->event_input;\n\t\t\tport->c_src.open = callback->subscribe;\n\t\t\tport->c_src.close = callback->unsubscribe;\n\t\t\tport->c_dest.open = callback->use;\n\t\t\tport->c_dest.close = callback->unuse;\n\t\t}\n\t}\n\n\tinfo->addr = port->addr;\n\n\tsnd_seq_set_port_info(port, info);\n\tsnd_seq_system_client_ev_port_start(port->addr.client, port->addr.port);\n\tsnd_seq_port_unlock(port);\n\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": " public SAXReader(XMLReader xmlReader) {\n this.xmlReader = xmlReader;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t$prepared = $eml->prepareBody();\n\t\t}\n\n if (!$prepared) { // InlineEmail failed validation\n $errors = $eml->getErrors ();\n return array (false, array_shift ($errors));\n }\n\n list ($success, $message) = $this->checkDoNotEmailFields ($eml);\n if (!$success) {\n return array ($success, $message);\n }\n\n\t\t$result = $eml->send($historyFlag);\n\t\tif (isset($result['code']) && $result['code'] == 200) {\n if (YII_UNIT_TESTING) {\n return array(true, $eml->message);\n } else {\n return array(true, \"\");\n }\n } else {\n return array (false, Yii::t('app', \"Email could not be sent\"));\n }\n\t}", "label": 1, "label_name": "safe"} -{"code": "void InferenceContext::PreInputInit(\n const OpDef& op_def, const std::vector& input_tensors,\n const std::vector& input_tensors_as_shapes) {\n // TODO(mdan): This is also done at graph construction. Run only here instead?\n const auto ret = full_type::SpecializeType(attrs_, op_def);\n DCHECK(ret.status().ok()) << \"while instantiating types: \" << ret.status();\n ret_types_ = ret.ValueOrDie();\n\n input_tensors_ = input_tensors;\n input_tensors_as_shapes_ = input_tensors_as_shapes;\n\n construction_status_ =\n NameRangesForNode(attrs_, op_def, &input_name_map_, &output_name_map_);\n if (!construction_status_.ok()) return;\n\n int num_outputs = 0;\n for (const auto& e : output_name_map_) {\n num_outputs = std::max(num_outputs, e.second.second);\n }\n outputs_.assign(num_outputs, nullptr);\n output_handle_shapes_and_types_.resize(num_outputs);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def test_without_crlf(self):\n data = \"Echo\\r\\nthis\\r\\nplease\"\n s = tobytes(\n \"GET / HTTP/1.0\\r\\n\"\n \"Connection: close\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\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": 1, "label_name": "safe"} -{"code": " public void preflightCheckNegative() {\n String origin = \"http://bla.com\";\n String headers =\"X-Data: Test\";\n expect(backend.isOriginAllowed(origin,false)).andReturn(false);\n replay(backend);\n\n Map ret = handler.handleCorsPreflightRequest(origin, headers);\n assertNull(ret.get(\"Access-Control-Allow-Origin\"));\n }", "label": 1, "label_name": "safe"} -{"code": "\t\t\t$text = str_replace( $variable, $replacement, $text );\n\t\t}\n\n\t\treturn $text;\n\t}", "label": 1, "label_name": "safe"} -{"code": " public static function versionReport()\n {\n $v = self::latestVersion();\n\n $html = \"\n
\n Warning: Your CMS version is different with our latest version ($v).\n Please upgrade your system.\n
\n \";\n\n return $html;\n }", "label": 1, "label_name": "safe"} -{"code": " public function IsQmail() {\n if (stristr(ini_get('sendmail_path'), 'qmail')) {\n $this->Sendmail = '/var/qmail/bin/sendmail';\n }\n $this->Mailer = 'sendmail';\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testStreaming()\n {\n $req = new HTTP_Request2(null, HTTP_Request2::METHOD_POST);\n $body = $req->addPostParameter('foo', 'I am a parameter')\n ->addUpload('upload', dirname(dirname(__FILE__)) . '/_files/plaintext.txt')\n ->getBody();\n $asString = '';\n while ($part = $body->read(10)) {\n $asString .= $part;\n }\n $this->assertEquals($body->getLength(), strlen($asString));\n $this->assertContains('This is a test.', $asString);\n $this->assertContains('I am a parameter', $asString);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " override func setUp() {\n super.setUp()\n \n let stream = stubProvider.videoStream().stream\n sut = SelfVideoPreviewView(stream: stream, isCovered: false, shouldShowActiveSpeakerFrame: false)\n sut.previewView = previewViewMock\n }", "label": 1, "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, "label_name": "safe"} -{"code": "MagickExport int LocaleLowercase(const int c)\n{\n#if defined(MAGICKCORE_LOCALE_SUPPORT)\n if (c_locale != (locale_t) NULL)\n return(tolower_l((int) ((unsigned char) c),c_locale));\n#endif\n return(tolower((int) ((unsigned char) c)));\n}", "label": 1, "label_name": "safe"} -{"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, _err = utils.execute('readlink', '-nm',\n os.path.join(fs, *args),\n run_as_root=True)\n if not absolute_path.startswith(os.path.realpath(fs) + '/'):\n raise exception.Invalid(_('injected file path not valid'))\n return absolute_path", "label": 1, "label_name": "safe"} -{"code": " public DesktopFrame GetLatestFrame()\n {\n var frame = new DesktopFrame();\n // Try to get the latest frame; this may timeout\n var retrievalTimedOut = RetrieveFrame();\n if (retrievalTimedOut)\n return null;\n try\n {\n RetrieveFrameMetadata(frame);\n //we don't need cursor info\n //RetrieveCursorMetadata(frame);\n //we dont need a full frame\n //ProcessFrame(frame);\n }\n catch\n {\n ReleaseFrame();\n }\n try\n {\n ReleaseFrame();\n }\n catch\n {\n // throw new DesktopDuplicationException(\"Couldn't release frame.\"); \n }\n return frame;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "!1;this.executeLayout(function(){za.execute(H.getDefaultParent(),ma);H.moveCells(ma,N,W)},!0,u);u=null}else if(\"organic\"==P||\"auto\"==P&&ma.length>y.length){H.view.validate();var wa=new mxFastOrganicLayout(H);wa.forceConstant=3*fa;wa.disableEdgeStyle=!1;wa.resetEdges=!1;var Ea=wa.isVertexIgnored;wa.isVertexIgnored=function(Da){return Ea.apply(this,arguments)||0>mxUtils.indexOf(y,Da)};this.executeLayout(function(){wa.execute(H.getDefaultParent());Fa()},!0,u);u=null}}this.hideDialog()}finally{H.model.endUpdate()}null!=\nu&&u()}}catch(Da){this.handleError(Da)}};EditorUi.prototype.getSearch=function(d){var f=\"\";if(\"1\"!=urlParams.offline&&\"1\"!=urlParams.demo&&null!=d&&0mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+\"=\"+urlParams[m],g=\"&\")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0data ) ) {\n\t\t\tif ( array_key_exists( 'default', $this->data[$parameter] ) ) {\n\t\t\t\treturn (bool)$this->data[$parameter]['default'];\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\tthrow new MWException( __METHOD__ . \": Attempted to load a parameter that does not exist.\" );\n\t}", "label": 1, "label_name": "safe"} -{"code": " def reactions_given\n params.require(:username)\n user = fetch_user_from_params(include_inactive: current_user.try(:staff?) || (current_user && SiteSetting.show_inactive_accounts))\n raise Discourse::NotFound unless guardian.can_see_profile?(user)\n\n reaction_users = DiscourseReactions::ReactionUser\n .joins(:reaction, :post)\n .includes(:user, :post, :reaction)\n .where(user_id: user.id)\n .where('discourse_reactions_reactions.reaction_users_count IS NOT NULL')\n\n if params[:before_reaction_user_id]\n reaction_users = reaction_users\n .where('discourse_reactions_reaction_users.id < ?', params[:before_reaction_user_id].to_i)\n end\n\n reaction_users = reaction_users\n .order(created_at: :desc)\n .limit(20)\n\n render_serialized(reaction_users.to_a, UserReactionSerializer)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should convert string 'undef' to false\" do\n result = scope.function_str2bool([\"undef\"])\n expect(result).to(eq(false))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " $body = str_replace(array(\"\\n\"), \"
\", $body);\r\n } else {\r\n // It's going elsewhere (doesn't like quoted-printable)\r\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\r\n }\r\n $title = $items[$i]->title;\r\n\r\n $msg .= \"BEGIN:VEVENT\\n\";\r\n $msg .= $dtstart . $dtend;\r\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\r\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\r\n if ($title) {\r\n $msg .= \"SUMMARY:$title\\n\";\r\n }\r\n if ($body) {\r\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\r\n }\r\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\r\n if (!empty($this->config['usecategories'])) {\r\n if (!empty($items[$i]->expCat[0]->title)) {\r\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\r\n } else {\r\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\r\n }\r\n }\r\n $msg .= \"END:VEVENT\\n\";\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public byte[] newIv() {\n return newIv(DEFAULT_IV_LENGTH);\n }", "label": 1, "label_name": "safe"} -{"code": " public async Task UpdateListBySeries(UpdateReadingListBySeriesDto dto)\n {\n var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());\n var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);\n if (readingList == null) return BadRequest(\"Reading List does not exist\");\n var chapterIdsForSeries =\n await _unitOfWork.SeriesRepository.GetChapterIdsForSeriesAsync(new [] {dto.SeriesId});\n\n // If there are adds, tell tracking this has been modified\n if (await AddChaptersToReadingList(dto.SeriesId, chapterIdsForSeries, readingList))\n {\n _unitOfWork.ReadingListRepository.Update(readingList);\n }\n\n try\n {\n if (_unitOfWork.HasChanges())\n {\n await _unitOfWork.CommitAsync();\n return Ok(\"Updated\");\n }\n }\n catch\n {\n await _unitOfWork.RollbackAsync();\n }\n\n return Ok(\"Nothing to do\");\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected function getColumn(array $project)\n {\n $column = $this->columnModel->getById($this->request->getIntegerParam('column_id'));\n\n if (empty($column)) {\n throw new PageNotFoundException();\n }\n\n if ($column['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n return $column;\n }", "label": 1, "label_name": "safe"} -{"code": "const hasStoreApiRouteChanges = () => {\n for (let file of danger.git.modified_files) {\n if (file.includes('SalesChannel') && file.includes('Route.php') && !file.includes('/Test/')) {\n return true;\n }\n }\n\n for (let file of danger.git.created_files) {\n if (file.includes('SalesChannel') && file.includes('Route.php') && !file.includes('/Test/')) {\n return true;\n }\n }\n\n return false;\n}", "label": 1, "label_name": "safe"} -{"code": " it 'validates an multiple arguments' do\n pp = <<-EOS\n $one = ['a', 'b']\n $two = [['c'], 'd']\n validate_array($one,$two)\n EOS\n\n apply_manifest(pp, :catch_failures => true)\n end", "label": 0, "label_name": "vulnerable"} -{"code": "static int _TIFFGetMaxColorChannels( uint16 photometric )\n{\n switch (photometric) {\n\tcase PHOTOMETRIC_PALETTE:\n\tcase PHOTOMETRIC_MINISWHITE:\n\tcase PHOTOMETRIC_MINISBLACK:\n return 1;\n\tcase PHOTOMETRIC_YCBCR:\n\tcase PHOTOMETRIC_RGB:\n\tcase PHOTOMETRIC_CIELAB:\n return 3;\n\tcase PHOTOMETRIC_SEPARATED:\n\tcase PHOTOMETRIC_MASK:\n return 4;\n\tcase PHOTOMETRIC_LOGL:\n\tcase PHOTOMETRIC_LOGLUV:\n\tcase PHOTOMETRIC_CFA:\n\tcase PHOTOMETRIC_ITULAB:\n\tcase PHOTOMETRIC_ICCLAB:\n\tdefault:\n return 0;\n }\n}", "label": 1, "label_name": "safe"} -{"code": " public function __construct()\n {\n parent::__construct();\n if ($GLOBALS['HTMLPurifierTest']['PH5P']) {\n require_once 'HTMLPurifier/Lexer/PH5P.php';\n }\n }", "label": 1, "label_name": "safe"} -{"code": " it \"should exist\" do\n expect(Puppet::Parser::Functions.function(\"empty\")).to eq(\"function_empty\")\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public boolean verify(final String host, final String certHostname) {\n return certHostname != null && !certHostname.isEmpty();\n }", "label": 1, "label_name": "safe"} -{"code": "void AnnotateRWLockDestroy(const char *file, int line,\n const volatile void *lock){}", "label": 0, "label_name": "vulnerable"} -{"code": "function Dot(runner) {\n Base.call(this, runner);\n\n var self = this\n , stats = this.stats\n , width = Base.window.width * .75 | 0\n , n = 0;\n\n runner.on('start', function(){\n process.stdout.write('\\n ');\n });\n\n runner.on('pending', function(test){\n process.stdout.write(color('pending', Base.symbols.dot));\n });\n\n runner.on('pass', function(test){\n if (++n % width == 0) process.stdout.write('\\n ');\n if ('slow' == test.speed) {\n process.stdout.write(color('bright yellow', Base.symbols.dot));\n } else {\n process.stdout.write(color(test.speed, Base.symbols.dot));\n }\n });\n\n runner.on('fail', function(test, err){\n if (++n % width == 0) process.stdout.write('\\n ');\n process.stdout.write(color('fail', Base.symbols.dot));\n });\n\n runner.on('end', function(){\n console.log();\n self.epilogue();\n });\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def self.instances\n rabbitmqctl('list_vhosts').split(/\\n/)[1..-2].map do |line|\n if line =~ /^(\\S+)$/\n new(:name => $1)\n else\n raise Puppet::Error, \"Cannot parse invalid user line: #{line}\"\n end\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "static int snd_hrtimer_stop(struct snd_timer *t)\n{\n\tstruct snd_hrtimer *stime = t->private_data;\n\tatomic_set(&stime->running, 0);\n\thrtimer_try_to_cancel(&stime->hrt);\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": "lspci_process(STREAM s)\n{\n\tunsigned int pkglen;\n\tstatic char *rest = NULL;\n\tchar *buf;\n\tstruct stream packet = *s;\n\n\tif (!s_check(s))\n\t{\n\t\trdp_protocol_error(\"lspci_process(), stream is in unstable state\", &packet);\n\t}\n\n\tpkglen = s->end - s->p;\n\t/* str_handle_lines requires null terminated strings */\n\tbuf = xmalloc(pkglen + 1);\n\tSTRNCPY(buf, (char *) s->p, pkglen + 1);\n\tstr_handle_lines(buf, &rest, lspci_process_line, NULL);\n\txfree(buf);\n}", "label": 1, "label_name": "safe"} -{"code": " 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": 1, "label_name": "safe"} -{"code": "function generate_mock_once($name)\n{\n $mock_name = $name . 'Mock';\n if (class_exists($mock_name, false)) return false;\n Mock::generate($name, $mock_name);\n}", "label": 1, "label_name": "safe"} -{"code": " def remove_all\n delete = Protocol::Delete.new(\n operation.database,\n operation.collection,\n operation.selector\n )\n\n session.with(consistency: :strong) do |session|\n session.execute delete\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it { should contain_file('/var/lib/pgsql/data').with_ensure('directory') }", "label": 0, "label_name": "vulnerable"} -{"code": "static int uio_mmap_physical(struct vm_area_struct *vma)\n{\n\tstruct uio_device *idev = vma->vm_private_data;\n\tint mi = uio_find_mem_index(vma);\n\tstruct uio_mem *mem;\n\tif (mi < 0)\n\t\treturn -EINVAL;\n\tmem = idev->info->mem + mi;\n\n\tif (vma->vm_end - vma->vm_start > mem->size)\n\t\treturn -EINVAL;\n\n\tvma->vm_ops = &uio_physical_vm_ops;\n\tvma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);\n\n\t/*\n\t * We cannot use the vm_iomap_memory() helper here,\n\t * because vma->vm_pgoff is the map index we looked\n\t * up above in uio_find_mem_index(), rather than an\n\t * actual page offset into the mmap.\n\t *\n\t * So we just do the physical mmap without a page\n\t * offset.\n\t */\n\treturn remap_pfn_range(vma,\n\t\t\t vma->vm_start,\n\t\t\t mem->addr >> PAGE_SHIFT,\n\t\t\t vma->vm_end - vma->vm_start,\n\t\t\t vma->vm_page_prot);\n}", "label": 1, "label_name": "safe"} -{"code": " $contents = ['form' => tep_draw_form('status', 'orders_status.php', 'page=' . $_GET['page'] . '&action=insert')];", "label": 0, "label_name": "vulnerable"} -{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);\n expHistory::back();\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static PyObject *__pyx_pf_17clickhouse_driver_14bufferedwriter_14BufferedWriter_8flush(struct __pyx_obj_17clickhouse_driver_14bufferedwriter_BufferedWriter *__pyx_v_self) {\n PyObject *__pyx_r = NULL;\n __Pyx_RefNannyDeclarations\n PyObject *__pyx_t_1 = NULL;\n int __pyx_lineno = 0;\n const char *__pyx_filename = NULL;\n int __pyx_clineno = 0;\n __Pyx_RefNannySetupContext(\"flush\", 0);\n\n /* \"clickhouse_driver/bufferedwriter.pyx\":47\n * \n * def flush(self):\n * self.write_into_stream() # <<<<<<<<<<<<<<\n * \n * def write_strings(self, items, encoding=None):\n */\n __pyx_t_1 = ((struct __pyx_vtabstruct_17clickhouse_driver_14bufferedwriter_BufferedWriter *)__pyx_v_self->__pyx_vtab)->write_into_stream(__pyx_v_self, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 47, __pyx_L1_error)\n __Pyx_GOTREF(__pyx_t_1);\n __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;\n\n /* \"clickhouse_driver/bufferedwriter.pyx\":46\n * written += size\n * \n * def flush(self): # <<<<<<<<<<<<<<\n * self.write_into_stream()\n * \n */\n\n /* function exit code */\n __pyx_r = Py_None; __Pyx_INCREF(Py_None);\n goto __pyx_L0;\n __pyx_L1_error:;\n __Pyx_XDECREF(__pyx_t_1);\n __Pyx_AddTraceback(\"clickhouse_driver.bufferedwriter.BufferedWriter.flush\", __pyx_clineno, __pyx_lineno, __pyx_filename);\n __pyx_r = NULL;\n __pyx_L0:;\n __Pyx_XGIVEREF(__pyx_r);\n __Pyx_RefNannyFinishContext();\n return __pyx_r;\n}", "label": 1, "label_name": "safe"} -{"code": "asmlinkage void kernel_unaligned_trap(struct pt_regs *regs, unsigned int insn)\n{\n\tenum direction dir = decode_direction(insn);\n\tint size = decode_access_size(insn);\n\n\tif(!ok_for_kernel(insn) || dir == both) {\n\t\tprintk(\"Unsupported unaligned load/store trap for kernel at <%08lx>.\\n\",\n\t\t regs->pc);\n\t\tunaligned_panic(\"Wheee. Kernel does fpu/atomic unaligned load/store.\");\n\t} else {\n\t\tunsigned long addr = compute_effective_address(regs, insn);\n\t\tint err;\n\n\t\tperf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, addr);\n\t\tswitch (dir) {\n\t\tcase load:\n\t\t\terr = do_int_load(fetch_reg_addr(((insn>>25)&0x1f),\n\t\t\t\t\t\t\t regs),\n\t\t\t\t\t size, (unsigned long *) addr,\n\t\t\t\t\t decode_signedness(insn));\n\t\t\tbreak;\n\n\t\tcase store:\n\t\t\terr = do_int_store(((insn>>25)&0x1f), size,\n\t\t\t\t\t (unsigned long *) addr, regs);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpanic(\"Impossible kernel unaligned trap.\");\n\t\t\t/* Not reached... */\n\t\t}\n\t\tif (err)\n\t\t\tkernel_mna_trap_fault(regs, insn);\n\t\telse\n\t\t\tadvance(regs);\n\t}\n}", "label": 0, "label_name": "vulnerable"} -{"code": " private async Task TrySaveSubtitle(\n Video video,\n LibraryOptions libraryOptions,\n SubtitleResponse response)\n {\n var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia;\n\n using (var stream = response.Stream)\n using (var memoryStream = new MemoryStream())\n {\n await stream.CopyToAsync(memoryStream).ConfigureAwait(false);\n memoryStream.Position = 0;\n\n var savePaths = new List();\n var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + \".\" + response.Language.ToLowerInvariant();\n\n if (response.IsForced)\n {\n saveFileName += \".forced\";\n }\n\n saveFileName += \".\" + response.Format.ToLowerInvariant();\n\n if (saveInMediaFolder)\n {\n var mediaFolderPath = Path.GetFullPath(Path.Combine(video.ContainingFolderPath, saveFileName));\n // TODO: Add some error handling to the API user: return BadRequest(\"Could not save subtitle, bad path.\");\n if (mediaFolderPath.StartsWith(video.ContainingFolderPath))\n {\n savePaths.Add(mediaFolderPath);\n }\n }\n\n var internalPath = Path.GetFullPath(Path.Combine(video.GetInternalMetadataPath(), saveFileName));\n\n // TODO: Add some error to the user: return BadRequest(\"Could not save subtitle, bad path.\");\n if (internalPath.StartsWith(video.GetInternalMetadataPath()))\n {\n savePaths.Add(internalPath);\n }\n\n if (savePaths.Count > 0)\n {\n await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false);\n }\n else\n {\n _logger.LogError(\"An uploaded subtitle could not be saved because the resulting paths were invalid.\");\n }\n }\n }", "label": 1, "label_name": "safe"} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // Check that the inputs and outputs have the right sizes and types.\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output_values = GetOutput(context, node, kOutputValues);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output_values->type);\n\n const TfLiteTensor* top_k = GetInput(context, node, kInputTopK);\n TF_LITE_ENSURE_TYPES_EQ(context, top_k->type, kTfLiteInt32);\n\n // Set output dynamic if the input is not const.\n if (IsConstantTensor(top_k)) {\n TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));\n } else {\n TfLiteTensor* output_indexes = GetOutput(context, node, kOutputIndexes);\n TfLiteTensor* output_values = GetOutput(context, node, kOutputValues);\n SetTensorToDynamic(output_indexes);\n SetTensorToDynamic(output_values);\n }\n return kTfLiteOk;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function setTextareaDimensions($cols = null, $rows = null)\n {\n if ($cols) {\n $this->fields['default']->cols = $cols;\n }\n if ($rows) {\n $this->fields['default']->rows = $rows;\n }\n }", "label": 1, "label_name": "safe"} -{"code": " def verify_signature(jwt)\n head = token_head(jwt)\n\n # Make sure the algorithm is supported and get the decode key.\n if head[:alg] == 'RS256'\n [rs256_decode_key(head[:kid]), head[:alg]]\n elsif head[:alg] == 'HS256'\n [@client_secret, head[:alg]]\n else\n raise OmniAuth::Auth0::TokenValidationError.new(\"Signature algorithm of #{head[:alg]} is not supported. Expected the ID token to be signed with RS256 or HS256\")\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public function test_removeComments()\n {\n $this->assertCleanCSS(\n\"\",\n\"div {\ntext-align:right\n}\"\n );\n }", "label": 1, "label_name": "safe"} -{"code": " it 'zips two arrays of numbers together and flattens them' do\n # XXX This only tests the argument `true`, even though the following are valid:\n # 1 t y true yes\n # 0 f n false no\n # undef undefined\n pp = <<-EOS\n $one = [1,2,3,4]\n $two = [5,6,7,8]\n $output = zip($one,$two,true)\n notice(inline_template('<%= @output.inspect %>'))\n EOS\n if is_future_parser_enabled?\n expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\\[1, 5, 2, 6, 3, 7, 4, 8\\]/)\n else\n expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\\[\"1\", \"5\", \"2\", \"6\", \"3\", \"7\", \"4\", \"8\"\\]/)\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def edit\n Log.add_info(request, params.inspect)\n\n date_s = params[:date]\n\n if date_s.nil? or date_s.empty?\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": 0, "label_name": "vulnerable"} -{"code": " protected List getRawCommandLine( String executable, String[] arguments )\n {\n List commandLine = new ArrayList();\n StringBuilder sb = new StringBuilder();\n\n if ( executable != null )\n {\n String preamble = getExecutionPreamble();\n if ( preamble != null )\n {\n sb.append( preamble );\n }\n\n if ( isQuotedExecutableEnabled() )\n {\n char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() );\n\n sb.append( StringUtils.quoteAndEscape( getExecutable(), getExecutableQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\\\', false ) );\n }\n else\n {\n sb.append( getExecutable() );\n }\n }\n for ( int i = 0; i < arguments.length; i++ )\n {\n if ( sb.length() > 0 )\n {\n sb.append( \" \" );\n }\n\n if ( isQuotedArgumentsEnabled() )\n {\n char[] escapeChars = getEscapeChars( isSingleQuotedArgumentEscaped(), isDoubleQuotedArgumentEscaped() );\n\n sb.append( StringUtils.quoteAndEscape( arguments[i], getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), getArgumentEscapePattern(), false ) );\n }\n else\n {\n sb.append( arguments[i] );\n }\n }\n\n commandLine.add( sb.toString() );\n\n return commandLine;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function setContainer($container, $type = Container::TYPE_TEXT)\n {\n $this->container = $container;\n $container->setType($type);\n }", "label": 1, "label_name": "safe"} -{"code": "def ban(bot, trigger):\n \"\"\"Ban a user from the channel. The bot must be a channel operator for this command to work.\"\"\"\n if ',' in str(parse_host_mask(trigger.group().split())):\n return bot.reply('Unable to ban. Banning multiple users is not allowed.')\n if '#' in str(parse_host_mask(trigger.group().split())):\n return bot.reply('Unable to ban. Use of # when banning is not expected.')\n makemodechange(bot, trigger, '+b', isbqmode=True)", "label": 1, "label_name": "safe"} -{"code": " def destroy\n FileUtils.rm_rf(@resource.value(:path))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " $masteroption->delete();\n }\n\n // delete the mastergroup\n $db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);\n $mastergroup->delete();\n\n expHistory::back();\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function approvedFileExtension($filename, $type = 'image')\n\t{\n\t\t$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));\n\t\tif ($type == 'image') {\n\t\t\tswitch ($ext) {\n\t\t\t\tcase 'gif':\n\t\t\t\tcase 'png':\n\t\t\t\tcase 'jpeg':\n\t\t\t\tcase 'jpg':\n\t\t\t\tcase 'svg':\n\t\t\t\t\treturn true;\n\t\t\t\tdefault:\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t} elseif ($type == 'cert') {\n\t\t\tswitch ($ext) {\n\t\t\t\tcase 'pem':\n\t\t\t\t\treturn true;\n\t\t\t\tdefault:\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "jas_iccprof_t *jas_iccprof_createfrombuf(jas_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": 1, "label_name": "safe"} -{"code": "resetType:function(){this.typing=!1;delete this.lastKeystroke;this.modifiersCount=this.typesCount=0},fireChange:function(){this.hasUndo=!!this.getNextImage(!0);this.hasRedo=!!this.getNextImage(!1);this.resetType();this.onChange()},save:function(a,c,d){if(this.locked)return!1;var b=this.snapshots;c||(c=new f(this.editor));if(!1===c.contents)return!1;if(this.currentImage)if(c.equalsContent(this.currentImage)){if(a||c.equalsSelection(this.currentImage))return!1}else this.editor.fire(\"change\");b.splice(this.index+", "label": 1, "label_name": "safe"} -{"code": "EditorUi.prototype.updateCssForMarker = function(markerDiv, prefix, shape, marker, fill)\n{\n\tmarkerDiv.style.verticalAlign = 'top';\n\tmarkerDiv.style.height = '21px';\n\tmarkerDiv.style.width = '21px';\n\tmarkerDiv.innerHTML = '';\n\n\tif (shape == 'flexArrow')\n\t{\n\t\tmarkerDiv.className = (marker != null && marker != mxConstants.NONE) ?\n\t\t\t'geSprite geSprite-' + prefix + 'blocktrans' : 'geSprite geSprite-noarrow';\n\t}\n\telse\n\t{\n\t\tvar src = this.getImageForMarker(marker, fill);\n\n\t\tif (src != null)\n\t\t{\n\t\t\tvar img = document.createElement('img');\n\t\t\timg.style.position = 'absolute';\n\t\t\timg.style.marginTop = '0.5px';\n\t\t\timg.setAttribute('src', src);\n\t\t\tmarkerDiv.className = '';\n\n\t\t\tif (prefix == 'end')\n\t\t\t{\n\t\t\t\tmxUtils.setPrefixedStyle(img.style, 'transform', 'scaleX(-1)');\n\t\t\t}\n\t\t\t\n\t\t\tif (Editor.isDarkMode())\n\t\t\t{\n\t\t\t\timg.style.filter = 'invert(100%)';\n\t\t\t}\t\n\n\t\t\tmarkerDiv.appendChild(img);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmarkerDiv.className = 'geSprite geSprite-noarrow';\n\t\t\tmarkerDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('none'));\n\t\t\tmarkerDiv.style.backgroundImage = 'none';\n\t\t\tmarkerDiv.style.verticalAlign = 'top';\n\t\t\tmarkerDiv.style.marginTop = '4px';\n\t\t\tmarkerDiv.style.fontSize = '10px';\n\t\t\tmarkerDiv.style.filter = 'none';\n\t\t\tmarkerDiv.style.color = this.defaultStrokeColor;\n\t\t\tmarkerDiv.nextSibling.style.marginTop = '0px';\n\t\t}\n\t}\n};", "label": 0, "label_name": "vulnerable"} -{"code": "_PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize)\n{\n size_t nbytes;\n assert(elsize == 0 || nelem <= PY_SSIZE_T_MAX / elsize);\n nbytes = nelem * elsize;\n return _PyMem_DebugRawAlloc(1, ctx, nbytes);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function copy($newpath)\n {\n if ($this->filesystem->copy($this->path, $newpath)) {\n return new File($this->filesystem, $newpath);\n }\n\n return false;\n }", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " it 'should escape the content of removed `xmp` elements' do\n Sanitize.fragment('hello! <script>alert(0)</script>')\n .must_equal 'hello! <script>alert(0)</script>'\n end", "label": 0, "label_name": "vulnerable"} -{"code": "func (mr *MockResourceOwnerPasswordCredentialsGrantStorageMockRecorder) GetRefreshTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetRefreshTokenSession\", reflect.TypeOf((*MockResourceOwnerPasswordCredentialsGrantStorage)(nil).GetRefreshTokenSession), arg0, arg1, arg2)\n}", "label": 1, "label_name": "safe"} -{"code": " public function search_external() {\n// global $db, $user;\n global $db;\n\n $sql = \"select DISTINCT(a.id) as id, a.source as source, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email \";\n $sql .= \"from \" . $db->prefix . \"external_addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function findAddress(App\\Request $request)\n\t{\n\t\t$instance = \\App\\Map\\Address::getInstance($request->getByType('type'));\n\t\t$response = new Vtiger_Response();\n\t\tif ($instance) {\n\t\t\t$response->setResult($instance->find($request->getByType('value', 'Text')));\n\t\t}\n\t\t$response->emit();\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def aesEncrypt(data, key):\n cipher = AES.new(key, AES.MODE_CTR,\n counter=Counter.new(128, initial_value=0))\n\n return cipher.encrypt(data)", "label": 1, "label_name": "safe"} -{"code": "\tpublic function strip_tags($input, $encode = TRUE)\n\t{\n\t\trequire_once APPPATH.'libraries/htmlpurifier/HTMLPurifier.auto.php';\n\n\t\t$config = HTMLPurifier_Config::createDefault();\n\t\t// Defaults to UTF-8\n\t\t// $config->set('Core.Encoding', 'UTF-8');\n\t\t// $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');\n\t\t$config->set('Core.EnableIDNA', TRUE);\n\t\t$config->set('HTML.Allowed', \"\");\n\t\t\n\t\t$purifier = new HTMLPurifier($config);\n\t\t$clean_html = $purifier->purify($input);\n\n\t\treturn $encode ? self::escape($clean_html) : $clean_html;\n\t}", "label": 1, "label_name": "safe"} -{"code": " it \"rejects images but not formatting with filter '#{filter}'\" do\n blog.comment_text_filter = filter\n\n html = comment.html(:body)\n\n ActiveSupport::Deprecation.silence do\n expect(html).not_to match(/foo})\n end\n end", "label": 1, "label_name": "safe"} -{"code": " public async Task UpdateListByChapter(UpdateReadingListByChapterDto dto)\n {\n var user = await UserHasReadingListAccess(dto.ReadingListId);\n if (user == null)\n {\n return BadRequest(\"You do not have permissions on this reading list or the list doesn't exist\");\n }\n var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);\n if (readingList == null) return BadRequest(\"Reading List does not exist\");\n\n // If there are adds, tell tracking this has been modified\n if (await AddChaptersToReadingList(dto.SeriesId, new List() { dto.ChapterId }, readingList))\n {\n _unitOfWork.ReadingListRepository.Update(readingList);\n }\n\n try\n {\n if (_unitOfWork.HasChanges())\n {\n await _unitOfWork.CommitAsync();\n return Ok(\"Updated\");\n }\n }\n catch\n {\n await _unitOfWork.RollbackAsync();\n }\n\n return Ok(\"Nothing to do\");\n }", "label": 1, "label_name": "safe"} -{"code": " it { should contain_class(\"postgresql::params\") }", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($definition->info[$token->name]->attr_transform_post as $transform) {\n $attr = $transform->transform($o = $attr, $config, $context);\n if ($e) {\n if ($attr != $o) {\n $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\n }\n }\n }", "label": 1, "label_name": "safe"} -{"code": " function _parseOptions($array)\n {\n foreach ($array as $key => $value) {\n if (isset($this->options[$key])) {\n $this->options[$key] = $value;\n }\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testRegister()\n {\n $builder = new ContainerBuilder();\n $builder->register('foo', 'Bar\\FooClass');\n $this->assertTrue($builder->hasDefinition('foo'), '->register() registers a new service definition');\n $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $builder->getDefinition('foo'), '->register() returns the newly created Definition instance');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def to_xml(options = nil)\n [name].to_xml\n end", "label": 1, "label_name": "safe"} -{"code": "static void opl3_setup_voice(int dev, int voice, int chn)\n{\n\tstruct channel_info *info =\n\t&synth_devs[dev]->chn_info[chn];\n\n\topl3_set_instr(dev, voice, info->pgm_num);\n\n\tdevc->voc[voice].bender = 0;\n\tdevc->voc[voice].bender_range = info->bender_range;\n\tdevc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME];\n\tdevc->voc[voice].panning = (info->controllers[CTL_PAN] * 2) - 128;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static int raw_cmd_copyout(int cmd, void __user *param,\n\t\t\t\t struct floppy_raw_cmd *ptr)\n{\n\tint ret;\n\n\twhile (ptr) {\n\t\tret = copy_to_user(param, ptr, sizeof(*ptr));\n\t\tif (ret)\n\t\t\treturn -EFAULT;\n\t\tparam += sizeof(struct floppy_raw_cmd);\n\t\tif ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {\n\t\t\tif (ptr->length >= 0 &&\n\t\t\t ptr->length <= ptr->buffer_length) {\n\t\t\t\tlong length = ptr->buffer_length - ptr->length;\n\t\t\t\tret = fd_copyout(ptr->data, ptr->kernel_data,\n\t\t\t\t\t\t length);\n\t\t\t\tif (ret)\n\t\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\t\tptr = ptr->next;\n\t}\n\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\t function update_upcharge() {\n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\t\t\n\t\t//This will make sure that only the country or region that given a rate value will be saved in the db\n\t\t$upcharge = array();\n\t\tforeach($this->params['upcharge'] as $key => $item) {\n\t\t\tif(!empty($item)) {\n\t\t\t\t$upcharge[$key] = $item;\n\t\t\t}\n\t\t}\n\t\t$this->config['upcharge'] = $upcharge;\n\t\t\n $config->update(array('config'=>$this->config));\n flash('message', gt('Configuration updated'));\n expHistory::back();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testAlternatePath()\n {\n $cache = new HTMLPurifier_DefinitionCache_Serializer('Test');\n $config = $this->generateConfigMock('serial');\n $config->version = '1.0.0';\n $config->returns('get', 1, array('Test.DefinitionRev'));\n $dir = dirname(__FILE__) . '/SerializerTest';\n $config->returns('get', $dir, array('Cache.SerializerPath'));\n\n $def_original = $this->generateDefinition();\n $cache->add($def_original, $config);\n $this->assertFileExist($dir . '/Test/1.0.0,serial,1.ser');\n\n unlink($dir . '/Test/1.0.0,serial,1.ser');\n rmdir( $dir . '/Test');\n\n }", "label": 1, "label_name": "safe"} -{"code": "int jpg_validate(jas_stream_t *in)\n{\n\tjas_uchar buf[JPG_MAGICLEN];\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\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\n\t/* Did we read enough data? */\n\tif (n < JPG_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\t/* Does this look like JPEG? */\n\tif (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label": 1, "label_name": "safe"} -{"code": "v=Math.max(0,Math.min(c,mxUtils.getValue(this.state.style,\"arrowSize\",$a.prototype.arrowSize)));return new mxPoint(x.x+(1-v)*x.width,x.y+(1-p)*x.height/2)},function(x,p){this.state.style.arrowWidth=Math.max(0,Math.min(1,Math.abs(x.y+x.height/2-p.y)/x.height*2));this.state.style.arrowSize=Math.max(0,Math.min(c,(x.x+x.width-p.x)/x.width))})]}},yb=function(c){return function(l){return[fb(l,[\"size\"],function(x){var p=Math.max(0,Math.min(.5*x.height,parseFloat(mxUtils.getValue(this.state.style,\"size\",\nc))));return new mxPoint(x.x,x.y+p)},function(x,p){this.state.style.size=Math.max(0,p.y-x.y)},!0)]}},ub=function(c,l,x){return function(p){var v=[fb(p,[\"size\"],function(A){var B=Math.max(0,Math.min(A.width,Math.min(A.height,parseFloat(mxUtils.getValue(this.state.style,\"size\",l)))))*c;return new mxPoint(A.x+B,A.y+B)},function(A,B){this.state.style.size=Math.round(Math.max(0,Math.min(Math.min(A.width,B.x-A.x),Math.min(A.height,B.y-A.y)))/c)},!1)];x&&mxUtils.getValue(p.style,mxConstants.STYLE_ROUNDED,", "label": 1, "label_name": "safe"} -{"code": " public function accept(NodeVisitor $nodeVisitor)\n {\n $nodeVisitor->visitElementNode($this);\n }", "label": 1, "label_name": "safe"} -{"code": " public TaskTreeForm(final TaskTreePage parentPage)\n {\n super(parentPage);\n csrfTokenHandler = new CsrfTokenHandler(this);\n }", "label": 1, "label_name": "safe"} -{"code": "null!=sa[ra]&&(ra=sa[ra]);ra={url:pa.getAttribute(\"url\"),libs:pa.getAttribute(\"libs\"),title:pa.getAttribute(\"title\"),tooltip:pa.getAttribute(\"name\")||pa.getAttribute(\"url\"),preview:pa.getAttribute(\"preview\"),clibs:ra,tags:pa.getAttribute(\"tags\")};wa.push(ra);null!=ya&&(wa=Ba[va],null==wa&&(wa={},Ba[va]=wa),va=wa[ya],null==va&&(va=[],wa[ya]=va),va.push(ra))}pa=pa.nextSibling}S.stop();B()}})};G.appendChild(ea);G.appendChild(Aa);G.appendChild(Z);var ta=!1,ka=k;/^https?:\\/\\//.test(ka)&&!b.editor.isCorsEnabledForUrl(ka)&&", "label": 0, "label_name": "vulnerable"} -{"code": " public Document read(URL url) throws DocumentException {\n String systemID = url.toExternalForm();\n\n InputSource source = new InputSource(systemID);\n if (this.encoding != null) {\n source.setEncoding(this.encoding);\n }\n\n return read(source);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it \"doesn't allow remote shell execution\" do\n expect {\n described_class.open(\"| touch file.txt\") # Kernel#open accepts this\n }.to raise_error(URI::InvalidURIError)\n\n expect(File.exist?(\"file.txt\")).to eq(false)\n end", "label": 1, "label_name": "safe"} -{"code": "PHP_NAMED_FUNCTION(zif_locale_set_default)\n{\n\tchar* locale_name = NULL;\n\tint len=0;\n\n\tif(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, \"s\",\n\t\t&locale_name ,&len ) == FAILURE)\n\t{\n\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t\t\t \t\"locale_set_default: unable to parse input params\", 0 TSRMLS_CC );\n\n\t\tRETURN_FALSE;\n\t}\n\n\tif(len == 0) {\n\t\tlocale_name = (char *)uloc_getDefault() ;\n\t\tlen = strlen(locale_name);\n\t}\n\n\tzend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);\n\n\tRETURN_TRUE;\n}", "label": 1, "label_name": "safe"} -{"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 TfLiteIntArray* input_dims = input->dims;\n int input_dims_size = input_dims->size;\n TF_LITE_ENSURE(context, input_dims_size >= 1);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n // Resize the output tensor.\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(input_dims_size + 1);\n for (int i = 0; i < input_dims_size; i++) {\n output_shape->data[i] = input_dims->data[i];\n }\n // Last dimension in the output is the same as the last dimension in the\n // input.\n output_shape->data[input_dims_size] = input_dims->data[input_dims_size - 1];\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, "label_name": "vulnerable"} -{"code": " public function testRouterResetWithParentRequestOnKernelFinishRequest()\n {\n // the request context is updated\n $context = $this->getMock('Symfony\\Component\\Routing\\RequestContext');\n $context->expects($this->once())->method('setParameter')->with('_locale', 'es');\n\n $router = $this->getMock('Symfony\\Component\\Routing\\Router', array('getContext'), array(), '', false);\n $router->expects($this->once())->method('getContext')->will($this->returnValue($context));\n\n $parentRequest = Request::create('/');\n $parentRequest->setLocale('es');\n\n $this->requestStack->expects($this->once())->method('getParentRequest')->will($this->returnValue($parentRequest));\n\n $event = $this->getMock('Symfony\\Component\\HttpKernel\\Event\\FinishRequestEvent', array(), array(), '', false);\n\n $listener = new LocaleListener($this->requestStack, 'fr', $router);\n $listener->onKernelFinishRequest($event);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function(a,c,b){a=d.preparse(a,c);return d.isValid(a)?(a.M-=100>a.Y?22801:1,b||a.Z?new Date(Date.UTC(a.Y,a.M,a.D,a.H,a.m+a.Z,a.s,a.S)):new Date(a.Y,a.M,a.D,a.H,a.m,a.s,a.S)):new Date(NaN)};d.transform=function(a,c,b,e){return d.format(d.parse(a,c),b,e)};d.addYears=function(a,c){return d.addMonths(a,12*c)};d.addMonths=function(a,c){var b=new Date(a.getTime());b.setMonth(b.getMonth()+c);return b};d.addDays=function(a,c){var b=new Date(a.getTime());b.setDate(b.getDate()+c);return b};d.addHours=function(a,", "label": 1, "label_name": "safe"} -{"code": " public function testOneTag()\n {\n $tokenizer = new JBBCode\\Tokenizer('[b]');\n $this->assertEquals('[', $tokenizer->next());\n $this->assertEquals('b', $tokenizer->next());\n $this->assertEquals(']', $tokenizer->next());\n $this->assertFalse($tokenizer->hasNext());\n }", "label": 1, "label_name": "safe"} -{"code": " public void translate(ServerSetTitlesAnimationPacket packet, GeyserSession session) {\n SetTitlePacket titlePacket = new SetTitlePacket();\n titlePacket.setType(SetTitlePacket.Type.TIMES);\n titlePacket.setText(\"\");\n titlePacket.setFadeInTime(packet.getFadeIn());\n titlePacket.setFadeOutTime(packet.getFadeOut());\n titlePacket.setStayTime(packet.getStay());\n titlePacket.setXuid(\"\");\n titlePacket.setPlatformOnlineId(\"\");\n session.sendUpstreamPacket(titlePacket);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function edit_externalalias() {\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\n if ($section->parent == -1) {\n notfoundController::handle_not_found();\n exit;\n } // doesn't work for standalone pages\n if (empty($section->id)) {\n $section->public = 1;\n if (!isset($section->parent)) {\n // This is another precaution. The parent attribute\n // should ALWAYS be set by the caller.\n //FJD - if that's the case, then we should die.\n notfoundController::handle_not_authorized();\n exit;\n //$section->parent = 0;\n }\n }\n assign_to_template(array(\n 'section' => $section,\n 'glyphs' => self::get_glyphs(),\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function z(ha,da){if(null!=J){var ca=function(pa){qa.isExternal?g(qa,function(na){la(na,pa)},ia):qa.url?mxUtils.get(TEMPLATE_PATH+\"/\"+qa.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?la(na.getText(),pa):ia()})):la(b.emptyDiagramXml,pa)},la=function(pa,na){y||b.hideDialog(!0);e(pa,na,qa,da)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){J=qa;za.className=\"geTempDlgCreateBtn\";da&&(Ga.className=\"geTempDlgOpenBtn\")},", "label": 0, "label_name": "vulnerable"} -{"code": " def testBoostedTreesCalculateBestGainsPerFeatureSecurity(self):\n node_id_range = [1, 2]\n stats_summary_list = [[[[]]]]\n l1 = [1.0]\n l2 = [1.0]\n tree_complexity = [1.0]\n min_node_weight = [1.17]\n max_splits = 1\n with self.assertRaises((errors.InvalidArgumentError, ValueError)):\n gen_boosted_trees_ops.boosted_trees_calculate_best_gains_per_feature(\n node_id_range=node_id_range,\n stats_summary_list=stats_summary_list,\n l1=l1,\n l2=l2,\n tree_complexity=tree_complexity,\n min_node_weight=min_node_weight,\n max_splits=max_splits)", "label": 1, "label_name": "safe"} -{"code": " ): Promise => {\n event.preventDefault();\n\n if (SingleSignOn.isSingleSignOnLoginWindow(frameName)) {\n return new SingleSignOn(main, event, url, options).init();\n }\n\n this.logger.log('Opening an external window from a webview.');\n return shell.openExternal(url);\n };", "label": 0, "label_name": "vulnerable"} -{"code": " protected function id($id)\n {\n return HTMLPurifier_ConfigSchema_Interchange_Id::make($id);\n }", "label": 1, "label_name": "safe"} -{"code": " public static void execute(String url, String modulePathInBaloCache, String moduleNameWithOrg, String proxyHost,\n int proxyPort, String proxyUsername, String proxyPassword, String supportedVersionRange, boolean isBuild,\n boolean isNightlyBuild, String langSpecVersion, String platform) {\n if (isBuild) {\n logFormatter = new BuildLogFormatter();\n }\n\n HttpURLConnection conn = null;\n try {\n initializeSsl();\n conn = createHttpUrlConnection(convertToUrl(url + supportedVersionRange), proxyHost, proxyPort,\n proxyUsername, proxyPassword);\n\n conn.setInstanceFollowRedirects(false);\n setRequestMethod(conn, Utils.RequestMethod.GET);\n\n // Set headers\n conn.setRequestProperty(BALLERINA_PLATFORM, platform);\n conn.setRequestProperty(BAL_LANG_SPEC_VERSION, langSpecVersion);\n conn.setRequestProperty(HttpHeaders.ACCEPT_ENCODING, IDENTITY);\n\n boolean redirect = false;\n // 302 - Module is found\n // Other - Error occurred, json returned with the error message\n if (getStatusCode(conn) == HttpURLConnection.HTTP_MOVED_TEMP) {\n redirect = true;\n } else {\n handleErrorResponse(conn, url, moduleNameWithOrg);\n }\n\n if (redirect) {\n // get redirect url from \"location\" header field\n String newUrl = conn.getHeaderField(HttpHeaders.LOCATION);\n String contentDisposition = conn.getHeaderField(HttpHeaders.CONTENT_DISPOSITION);\n\n conn = createHttpUrlConnection(convertToUrl(newUrl), proxyHost, proxyPort, proxyUsername,\n proxyPassword);\n conn.setRequestProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);\n\n createBaloInHomeRepo(conn, modulePathInBaloCache, moduleNameWithOrg, isNightlyBuild, newUrl,\n contentDisposition);\n }\n } catch (Exception e) {\n throw ErrorUtil.createCommandException(e.getMessage());\n } finally {\n if (conn != null) {\n conn.disconnect();\n }\n Authenticator.setDefault(null);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getFilePath($fileName = null)\n {\n if ($fileName === null) {\n $fileName = $this->fileName;\n }\n\n return $this->theme->getPath().'/'.$this->dirName.'/'.$fileName;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getCode()\n {\n return $this->getParameter('code');\n }", "label": 1, "label_name": "safe"} -{"code": " public function __construct(FilesystemInterface $filesystem = null, $path = null)\n {\n $this->path = $path;\n $this->filesystem = $filesystem;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\"geCommentActionLnk\";mxUtils.write(ba,N);Y.appendChild(ba);mxEvent.addListener(ba,\"click\",function(ea){Q(ea,K);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;baemail] = trim(user::getUserAttribution($u->id));\n }", "label": 1, "label_name": "safe"} -{"code": "function ed(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 fd(a){return a>1&&5>a&&1!==~~(a/10)}function gd(a,b,c,d){var e=a+\" \";switch(c){case\"s\":return b||d?\"p\u00e1r sekund\":\"p\u00e1r sekundami\";case\"m\":return b?\"minuta\":d?\"minutu\":\"minutou\";case\"mm\":return b||d?e+(fd(a)?\"minuty\":\"minut\"):e+\"minutami\";break;case\"h\":return b?\"hodina\":d?\"hodinu\":\"hodinou\";case\"hh\":return b||d?e+(fd(a)?\"hodiny\":\"hodin\"):e+\"hodinami\";break;case\"d\":return b||d?\"den\":\"dnem\";case\"dd\":return b||d?e+(fd(a)?\"dny\":\"dn\u00ed\"):e+\"dny\";break;case\"M\":return b||d?\"m\u011bs\u00edc\":\"m\u011bs\u00edcem\";case\"MM\":return b||d?e+(fd(a)?\"m\u011bs\u00edce\":\"m\u011bs\u00edc\u016f\"):e+\"m\u011bs\u00edci\";break;case\"y\":return b||d?\"rok\":\"rokem\";case\"yy\":return b||d?e+(fd(a)?\"roky\":\"let\"):e+\"lety\"}}", "label": 0, "label_name": "vulnerable"} -{"code": "static GF_AV1Config* AV1_DuplicateConfig(GF_AV1Config const * const cfg)\n{\n\tu32 i = 0;\n\tGF_AV1Config *out = gf_malloc(sizeof(GF_AV1Config));\n\n\tout->marker = cfg->marker;\n\tout->version = cfg->version;\n\tout->seq_profile = cfg->seq_profile;\n\tout->seq_level_idx_0 = cfg->seq_level_idx_0;\n\tout->seq_tier_0 = cfg->seq_tier_0;\n\tout->high_bitdepth = cfg->high_bitdepth;\n\tout->twelve_bit = cfg->twelve_bit;\n\tout->monochrome = cfg->monochrome;\n\tout->chroma_subsampling_x = cfg->chroma_subsampling_x;\n\tout->chroma_subsampling_y = cfg->chroma_subsampling_y;\n\tout->chroma_sample_position = cfg->chroma_sample_position;\n\n\tout->initial_presentation_delay_present = cfg->initial_presentation_delay_present;\n\tout->initial_presentation_delay_minus_one = cfg->initial_presentation_delay_minus_one;\n\tout->obu_array = gf_list_new();\n\tfor (i = 0; iobu_array); ++i) {\n\t\tGF_AV1_OBUArrayEntry *dst = gf_malloc(sizeof(GF_AV1_OBUArrayEntry)), *src = gf_list_get(cfg->obu_array, i);\n\t\tdst->obu_length = src->obu_length;\n\t\tdst->obu_type = src->obu_type;\n\t\tdst->obu = gf_malloc((size_t)dst->obu_length);\n\t\tmemcpy(dst->obu, src->obu, (size_t)src->obu_length);\n\t\tgf_list_add(out->obu_array, dst);\n\t}\n\treturn out;\n}", "label": 1, "label_name": "safe"} -{"code": "int bmp_validate(jas_stream_t *in)\n{\n\tint n;\n\tint i;\n\tjas_uchar buf[2];\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, (char *) buf, 2)) < 0) {\n\t\treturn -1;\n\t}\n\t/* Put the characters read back onto 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 characters? */\n\tif (n < 2) {\n\t\treturn -1;\n\t}\n\t/* Is the signature correct for the BMP format? */\n\tif (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) {\n\t\treturn 0;\n\t}\n\treturn -1;\n}", "label": 1, "label_name": "safe"} -{"code": " protected RuntimeException createServletException(Exception e) {\n return new RuntimeException(e);\n }", "label": 1, "label_name": "safe"} -{"code": " def protected!\n gui_request = ( # these are URLs for web pages\n request.path == '/' or\n request.path == '/manage' or\n request.path == '/permissions' or\n request.path.match('/managec/.+/main')\n )\n if request.path.start_with?('/remote/') or request.path == '/run_pcs'\n @auth_user = PCSAuth.loginByToken(cookies)\n unless @auth_user\n halt [401, '{\"notauthorized\":\"true\"}']\n end\n else #/managec/* /manage/* /permissions\n if !gui_request and !is_ajax? then\n # Accept non GUI requests only with header\n # \"X_REQUESTED_WITH: XMLHttpRequest\". (check if they are send via AJAX).\n # This prevents CSRF attack.\n halt [401, '{\"notauthorized\":\"true\"}']\n elsif not PCSAuth.isLoggedIn(session)\n if gui_request\n session[:pre_login_path] = request.path\n redirect '/login'\n else\n halt [401, '{\"notauthorized\":\"true\"}']\n end\n end\n end\n end", "label": 1, "label_name": "safe"} -{"code": " public function setUp()\n {\n parent::setUp();\n $this->func = 'transform';\n }", "label": 1, "label_name": "safe"} -{"code": " function columnUpdate($table, $col, $val, $where=1) { \n $res = @mysqli_query($this->connection, \"UPDATE `\" . $this->prefix . \"$table` SET `$col`='\" . $val . \"' WHERE $where\");\n /*if ($res == null)\n return array();\n $objects = array();\n for ($i = 0; $i < mysqli_num_rows($res); $i++)\n $objects[] = mysqli_fetch_object($res);*/\n //return $objects;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " private function assertEqualYamlStructure($yaml, $expected, $message = '')\n {\n $this->assertEquals(Yaml::parse($expected), Yaml::parse($yaml), $message);\n }", "label": 0, "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, "label_name": "vulnerable"} -{"code": "function addToolTipToTableCell(value) {\n if (value) {\n const sanitizedValue = $('
').text(value).html()\n return `${sanitizedValue}`\n }\n return ''\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "display_dollar(colnr_T col)\n{\n colnr_T save_col;\n\n if (!redrawing())\n\treturn;\n\n cursor_off();\n save_col = curwin->w_cursor.col;\n curwin->w_cursor.col = col;\n if (has_mbyte)\n {\n\tchar_u *p;\n\n\t// If on the last byte of a multi-byte move to the first byte.\n\tp = ml_get_curline();\n\tcurwin->w_cursor.col -= (*mb_head_off)(p, p + col);\n }\n curs_columns(FALSE);\t // recompute w_wrow and w_wcol\n if (curwin->w_wcol < curwin->w_width)\n {\n\tedit_putchar('$', FALSE);\n\tdollar_vcol = curwin->w_virtcol;\n }\n curwin->w_cursor.col = save_col;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def __init__(self, method, uri, headers, bodyProducer, persistent=False):\n \"\"\"\n @param method: The HTTP method for this request, ex: b'GET', b'HEAD',\n b'POST', etc.\n @type method: L{bytes}\n\n @param uri: The relative URI of the resource to request. For example,\n C{b'/foo/bar?baz=quux'}.\n @type uri: L{bytes}\n\n @param headers: Headers to be sent to the server. It is important to\n note that this object does not create any implicit headers. So it\n is up to the HTTP Client to add required headers such as 'Host'.\n @type headers: L{twisted.web.http_headers.Headers}\n\n @param bodyProducer: L{None} or an L{IBodyProducer} provider which\n produces the content body to send to the remote HTTP server.\n\n @param persistent: Set to C{True} when you use HTTP persistent\n connection, defaults to C{False}.\n @type persistent: L{bool}\n \"\"\"\n self.method = method\n self.uri = uri\n self.headers = headers\n self.bodyProducer = bodyProducer\n self.persistent = persistent\n self._parsedURI = None", "label": 0, "label_name": "vulnerable"} -{"code": "rcube_webmail.prototype.enigma_export = function(selected)\n{\n var keys = selected ? this.keys_list.get_selection().join(',') : '*';\n\n if (!keys.length)\n return;\n\n this.goto_url('plugin.enigmakeys', {_a: 'export', _keys: keys});\n};", "label": 0, "label_name": "vulnerable"} -{"code": "Editor.enableExportUrl=!0;Editor.compressXml=!0;Editor.oneDriveInlinePicker=null!=window.urlParams&&\"0\"==window.urlParams.inlinePicker?!1:!0;Editor.globalVars=null;Editor.config=null;Editor.configVersion=null;Editor.defaultBorder=5;Editor.commonProperties=[{name:\"enumerate\",dispName:\"Enumerate\",type:\"bool\",defVal:!1,onChange:function(u){u.refresh()}},{name:\"enumerateValue\",dispName:\"Enumerate Value\",type:\"string\",defVal:\"\",isVisible:function(u,E){return\"1\"==mxUtils.getValue(u.style,\"enumerate\",\"0\")}},", "label": 0, "label_name": "vulnerable"} -{"code": "mxImageShape.prototype.redrawHtmlShape=function(){this.node.style.left=Math.round(this.bounds.x)+\"px\";this.node.style.top=Math.round(this.bounds.y)+\"px\";this.node.style.width=Math.max(0,Math.round(this.bounds.width))+\"px\";this.node.style.height=Math.max(0,Math.round(this.bounds.height))+\"px\";this.node.innerHTML=\"\";if(null!=this.image){var a=mxUtils.getValue(this.style,mxConstants.STYLE_IMAGE_BACKGROUND,\"\"),b=mxUtils.getValue(this.style,mxConstants.STYLE_IMAGE_BORDER,\"\");this.node.style.backgroundColor=\na;this.node.style.borderColor=b;a=document.createElement(\"img\");a.setAttribute(\"border\",\"0\");a.style.position=\"absolute\";a.src=this.image;b=100>this.opacity?\"alpha(opacity=\"+this.opacity+\")\":\"\";this.node.style.filter=b;this.flipH&&this.flipV?b+=\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)\":this.flipH?b+=\"progid:DXImageTransform.Microsoft.BasicImage(mirror=1)\":this.flipV&&(b+=\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)\");a.style.filter!=b&&(a.style.filter=b);\"image\"==\na.nodeName?a.style.rotation=this.rotation:0!=this.rotation?mxUtils.setPrefixedStyle(a.style,\"transform\",\"rotate(\"+this.rotation+\"deg)\"):mxUtils.setPrefixedStyle(a.style,\"transform\",\"\");a.style.width=this.node.style.width;a.style.height=this.node.style.height;this.node.style.backgroundImage=\"\";this.node.appendChild(a)}else this.setTransparentBackgroundImage(this.node)};function mxLabel(a,b,c,d){mxRectangleShape.call(this,a,b,c,d)}mxUtils.extend(mxLabel,mxRectangleShape);", "label": 0, "label_name": "vulnerable"} -{"code": " public static function author($vars, $type='')\n {\n switch (SMART_URL) {\n case true:\n $type = ($type != '') ? $type.'/': '';\n $inFold = (Options::v('permalink_use_index_php') == 'on') ? 'index.php/' : '';\n $url = Site::$url.$inFold.'author/'.$vars.'/'.$type;\n break;\n\n default:\n $type = ($type != '') ? '&type='.$type: '';\n $url = Site::$url.\"?author={$vars}$type\";\n break;\n }\n\n return $url;\n }", "label": 1, "label_name": "safe"} -{"code": " def testSparseCountSparseOutputBadWeightsShape(self):\n indices = [[0, 0], [0, 1], [1, 0], [1, 2]]\n values = [1, 1, 1, 10]\n weights = [1, 2, 4]\n dense_shape = [2, 3]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Weights and values must have the same shape\"):\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, "label_name": "safe"} -{"code": " def initialize(*args)\n super\n # Sort roles array before comparison.\n self[:roles] = Array(self[:roles]).sort!\n end", "label": 0, "label_name": "vulnerable"} -{"code": "ObfuscatedPasswd::ObfuscatedPasswd(const PlainPasswd& plainPwd) : CharArray(8), length(8) {\n int l = strlen(plainPwd.buf), i;\n for (i=0; i<8; i++)\n buf[i] = i cert = readCertFromFile(TestEnvironment::substitute(\n \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem\"));\n envoy::type::matcher::v3::StringMatcher matcher;\n matcher.MergeFrom(TestUtility::createRegexMatcher(R\"raw([^.]*\\.example.com)raw\"));\n std::vector subject_alt_name_matchers;\n subject_alt_name_matchers.push_back(\n SanMatcherPtr{std::make_unique(GEN_DNS, matcher)});\n EXPECT_TRUE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers));\n}", "label": 1, "label_name": "safe"} -{"code": " */\nint re_yyget_lineno (yyscan_t yyscanner)\n{\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n \n if (! YY_CURRENT_BUFFER)\n return 0;\n \n return yylineno;", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should squeeze all elements in an array\" do\n result = scope.function_squeeze([[\"aaabbbbcccc\",\"dddfff\"]])\n expect(result).to(eq(['abc','df']))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($day as $extevent) {\r\n $event_cache = new stdClass();\r\n $event_cache->feed = $extgcalurl;\r\n $event_cache->event_id = $extevent->event_id;\r\n $event_cache->title = $extevent->title;\r\n $event_cache->body = $extevent->body;\r\n $event_cache->eventdate = $extevent->eventdate->date;\r\n if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)\r\n $event_cache->dateFinished = $extevent->dateFinished;\r\n if (isset($extevent->eventstart))\r\n $event_cache->eventstart = $extevent->eventstart;\r\n if (isset($extevent->eventend))\r\n $event_cache->eventend = $extevent->eventend;\r\n if (isset($extevent->is_allday))\r\n $event_cache->is_allday = $extevent->is_allday;\r\n $found = false;\r\n if ($extevent->eventdate->date < $start) // prevent duplicating events crossing month boundaries\r\n $found = $db->selectObject('event_cache','feed=\"'.$extgcalurl.'\" AND event_id=\"'.$event_cache->event_id.'\" AND eventdate='.$event_cache->eventdate);\r\n if (!$found)\r\n $db->insertObject($event_cache,'event_cache');\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " def test_attr_wrapper\n assert_equal(\"

\\n\", render(\"%p{ :strange => 'attrs'}\", :attr_wrapper => '*'))\n assert_equal(\"

\\n\", render(\"%p{ :escaped => 'quo\\\"te'}\", :attr_wrapper => '\"'))\n assert_equal(\"

\\n\", render(\"%p{ :escaped => 'quo\\\\'te'}\", :attr_wrapper => '\"'))\n assert_equal(\"

\\n\", render(\"%p{ :escaped => 'q\\\\'uo\\\"te'}\", :attr_wrapper => '\"'))\n assert_equal(\"\\n\", render(\"!!! XML\", :attr_wrapper => '\"', :format => :xhtml))\n end", "label": 1, "label_name": "safe"} -{"code": " def warnDbgDieIf(test: => Bo, errorCode: St, details: St = \"\"): U = {\n if (test) {\n warnDbgDie(errorCode, details)\n }\n }\n\n def warnDevDieUnless(test: => Bo, errorCode: St, details: St = \"\"): U = {", "label": 1, "label_name": "safe"} -{"code": " it 'should be able to find module paths from the modulepath setting' do\n Puppet::Module.expects(:find).with('foo', 'production').returns(path_of_module_foo)\n expect(scope.function_get_module_path(['foo'])).to eq(path_of_module_foo.path)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " public static boolean filter( final Collection includes,\n final Collection excludes,\n final URI uri ) {\n checkNotNull( \"includes\", includes );\n checkNotNull( \"excludes\", excludes );\n checkNotNull( \"uri\", uri );\n if ( includes.isEmpty() && excludes.isEmpty() ) {\n return true;\n } else if ( includes.isEmpty() ) {\n return !( excludes( excludes, uri ) );\n } else if ( excludes.isEmpty() ) {\n return includes( includes, uri );\n }\n return includes( includes, uri ) && !( excludes( excludes, uri ) );\n }", "label": 1, "label_name": "safe"} -{"code": "function yourls_create_nonce( $action, $user = false ) {\n\tif( false == $user )\n\t\t$user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';\n\t$tick = yourls_tick();\n\t$nonce = substr( yourls_salt($tick . $action . $user), 0, 10 );\n\t// Allow plugins to alter the nonce\n\treturn yourls_apply_filter( 'create_nonce', $nonce, $action, $user );\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public static function init() {}", "label": 0, "label_name": "vulnerable"} -{"code": "function addToolTipToTableCell(value) {\n if (value) {\n return `${value}`\n }\n return ''\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\tprotected function getNetVolumeUniqueId($netVolumes = null, $prefix = 'nm') {\n\t\t$id = false;\n\t\tif (is_null($netVolumes)) {\n\t\t\t$netVolumes = $this->getNetVolumes();\n\t\t}\n\t\t$ids = array();\n\t\tforeach($netVolumes as $vOps) {\n\t\t\tif (isset($vOps['id']) && strpos($vOps['id'], $prefix) === 0) {\n\t\t\t\t$ids[$vOps['id']] = true;\n\t\t\t}\n\t\t}\n\t\tif (! $ids) {\n\t\t\t$id = $prefix.'1';\n\t\t} else {\n\t\t\t$i = 0;\n\t\t\twhile(isset($ids[$prefix.++$i]) && $i < 10000);\n\t\t\t$id = $prefix.$i;\n\t\t\tif (isset($ids[$id])) {\n\t\t\t\t$id = false;\n\t\t\t}\n\t\t}\n\t\treturn $id;\n\t}", "label": 1, "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, "label_name": "safe"} -{"code": " public static AsciiString of(CharSequence name) {\n if (name instanceof AsciiString) {\n return of((AsciiString) name);\n }\n\n final String lowerCased = Ascii.toLowerCase(requireNonNull(name, \"name\"));\n final AsciiString cached = map.get(lowerCased);\n return cached != null ? cached : AsciiString.cached(lowerCased);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " server.onData = function (stream, session, callback) {\n let chunks = [];\n stream.on('data', function (chunk) {\n chunks.push(chunk);\n });\n stream.on('end', function () {\n let body = Buffer.concat(chunks);\n expect(body.toString()).to.equal(message.trim().replace(/\\n/g, '\\r\\n') + '\\r\\n');\n callback();\n });\n };", "label": 1, "label_name": "safe"} -{"code": "static RList *symbols(RBinFile *bf) {\n\tr_return_val_if_fail (bf && bf->o && bf->o->bin_obj, NULL);\n\tRCoreSymCacheElement *element = bf->o->bin_obj;\n\tsize_t i;\n\tHtUU *hash = ht_uu_new0 ();\n\tif (!hash) {\n\t\treturn NULL;\n\t}\n\tRList *res = r_list_newf ((RListFree)r_bin_symbol_free);\n\tbool found = false;\n\tif (element->lined_symbols) {\n\t\tfor (i = 0; i < element->hdr->n_lined_symbols; i++) {\n\t\t\tRCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i];\n\t\t\tif (!sym) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tht_uu_find (hash, sym->paddr, &found);\n\t\t\tif (found) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRBinSymbol *s = bin_symbol_from_symbol (element, sym);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t\tht_uu_insert (hash, sym->paddr, 1);\n\t\t\t}\n\t\t}\n\t}\n\tif (element->symbols) {\n\t\tfor (i = 0; i < element->hdr->n_symbols; i++) {\n\t\t\tRCoreSymCacheElementSymbol *sym = &element->symbols[i];\n\t\t\tht_uu_find (hash, sym->paddr, &found);\n\t\t\tif (found) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRBinSymbol *s = bin_symbol_from_symbol (element, sym);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t}\n\t\t}\n\t}\n\tht_uu_free (hash);\n\treturn res;\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "function(){try{var M=L.width,n=L.height;if(0==M&&0==n){var y=A.result,K=y.indexOf(\",\"),B=decodeURIComponent(escape(atob(y.substring(K+1)))),F=mxUtils.parseXml(B).getElementsByTagName(\"svg\");0assertResult(\n 'Wrap'. '

Do not wrap

',\n '

Wrap

Do not wrap

'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "func WriteCode(id string, code string) {\n\tmemory.Code[id] = code\n}", "label": 0, "label_name": "vulnerable"} -{"code": "y={},A=1,B={},I={},O={},t={},z,L={},C={},E=!0,G=!1,P=!1,J=\"0\"!=urlParams[\"no-p2p\"],F=!1,H=0,S=null,V=mxUtils.bind(this,function(M,W){if(!P)try{null!=q?(q.send(JSON.stringify({action:M,msg:W})),J||EditorUi.debug(\"P2PCollab: sending to socket server\",[M],[W])):this.joinFile(!0)}catch(U){S=U,e.file.fireEvent(new mxEventObject(\"realtimeStateChanged\")),EditorUi.debug(\"P2PCollab:\",\"sendReply error\",arguments,U)}});this.sendMessage=c;this.sendDiff=function(M){this.sendMessage(\"diff\",{patch:M})};this.getState=", "label": 1, "label_name": "safe"} -{"code": "def update(request, pk):\n comment = Comment.objects.for_update_or_404(pk, request.user)\n form = CommentForm(data=post_data(request), instance=comment)\n if is_post(request) and form.is_valid():\n pre_comment_update(comment=Comment.objects.get(pk=comment.pk))\n comment = form.save()\n post_comment_update(comment=comment)\n return safe_redirect(request, 'next', comment.get_absolute_url(), method='POST')\n return render(\n request=request,\n template_name='spirit/comment/update.html',\n context={'form': form})", "label": 1, "label_name": "safe"} -{"code": " it \"raises a QueryFailure exception\" do\n expect {\n session.query(query)\n }.to raise_exception(Moped::Errors::QueryFailure)\n end", "label": 0, "label_name": "vulnerable"} -{"code": "Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def,\n string* init_op_name) {\n const auto& sig_def_map = meta_graph_def.signature_def();\n const auto& init_op_sig_it =\n meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey);\n if (init_op_sig_it != sig_def_map.end()) {\n *init_op_name = init_op_sig_it->second.outputs()\n .find(kSavedModelInitOpSignatureKey)\n ->second.name();\n return Status::OK();\n }\n\n const auto& collection_def_map = meta_graph_def.collection_def();\n string init_op_collection_key;\n if (collection_def_map.find(kSavedModelMainOpKey) !=\n collection_def_map.end()) {\n init_op_collection_key = kSavedModelMainOpKey;\n } else {\n init_op_collection_key = kSavedModelLegacyInitOpKey;\n }\n\n const auto init_op_it = collection_def_map.find(init_op_collection_key);\n if (init_op_it != collection_def_map.end()) {\n if (init_op_it->second.node_list().value_size() != 1) {\n return errors::FailedPrecondition(\n strings::StrCat(\"Expected exactly one main op in : \", export_dir));\n }\n *init_op_name = init_op_it->second.node_list().value(0);\n }\n return Status::OK();\n}", "label": 0, "label_name": "vulnerable"} -{"code": "func (mr *MockAuthorizeRequesterMockRecorder) GetID() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetID\", reflect.TypeOf((*MockAuthorizeRequester)(nil).GetID))\n}", "label": 1, "label_name": "safe"} -{"code": " public String findFilter( String url_suffix )\n {\n if( url_suffix == null )\n {\n throw new IllegalArgumentException( \"The url_suffix must not be null.\" );\n }\n \n CaptureType type = em.find( CaptureType.class, url_suffix );\n \n if( type == null )\n {\n throw new IllegalArgumentException( \"The url_suffix must exist in the database.\" );\n }\n \n // It is okay for the capture filter itself to be null, but the CaptureType\n // must be in the database, otherwise the user could effectively forge\n // a capture filter for \"all\" just by requesting a non-existent filter.\n \n return type.getCaptureFilter();\n }", "label": 1, "label_name": "safe"} -{"code": "function g(D){D.dataTransfer.dropEffect=null!=B?\"move\":\"copy\";D.stopPropagation();D.preventDefault()}function k(D){D.stopPropagation();D.preventDefault();z=!1;I=v(D);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]));else if(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, "label_name": "safe"} -{"code": " public function upsize()\n {\n $this->fix(self::UPSIZE);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function check_return_code_redirect($return_var, $output, $location){\n if ($return_var != 0) {\n $error = implode('
', $output);\n if (empty($error)) {\n $error = sprintf(_('Error code:'), $return_var);\n }\n $_SESSION['error_msg'] = $error;\n header(\"Location:\".$location);\n }\n\n}", "label": 1, "label_name": "safe"} -{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {\n $limit = '0';\n }\n $order = isset($this->config['order']) ? $this->config['order'] : \"rank\";\n $page = new expPaginator(array(\n 'model'=>'photo',\n 'where'=>$this->aggregateWhereClause(),\n 'limit'=>$limit,\n 'order'=>$order,\n 'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],\n 'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),\n 'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),\n 'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'params'=>$this->params,\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function setup($config)\n {\n if ($this->setup) {\n return;\n }\n $this->setup = true;\n $this->doSetup($config);\n }", "label": 1, "label_name": "safe"} -{"code": "def scriptPath(*pathSegs):\n startPath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n return os.path.join(startPath, *pathSegs)", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function formatList( $articles, $start, $count ) {\n\t\t$filteredCount = 0;\n\t\t$items = [];\n\n\t\tfor ( $i = $start; $i < $start + $count; $i++ ) {\n\t\t\t$article = $articles[$i];\n\n\t\t\tif ( empty( $article ) || empty( $article->mTitle ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$pageText = null;\n\t\t\tif ( $this->includePageText ) {\n\t\t\t\t$pageText = $this->transcludePage( $article, $filteredCount );\n\t\t\t} else {\n\t\t\t\t$filteredCount++;\n\t\t\t}\n\n\t\t\t$this->rowCount = $filteredCount;\n\n\t\t\t$items[] = $this->formatItem( $article, $pageText );\n\t\t}\n\n\t\t$this->rowCount = $filteredCount;\n\n\t\treturn $this->getListStart() . $this->implodeItems( $items ) . $this->listEnd;\n\t}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "\t\t\t\t\t\t\t\t\t\t\ttitle : $('input:checked', uitype).val(),\n\t\t\t\t\t\t\t\t\t\t\ttext : 'confirmReq',\n\t\t\t\t\t\t\t\t\t\t\taccept : {\n\t\t\t\t\t\t\t\t\t\t\t\tlabel : 'btnApply',\n\t\t\t\t\t\t\t\t\t\t\t\tcallback : function() { \n\t\t\t\t\t\t\t\t\t\t\t\t\tsave();\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\tcancel : {\n\t\t\t\t\t\t\t\t\t\t\t\tlabel : 'btnCancel',\n\t\t\t\t\t\t\t\t\t\t\t\tcallback : function() {}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\treturn;\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\t\tif (!((c >= 48 && c <= 57) || (c >= 96 && c <= 105))) {\n\t\t\t\t\t\t\t\t\t\te.preventDefault();\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\t.filter(':first');\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t!fm.UA.Mobile && inputFirst.focus();\n\t\t\t\t\t\t\tresizable();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\treset.hover(function() { reset.toggleClass('ui-state-hover'); }).click(resetView);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t})", "label": 1, "label_name": "safe"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"has an empty list of servers\" do\n cluster.servers.should be_empty\n end", "label": 0, "label_name": "vulnerable"} -{"code": "function draw_cdef_preview($cdef_id) {\n\t?>\n\t\n\t\t\n\t\t\t
cdef=
\n\t\t\n\t\n\tincreaseImpressions();\n }\n }\n \n // assign banner to the template and show it!\n assign_to_template(array(\n 'banners'=>$banners\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "static void smp_task_timedout(struct timer_list *t)\n{\n\tstruct sas_task_slow *slow = from_timer(slow, t, timer);\n\tstruct sas_task *task = slow->task;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&task->task_state_lock, flags);\n\tif (!(task->task_state_flags & SAS_TASK_STATE_DONE)) {\n\t\ttask->task_state_flags |= SAS_TASK_STATE_ABORTED;\n\t\tcomplete(&task->slow_task->completion);\n\t}\n\tspin_unlock_irqrestore(&task->task_state_lock, flags);\n}", "label": 1, "label_name": "safe"} -{"code": " def test_long_body(self):\n # check server doesnt close connection when body is too short\n # for cl header\n to_send = tobytes(\n \"GET /long_body HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: 0\\n\"\n \"\\n\"\n )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n content_length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(content_length)\n self.assertEqual(int(status), 200)\n self.assertEqual(content_length, len(response_body))\n self.assertEqual(response_body, tobytes(\"abcdefgh\"))\n # remote does not close connection (keepalive header)\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n content_length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(content_length)\n self.assertEqual(int(status), 200)", "label": 0, "label_name": "vulnerable"} -{"code": " def crop_command\n target = @attachment.instance\n\n if target.cropping?(@attachment.name)\n w = target.send :\"#{@attachment.name}_crop_w\"\n h = target.send :\"#{@attachment.name}_crop_h\"\n x = target.send :\"#{@attachment.name}_crop_x\"\n y = target.send :\"#{@attachment.name}_crop_y\"\n [\"-crop\", \"#{w}x#{h}+#{x}+#{y}\"]\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "def to_csv(function_list,tests)\n function_list.collect do |function_name|\n if v = tests[\"#{function_name} function\"]\n positive_tests = count_tests_in(v[\"groups\"][\"success\"])\n negative_tests = count_tests_in(v[\"groups\"][\"failure\"])\n pending_tests =\n count_pending_tests_in(v[\"groups\"][\"failure\"]) +\n count_pending_tests_in(v[\"groups\"][\"failure\"])\n else\n positive_tests = 0\n negative_tests = 0\n pending_tests = 0\n end\n sprintf(\"%-25s, %-9d, %-9d, %-9d\", function_name,positive_tests,negative_tests,pending_tests)\n end.compact\nend", "label": 0, "label_name": "vulnerable"} -{"code": " public void testFilterUri() {\n final Collection includes = new ArrayList() {{\n add( \"git://**\" );\n }};\n final Collection excludes = new ArrayList() {{\n add( \"file://**\" );\n }};\n\n Assert.assertFalse( filter( includes, excludes, URI.create( \"file:///Users/home\" ) ) );\n\n Assert.assertTrue( filter( includes, excludes, URI.create( \"git://antpathmatcher\" ) ) );\n\n Assert.assertTrue( filter( includes, excludes, URI.create( \"git://master@antpathmatcher/repo/sss\" ) ) );\n\n Assert.assertTrue( filter( Collections.emptyList(), Collections.emptyList(), URI.create( \"file:///Users/home\" ) ) );\n\n Assert.assertTrue( filter( Collections.emptyList(), Collections.emptyList(), URI.create( \"git://master@antpathmatcher/repo/sss\" ) ) );\n\n }", "label": 1, "label_name": "safe"} -{"code": " public function testConstructor()\n {\n $sc = new Container();\n $this->assertSame($sc, $sc->get('service_container'), '__construct() automatically registers itself as a service');\n\n $sc = new Container(new ParameterBag(array('foo' => 'bar')));\n $this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '__construct() takes an array of parameters as its first argument');\n }", "label": 0, "label_name": "vulnerable"} -{"code": "struct clock_source *dce80_clock_source_create(\n\tstruct dc_context *ctx,\n\tstruct dc_bios *bios,\n\tenum clock_source_id id,\n\tconst struct dce110_clk_src_regs *regs,\n\tbool dp_clk_src)\n{\n\tstruct dce110_clk_src *clk_src =\n\t\tkzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL);\n\n\tif (!clk_src)\n\t\treturn NULL;\n\n\tif (dce110_clk_src_construct(clk_src, ctx, bios, id,\n\t\t\tregs, &cs_shift, &cs_mask)) {\n\t\tclk_src->base.dp_clk_src = dp_clk_src;\n\t\treturn &clk_src->base;\n\t}\n\n\tkfree(clk_src);\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n}", "label": 1, "label_name": "safe"} -{"code": " def __init__(self):\n super(ManyCookies, self).__init__()\n self.putChild(b'', HelloWorld())\n self.putChild(b'login', self.SetMyCookie())", "label": 0, "label_name": "vulnerable"} -{"code": "static void put_prev_task(struct rq *rq, struct task_struct *prev)\n{\n\tif (prev->se.on_rq)\n\t\tupdate_rq_clock(rq);\n\trq->skip_clock_update = 0;\n\tprev->sched_class->put_prev_task(rq, prev);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " function fetchData($username, $password)\n {\n $this->log('Auth_Container_PEAR::fetchData() called.', AUTH_LOG_DEBUG);\n\n $client = new HTTP_Client;\n\n $this->log('Auth_Container_PEAR::fetchData() getting salt.', AUTH_LOG_DEBUG);\n $code = $client->get($this->url . '/getsalt');\n if ($code instanceof PEAR_Error) {\n return $code;\n }\n if ($code != 200) {\n return PEAR::raiseError('Bad response to salt request.', $code);\n }\n $resp = $client->currentResponse();\n $salt = $resp['body'];\n\n $this->log('Auth_Container_PEAR::fetchData() calling validate.', AUTH_LOG_DEBUG);\n $postOptions = array(\n 'username' => $username,\n 'password' => md5($salt . md5($password))\n );\n if (is_array($this->karma) && count($this->karma) > 0) {\n $postOptions['karma'] = implode(',', $this->karma);\n }\n\n $code = $client->post($this->url . '/validate', $postOptions);\n if ($code instanceof PEAR_Error) {\n return $code;\n }\n if ($code != 200) {\n return PEAR::raiseError('Bad response to validate request.', $code);\n }\n $resp = $client->currentResponse();\n\n list($code, $message) = explode(' ', $resp['body'], 2);\n if ($code != 8) {\n return PEAR::raiseError($message, $code);\n }\n return true;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $this->addCollector($collector);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public void Restore()\n {\n Client.Instance.PerformRequest(Client.HttpRequestMethod.Put,\n UrlPrefix + Uri.EscapeUriString(CouponCode) + \"/restore\",\n WriteXmlUpdate);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def fix_keywords(value: str) -> str:\n if iskeyword(value):\n return f\"{value}_\"\n return value", "label": 1, "label_name": "safe"} -{"code": " public function testFontTransform()\n {\n $this->assertResult(\n 'Big Warning!',\n 'Big'.\n ' Warning!'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "func (x *StatusList_Status) Reset() {\n\t*x = StatusList_Status{}\n\tif protoimpl.UnsafeEnabled {\n\t\tmi := &file_console_proto_msgTypes[49]\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tms.StoreMessageInfo(mi)\n\t}\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function lists($column, $key = null)\n {\n $select = is_null($key) ? [$column] : [$column, $key];\n\n if (!is_null($this->cacheMinutes)) {\n $results = $this->getCached($select);\n }\n else {\n $results = $this->getFresh($select);\n }\n\n $collection = new Collection($results);\n\n return $collection->lists($column, $key);\n }", "label": 1, "label_name": "safe"} -{"code": " public void sendRedirect(String redirect) throws IOException\n {\n if (StringUtils.isBlank(redirect)) {\n // Nowhere to go to\n return;\n }\n if (StringUtils.containsAny(redirect, '\\r', '\\n')) {\n LOGGER.warn(\"Possible HTTP Response Splitting attack, attempting to redirect to [{}]\", redirect);\n return;\n }\n\n // check for trusted domains, only if the given location is an absolute URL.\n if (ABSOLUTE_URL_PATTERN.matcher(redirect).matches()) {\n if (!getURLSecurityManager().isDomainTrusted(new URL(redirect))) {\n LOGGER.warn(\n \"Possible phishing attack, attempting to redirect to [{}], this request has been blocked. \"\n + \"If the request was legitimate, add the domain related to this request in the list \"\n + \"of trusted domains in the configuration.\", redirect);\n return;\n }\n }\n this.response.sendRedirect(redirect);\n }", "label": 1, "label_name": "safe"} -{"code": "compat_mptfwxfer_ioctl(struct file *filp, unsigned int cmd,\n\t\t\tunsigned long arg)\n{\n\tstruct mpt_fw_xfer32 kfw32;\n\tstruct mpt_fw_xfer kfw;\n\tMPT_ADAPTER *iocp = NULL;\n\tint iocnum, iocnumX;\n\tint nonblock = (filp->f_flags & O_NONBLOCK);\n\tint ret;\n\n\n\tif (copy_from_user(&kfw32, (char __user *)arg, sizeof(kfw32)))\n\t\treturn -EFAULT;\n\n\t/* Verify intended MPT adapter */\n\tiocnumX = kfw32.iocnum & 0xFF;\n\tif (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||\n\t (iocp == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"::compat_mptfwxfer_ioctl @%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_mptfwxfer_ioctl() called\\n\",\n\t iocp->name));\n\tkfw.iocnum = iocnum;\n\tkfw.fwlen = kfw32.fwlen;\n\tkfw.bufp = compat_ptr(kfw32.bufp);\n\n\tret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);\n\n\tmutex_unlock(&iocp->ioctl_cmds.mutex);\n\n\treturn ret;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " private void ChangeScreenResolution()\n {\n\n /*var width = int.Parse(_packet.Args[0].ToString());\n var height = int.Parse(_packet.Args[1].ToString());\n var bbp = int.Parse(_packet.Args[2].ToString());\n var freq = int.Parse(_packet.Args[3].ToString());\n var device = _packet.Args[4].ToString();\n var message = Display.ChangeResolution(device, width, height, bbp, freq);\n var formThread = new\n {\n message\n };\n _builder.WriteMessage(formThread);*/\n }", "label": 1, "label_name": "safe"} -{"code": " public function isConnected()\n {\n return is_resource($this->connection) && ftp_systype($this->connection) !== false;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "xa=E.actions.get(\"zoomOut\"),Da=E.actions.get(\"resetView\");p=E.actions.get(\"fullscreen\");var Ba=E.actions.get(\"undo\"),Ka=E.actions.get(\"redo\"),Oa=F(\"\",Ba.funct,null,mxResources.get(\"undo\")+\" (\"+Ba.shortcut+\")\",Ba,Editor.undoImage),Ia=F(\"\",Ka.funct,null,mxResources.get(\"redo\")+\" (\"+Ka.shortcut+\")\",Ka,Editor.redoImage),Ea=F(\"\",p.funct,null,mxResources.get(\"fullscreen\"),p,Editor.fullscreenImage);if(null!=T){C=function(){ta.style.display=null!=E.pages&&(\"0\"!=urlParams.pages||1 'utf8', 'collate' => 'utf8_danish_ci'})\n should contain_mysql_database('test_db').with({\n 'charset' => 'utf8',\n 'collate' => 'utf8_danish_ci',\n })\n end", "label": 0, "label_name": "vulnerable"} -{"code": "static void process_blob(struct rev_info *revs,\n\t\t\t struct blob *blob,\n\t\t\t show_object_fn show,\n\t\t\t struct strbuf *path,\n\t\t\t const char *name,\n\t\t\t void *cb_data)\n{\n\tstruct object *obj = &blob->object;\n\n\tif (!revs->blob_objects)\n\t\treturn;\n\tif (!obj)\n\t\tdie(\"bad blob object\");\n\tif (obj->flags & (UNINTERESTING | SEEN))\n\t\treturn;\n\tobj->flags |= SEEN;\n\tshow(obj, path, name, cb_data);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " context.it.skip = function(title) {\n context.it(title);\n };", "label": 1, "label_name": "safe"} -{"code": " list($r, $g, $b) = $array;\n $this->a = 0;\n\n }\n\n $this->r = $r;\n $this->g = $g;\n $this->b = $b;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,\n\t\t\t\t u64 devid, u8 *uuid, u8 *fsid,\n\t\t\t\t bool seed)\n{\n\tstruct btrfs_device *device;\n\n\twhile (fs_devices) {\n\t\tif (!fsid ||\n\t\t !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {\n\t\t\tlist_for_each_entry(device, &fs_devices->devices,\n\t\t\t\t\t dev_list) {\n\t\t\t\tif (device->devid == devid &&\n\t\t\t\t (!uuid || memcmp(device->uuid, uuid,\n\t\t\t\t\t\t BTRFS_UUID_SIZE) == 0))\n\t\t\t\t\treturn device;\n\t\t\t}\n\t\t}\n\t\tif (seed)\n\t\t\tfs_devices = fs_devices->seed;\n\t\telse\n\t\t\treturn NULL;\n\t}\n\treturn NULL;\n}", "label": 1, "label_name": "safe"} -{"code": "\t\t\t$iloc = expUnserialize($container->internal);\n\t\t\tif ($db->selectObject('sectionref',\"module='\".$iloc->mod.\"' AND source='\".$iloc->src.\"'\") == null) {\n\t\t\t// There is no sectionref for this container. Populate sectionref\n if ($container->external != \"N;\") {\n $newSecRef = new stdClass();\n $newSecRef->module = $iloc->mod;\n $newSecRef->source = $iloc->src;\n $newSecRef->internal = '';\n $newSecRef->refcount = 1;\n// $newSecRef->is_original = 1;\n\t\t\t\t\t$eloc = expUnserialize($container->external);\n//\t\t\t\t\t$section = $db->selectObject('sectionref',\"module='containermodule' AND source='\".$eloc->src.\"'\");\n $section = $db->selectObject('sectionref',\"module='container' AND source='\".$eloc->src.\"'\");\n\t\t\t\t\tif (!empty($section)) {\n\t\t\t\t\t\t$newSecRef->section = $section->id;\n\t\t\t\t\t\t$db->insertObject($newSecRef,\"sectionref\");\n\t\t\t\t\t\t$missing_sectionrefs[] = gt(\"Missing sectionref for container replaced\").\": \".$iloc->mod.\" - \".$iloc->src.\" - PageID #\".$section->id;\n\t\t\t\t\t} else {\n $db->delete('container','id=\"'.$container->id.'\"');\n $missing_sectionrefs[] = gt(\"Cant' find the container page for container\").\": \".$iloc->mod.\" - \".$iloc->src.' - '.gt('deleted');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n assign_to_template(array(\n 'missing_sectionrefs'=>$missing_sectionrefs,\n ));\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testFilterRelativePathBase()\n {\n $this->setBase('foo/baz.html');\n $this->assertFiltering('foo.php', 'foo/foo.php');\n }", "label": 1, "label_name": "safe"} -{"code": " protected function varToString($var)\n {\n if (null === $this->valueExporter) {\n $this->valueExporter = new ValueExporter();\n }\n\n return $this->valueExporter->exportValue($var);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "(function(){var b=new mxObjectCodec(new ChangeGridColor,[\"ui\"]);b.beforeDecode=function(e,f,c){c.ui=e.ui;return f};mxCodecRegistry.register(b)})();(function(){EditorUi.VERSION=\"18.0.4\";EditorUi.compactUi=\"atlas\"!=uiTheme;Editor.isDarkMode()&&(mxGraphView.prototype.gridColor=mxGraphView.prototype.defaultDarkGridColor);EditorUi.enableLogging=\"1\"!=urlParams.stealth&&\"1\"!=urlParams.lockdown&&(/.*\\.draw\\.io$/.test(window.location.hostname)||/.*\\.diagrams\\.net$/.test(window.location.hostname))&&\"support.draw.io\"!=window.location.hostname;EditorUi.drawHost=window.DRAWIO_BASE_URL;EditorUi.lightboxHost=window.DRAWIO_LIGHTBOX_URL;EditorUi.lastErrorMessage=", "label": 1, "label_name": "safe"} -{"code": "\tpub fn generate_web_proxy_access_token(&self, domain: Origin) -> String {\n\t\tlet token = random_string(16);\n\t\tlet mut tokens = self.web_proxy_tokens.lock();\n\t\ttokens.prune();\n\t\ttokens.insert(token.clone(), domain);\n\t\ttoken\n\t}", "label": 1, "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, "label_name": "safe"} -{"code": " processResponse: function(response, node, callback, scope) {\n // convert tine search response into usual treeLoader structure\n var o = response.responseData || Ext.decode(response.responseText);\n response.responseData = o.hasOwnProperty('totalcount') ? o.results : o;\n \n // processed nodes / structures\n var newResponse = [];\n\n // read every node\n Ext.each(response.responseData, function (node) {\n var parentNode = newResponse;\n \n if (! Ext.isString(node.name)) {\n parentNode.push(node);\n return;\n }\n \n // Get folder name to final container\n var parts = Ext.isString(node.name) ? node.name.split(\"/\") : [''];\n var containerName = parts[parts.length-1];\n\n // Remove first \"\" and last item because they don't belong to the folder names\n // This could be \"\" if the name starts with a /\n if (parts[0] == \"\") {\n parts.shift();\n }\n parts.pop();\n\n Ext.each(parts, function (part, idx) {\n var child = this.findNodeByName(part, parentNode);\n\n if (! child) {\n var child = {\n 'name': part,\n 'id': part,\n 'children': [],\n 'leaf': false,\n 'editable': false,\n 'draggable': false,\n 'allowDrag': false,\n 'allowDrop': false,\n 'singleClickExpand': true,\n 'listeners': {'beforeclick' : function(n,e) {n.toggle(); return false}}\n };\n parentNode.push(child);\n }\n\n parentNode = child.children;\n }, this);\n\n node.longName = node.name;\n node.text = node.name = Ext.util.Format.htmlEncode(containerName);\n\n parentNode.push(node);\n }, this);\n\n response.responseData = newResponse;\n\n return Tine.widgets.tree.Loader.superclass.processResponse.apply(this, arguments);\n },", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function approve_submit() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n\n /* The global constants can be overriden by passing appropriate params */\n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\n\t $comment = new expComment($this->params['id']);\n\t $comment->body = $this->params['body'];\n\t $comment->approved = $this->params['approved'];\n\t $comment->save();\n\t expHistory::back();\n\t}", "label": 1, "label_name": "safe"} -{"code": " def test_execute_details_cleans_text\n spec_fetcher do |fetcher|\n fetcher.spec 'a', 2 do |s|\n s.summary = 'This is a lot of text. ' * 4\n s.authors = [\"Abraham Lincoln \\u0001\", \"\\u0002 Hirohito\"]\n s.homepage = \"http://a.example.com/\\u0003\"\n end\n\n fetcher.legacy_platform\n end\n\n @cmd.handle_options %w[-r -d]\n\n use_ui @ui do\n @cmd.execute\n end\n\n expected = <<-EOF\n\n*** REMOTE GEMS ***\n\na (2)\n Authors: Abraham Lincoln ., . Hirohito\n Homepage: http://a.example.com/.\n\n This is a lot of text. This is a lot of text. This is a lot of text.\n This is a lot of text.\n\npl (1)\n Platform: i386-linux\n Author: A User\n Homepage: http://example.com\n\n this is a summary\n EOF\n\n assert_equal expected, @ui.output\n assert_equal '', @ui.error\n end", "label": 1, "label_name": "safe"} -{"code": "y,mxUtils.bind(this,function(){var C=null;if(!n){C=parseInt(H.value);var I=parseInt(U.value);C=J.checked||C==G&&I==G?null:{from:Math.max(0,Math.min(F-1,C-1)),to:Math.max(0,Math.min(F-1,I-1))}}d.downloadFile(\"pdf\",null,null,!Q.checked,n?!0:!J.checked&&null==C,!W.checked,null!=X&&X.checked,null,null,V.checked,null!=p&&p.checked,C)}),null,mxResources.get(\"export\"));d.showDialog(y.container,300,K,!0,!0)}else d.showDialog((new PrintDialog(d,mxResources.get(\"formatPdf\"))).container,360,null!=d.pages&&1<", "label": 0, "label_name": "vulnerable"} -{"code": " public function activate_address()\n {\n global $db, $user;\n\n $object = new stdClass();\n $object->id = $this->params['id'];\n $db->setUniqueFlag($object, 'addresses', expString::escape($this->params['is_what']), \"user_id=\" . $user->id);\n flash(\"message\", gt(\"Successfully updated address.\"));\n expHistory::back();\n }", "label": 1, "label_name": "safe"} -{"code": "static int msg_cache_check(const char *id, struct BodyCache *bcache, void *data)\n{\n struct Context *ctx = (struct Context *) data;\n if (!ctx)\n return -1;\n struct PopData *pop_data = (struct PopData *) ctx->data;\n if (!pop_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 (int i = 0; i < ctx->msgcount; i++)\n {\n /* if the id we get is known for a header: done (i.e. keep in cache) */\n if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0))\n return 0;\n }\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, "label_name": "safe"} -{"code": "b.apply(d)},a||0)},trim:function(){var b=/(?:^[ \\t\\n\\r]+)|(?:[ \\t\\n\\r]+$)/g;return function(a){return a.replace(b,\"\")}}(),ltrim:function(){var b=/^[ \\t\\n\\r]+/g;return function(a){return a.replace(b,\"\")}}(),rtrim:function(){var b=/[ \\t\\n\\r]+$/g;return function(a){return a.replace(b,\"\")}}(),indexOf:function(b,a){if(typeof a==\"function\")for(var d=0,g=b.length;d= 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, "label_name": "safe"} -{"code": " public static Coupon Get(string couponCode)\n {\n var coupon = new Coupon();\n\n var statusCode = Client.Instance.PerformRequest(Client.HttpRequestMethod.Get,\n Coupon.UrlPrefix + Uri.EscapeUriString(couponCode),\n coupon.ReadXml);\n\n return statusCode == HttpStatusCode.NotFound ? null : coupon;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " function call($methodname, $args)\n {\n if (!$this->hasMethod($methodname)) {\n return new Error(-32601, 'server error. requested method ' . $methodname . ' does not exist.');\n }\n $method = $this->callbacks[$methodname];\n\n // Perform the callback and send the response\n if (count($args) == 1) {\n // If only one paramater just send that instead of the whole array\n $args = $args[0];\n }\n\n // See if this method comes from one of our objects or maybe self\n if (is_array($method) || (substr($method, 0, 5) == 'this:')) {\n if (is_array($method)) {\n $object = $this->_objects[$method[0]];\n $method = $method[1];\n } else {\n $object = $this;\n $method = substr($method, 5);\n }\n\n // It's a class method - check it exists\n if (!method_exists($object, $method)) {\n return new Error(-32601, 'server error. requested class method \"' . $method . '\" does not exist.');\n }\n\n // Call the method\n $result = $object->$method($args);\n } else {\n // It's a function - does it exist?\n if (!function_exists($method)) {\n return new Error(-32601, 'server error. requested function \"' . $method . '\" does not exist.');\n }\n\n // Call the function\n $result = $method($args);\n }\n return $result;\n }", "label": 1, "label_name": "safe"} -{"code": " text: Ext.util.Format.htmlEncode(record.get('name')),\n qtip: Tine.Tinebase.common.doubleEncode(record.get('host')),\n leaf: false,\n cls: 'felamimail-node-account',\n delimiter: record.get('delimiter'),\n ns_personal: record.get('ns_personal'),\n account_id: record.data.id\n });", "label": 0, "label_name": "vulnerable"} -{"code": " public function delete() {\n global $db, $history;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the comment you would like to delete'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n // delete the note\n $simplenote = new expSimpleNote($this->params['id']);\n $rows = $simplenote->delete();\n \n // delete the assocication too\n $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']); \n \n // send the user back where they came from.\n $lastUrl = expHistory::getLast('editable');\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tpublic static function upload_user_avatar() {\n\t\t\t$file = $_FILES['lp-upload-avatar'];\n\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();\n\n\t\t\tadd_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\n\t\t\t$result = wp_handle_upload(\n\t\t\t\t$file,\n\t\t\t\tarray(\n\t\t\t\t\t'test_form' => false,\n\t\t\t\t)\n\t\t\t);\n\n\t\t\tremove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\n\t\t\tif ( is_array( $result ) ) {\n\t\t\t\t$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );\n\t\t\t\tunset( $result['file'] );\n\t\t\t} else {\n\t\t\t\t$result = array(\n\t\t\t\t\t'error' => __( 'Profile picture upload failed', 'learnpress' ),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlearn_press_send_json( $result );\n\t\t}", "label": 0, "label_name": "vulnerable"} -{"code": " private function cacheIsInstalled()\n {\n return class_exists('Intervention\\\\Image\\\\ImageCache');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public FrameInformation GetFullFrame()\n {\n try\n {\n return FrameChannel.GetFullFrame();\n }\n catch (EndpointNotFoundException)\n {\n return null;\n }\n catch (CommunicationException)\n {\n return null;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($mergedPermissions as $mergedPermission => $value) {\n // Strip the '*' off the beginning of the permission.\n $checkPermission = substr($permission, 1);\n\n // We will make sure that the merged permission does not\n // exactly match our permission, but ends with it.\n if ($checkPermission != $mergedPermission && ends_with($mergedPermission, $checkPermission) && $value == 1) {\n $matched = true;\n break;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def _cnonce():\n dig = _md5(\n (\n \"%s:%s\"\n % (time.ctime(), [\"0123456789\"[random.randrange(0, 9)] for i in range(20)])\n ).encode(\"utf-8\")\n ).hexdigest()\n return dig[:16]", "label": 0, "label_name": "vulnerable"} -{"code": " it { is_expected.to be_installed }", "label": 0, "label_name": "vulnerable"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask($task);\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label": 1, "label_name": "safe"} -{"code": " setEntries(entries) {\n if (entries.length === 0) {\n this.emptyList();\n return;\n }\n\n let htmlToInsert = '';\n\n for (let timesheet of entries) {\n let label = this.attributes['template']\n .replace('%customer%', timesheet.project.customer.name)\n .replace('%project%', timesheet.project.name)\n .replace('%activity%', timesheet.activity.name);\n\n htmlToInsert +=\n `
  • ` +\n `` +\n ` ${ label }` +\n `` +\n `
  • `;\n }\n\n this.itemList.innerHTML = htmlToInsert;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testNoWrapForWhitespaceOrValidElements()\n {\n $this->assertResult('

    Do not wrap

    Whitespace

    ');\n }", "label": 1, "label_name": "safe"} -{"code": " public function setUp()\n {\n $client = $this->getHttpClient();\n $request = $this->getHttpRequest();\n $this->request = new RestCreateSubscriptionRequest($client, $request);\n\n $this->request->initialize(array(\n 'name' => 'Test Subscription',\n 'description' => 'Test Billing Subscription',\n 'startDate' => new \\DateTime(),\n 'planId' => 'ABC-123',\n 'payerDetails' => array(\n 'payment_method' => 'paypal',\n ),\n ));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function insert()\r\n\t{\r\n\t\tglobal $DB;\r\n \r\n\t\t$ok = $DB->execute(' \r\n \t\t\tINSERT INTO nv_menus\r\n\t\t\t\t(id, codename, icon, lid, notes, functions, enabled)\r\n\t\t\tVALUES \r\n\t\t\t\t( 0, :codename, :icon, :lid, :notes, :functions, :enabled)',\r\n\t\t\tarray(\r\n\t\t\t\t'codename' => value_or_default($this->codename, \"\"),\r\n\t\t\t\t'icon' => value_or_default($this->icon, \"\"),\r\n\t\t\t\t'lid' => value_or_default($this->lid, 0),\r\n\t\t\t\t'notes' => value_or_default($this->notes, \"\"),\r\n\t\t\t\t'functions' => json_encode($this->functions),\r\n\t\t\t\t'enabled' => value_or_default($this->enabled, 0)\r\n\t\t\t)\r\n\t\t);\r\n\t\t\t\t\r\n\t\tif(!$ok)\r\n\t\t\tthrow new Exception($DB->get_last_error());\r\n\t\t\r\n\t\t$this->id = $DB->get_last_id();\r\n\t\t\r\n\t\treturn true;\r\n\t}\t\r", "label": 0, "label_name": "vulnerable"} -{"code": " public function testDisabledExcludes()\n {\n $this->config->set('Core.DisableExcludes', true);\n $this->assertResult('
    ');\n }", "label": 1, "label_name": "safe"} -{"code": " EmailProvider({\n sendVerificationRequest,\n normalizeIdentifier(identifier) {\n if (identifier.split(\"@\").length > 2) throw error\n return identifier\n },", "label": 1, "label_name": "safe"} -{"code": " it { should contain_package('java').with_name('java-1.6.0-openjdk-devel') }", "label": 0, "label_name": "vulnerable"} -{"code": " def markNotificationAsSeen(): Action[JsValue] = PostJsonAction(RateLimits.MarkNotfAsSeen,\n maxBytes = 200) { request =>", "label": 1, "label_name": "safe"} -{"code": " public function testUnnecessaryEndTagToText()\n {\n $this->config->set('Core.EscapeInvalidTags', true);\n $this->expectErrorCollection(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');\n $this->expectContext('CurrentToken', new HTMLPurifier_Token_End('b', array(), 1, 0));\n $this->invoke('');\n }", "label": 1, "label_name": "safe"} -{"code": "Status QuantizeV2Shape(InferenceContext* c) {\n int axis = -1;\n Status s = c->GetAttr(\"axis\", &axis);\n if (!s.ok() && s.code() != error::NOT_FOUND) {\n return s;\n }\n if (axis < -1) {\n return errors::InvalidArgument(\"axis should be at least -1, got \", axis);\n }\n const int minmax_rank = (axis == -1) ? 0 : 1;\n TF_RETURN_IF_ERROR(shape_inference::UnchangedShape(c));\n ShapeHandle minmax;\n TF_RETURN_IF_ERROR(c->WithRank(c->input(1), minmax_rank, &minmax));\n TF_RETURN_IF_ERROR(c->WithRank(c->input(2), minmax_rank, &minmax));\n if (axis != -1) {\n ShapeHandle input;\n TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), axis + 1, &input));\n DimensionHandle depth;\n TF_RETURN_IF_ERROR(\n c->Merge(c->Dim(minmax, 0), c->Dim(input, axis), &depth));\n }\n c->set_output(1, minmax);\n c->set_output(2, minmax);\n return Status::OK();\n}", "label": 1, "label_name": "safe"} -{"code": "\thttpSuccess: function( xhr ) {\n\t\ttry {\n\t\t\t// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450\n\t\t\treturn !xhr.status && location.protocol == \"file:\" ||\n\t\t\t\t( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;\n\t\t} catch(e){}\n\t\treturn false;\n\t},", "label": 0, "label_name": "vulnerable"} -{"code": "\tstatic function validUTF($string) {\n\t\tif(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {\n\t\t\treturn false;\n\t\t}\t\t\n\t\treturn true;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n cred_t *cr, zfs_fuid_type_t type)\n{\n#ifdef HAVE_KSID\n\tuint32_t index = FUID_INDEX(fuid);\n\tconst char *domain;\n\tuid_t id;\n\n\tif (index == 0)\n\t\treturn (fuid);\n\n\tdomain = zfs_fuid_find_by_idx(zfsvfs, index);\n\tASSERT(domain != NULL);\n\n\tif (type == ZFS_OWNER || type == ZFS_ACE_USER) {\n\t\t(void) kidmap_getuidbysid(crgetzone(cr), domain,\n\t\t FUID_RID(fuid), &id);\n\t} else {\n\t\t(void) kidmap_getgidbysid(crgetzone(cr), domain,\n\t\t FUID_RID(fuid), &id);\n\t}\n\treturn (id);\n#else\n\t/*\n\t * The Linux port only supports POSIX IDs, use the passed id.\n\t */\n\treturn (fuid);\n#endif /* HAVE_KSID */\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testAddXMLLang()\n {\n $this->assertResult(\n 'La soupe.',\n 'La soupe.'\n );\n }", "label": 1, "label_name": "safe"} -{"code": "mrb_mod_define_method_m(mrb_state *mrb, struct RClass *c)\n{\n struct RProc *p;\n mrb_method_t m;\n mrb_sym mid;\n mrb_value proc = mrb_undef_value();\n mrb_value blk;\n\n mrb_get_args(mrb, \"n|o&\", &mid, &proc, &blk);\n switch (mrb_type(proc)) {\n case MRB_TT_PROC:\n blk = proc;\n break;\n case MRB_TT_UNDEF:\n /* ignored */\n break;\n default:\n mrb_raisef(mrb, E_TYPE_ERROR, \"wrong argument type %T (expected Proc)\", proc);\n break;\n }\n if (mrb_nil_p(blk)) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"no block given\");\n }\n p = MRB_OBJ_ALLOC(mrb, MRB_TT_PROC, mrb->proc_class);\n mrb_proc_copy(p, mrb_proc_ptr(blk));\n p->flags |= MRB_PROC_STRICT;\n MRB_METHOD_FROM_PROC(m, p);\n mrb_define_method_raw(mrb, c, mid, m);\n mrb_method_added(mrb, c, mid);\n return mrb_symbol_value(mid);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = \"\" + path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}", "label": 1, "label_name": "safe"} -{"code": " public function getCookies()\n {\n return $this->cookies;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " private DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfigurationException {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n\n // Security: Disable XInclude & expanding entity references (\"bombs\"), not needed for XMP\n factory.setXIncludeAware(false);\n factory.setExpandEntityReferences(false);\n\n // Security: Enable \"secure processing\", to prevent DoS attacks\n factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);\n\n // Security: Remove possibility to access external DTDs or Schema, not needed for XMP\n factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, \"\");\n factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, \"\");\n\n // Security: Disable loading of external DTD and entities, not needed for XMP\n factory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n factory.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n factory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n\n return factory;\n }", "label": 1, "label_name": "safe"} -{"code": "function applyInlineFootnotes(elem) {\n const footnoteRefs = elem.querySelectorAll(\"sup.footnote-ref\");\n\n footnoteRefs.forEach((footnoteRef) => {\n const expandableFootnote = document.createElement(\"a\");\n expandableFootnote.classList.add(\"expand-footnote\");\n expandableFootnote.innerHTML = iconHTML(\"ellipsis-h\");\n expandableFootnote.href = \"\";\n expandableFootnote.role = \"button\";\n expandableFootnote.dataset.footnoteId = footnoteRef\n .querySelector(\"a\")\n .id.replace(\"footnote-ref-\", \"\");\n\n footnoteRef.after(expandableFootnote);\n });\n\n if (footnoteRefs.length) {\n elem.classList.add(\"inline-footnotes\");\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "options_dic_send:function(){var b={osp:e.cookie.get(\"osp\"),udn:e.cookie.get(\"udn\"),cust_dic_ids:a.cust_dic_ids,id:\"options_dic_send\",udnCmd:e.cookie.get(\"udnCmd\")};e.postMessage.send({message:b,target:a.targetFromFrame[a.iframeNumber+\"_\"+a.dialog._.currentTabId]})},data:function(a){delete a.id},giveOptions:function(){},setOptionsConfirmF:function(){},setOptionsConfirmT:function(){j.setValue(\"\")},clickBusy:function(){a.div_overlay.setEnable()},suggestAllCame:function(){a.div_overlay.setDisable();a.div_overlay_no_check.setDisable()},", "label": 1, "label_name": "safe"} -{"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;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &hash));\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;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &input));\n TF_LITE_ENSURE(context, NumDimensions(input) >= 1);\n\n if (NumInputs(node) == 3) {\n const TfLiteTensor* weight;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &weight));\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;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\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": 1, "label_name": "safe"} -{"code": "CKEDITOR.dom.event.prototype={getKey:function(){return this.$.keyCode||this.$.which},getKeystroke:function(){var a=this.getKey();if(this.$.ctrlKey||this.$.metaKey)a=a+CKEDITOR.CTRL;this.$.shiftKey&&(a=a+CKEDITOR.SHIFT);this.$.altKey&&(a=a+CKEDITOR.ALT);return a},preventDefault:function(a){var e=this.$;e.preventDefault?e.preventDefault():e.returnValue=false;a&&this.stopPropagation()},stopPropagation:function(){var a=this.$;a.stopPropagation?a.stopPropagation():a.cancelBubble=true},getTarget:function(){var a=", "label": 1, "label_name": "safe"} -{"code": "read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval)\n/* Read an unsigned decimal integer from the PPM file */\n/* Swallows one trailing character after the integer */\n/* Note that on a 16-bit-int machine, only values up to 64k can be read. */\n/* This should not be a problem in practice. */\n{\n register int ch;\n register unsigned int val;\n\n /* Skip any leading whitespace */\n do {\n ch = pbm_getc(infile);\n if (ch == EOF)\n ERREXIT(cinfo, JERR_INPUT_EOF);\n } while (ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\r');\n\n if (ch < '0' || ch > '9')\n ERREXIT(cinfo, JERR_PPM_NONNUMERIC);\n\n val = ch - '0';\n while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {\n val *= 10;\n val += ch - '0';\n }\n\n if (val > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n\n return val;\n}", "label": 1, "label_name": "safe"} -{"code": "static void parseTarget(HttpRoute *route, cchar *key, MprJson *prop)\n{\n cchar *name, *args;\n\n if (prop->type & MPR_JSON_OBJ) {\n name = mprReadJson(prop, \"operation\");\n args = mprReadJson(prop, \"args\");\n } else {\n name = \"run\";\n args = prop->value;\n }\n httpSetRouteTarget(route, name, args);\n}", "label": 1, "label_name": "safe"} -{"code": " $list[] = $this->getClass($obj, 'AttrTransform_');\n }\n return $this->listify($list);\n }", "label": 1, "label_name": "safe"} -{"code": " public function tokenizeHTML($string, $config, $context)\n {\n trigger_error('Call to abstract class', E_USER_ERROR);\n }", "label": 1, "label_name": "safe"} -{"code": " public function thumbnailTreeAction()\n {\n $this->checkPermission('thumbnails');\n\n $thumbnails = [];\n\n $list = new Asset\\Image\\Thumbnail\\Config\\Listing();\n\n $groups = [];\n foreach ($list->getThumbnails() as $item) {\n if ($item->getGroup()) {\n if (empty($groups[$item->getGroup()])) {\n $groups[$item->getGroup()] = [\n 'id' => 'group_' . $item->getName(),\n 'text' => htmlspecialchars($item->getGroup()),\n 'expandable' => true,\n 'leaf' => false,\n 'allowChildren' => true,\n 'iconCls' => 'pimcore_icon_folder',\n 'group' => $item->getGroup(),\n 'children' => [],\n ];\n }\n $groups[$item->getGroup()]['children'][] =\n [\n 'id' => $item->getName(),\n 'text' => $item->getName(),\n 'leaf' => true,\n 'iconCls' => 'pimcore_icon_thumbnails',\n 'cls' => 'pimcore_treenode_disabled',\n 'writeable' => $item->isWriteable(),\n ];\n } else {\n $thumbnails[] = [\n 'id' => $item->getName(),\n 'text' => $item->getName(),\n 'leaf' => true,\n 'iconCls' => 'pimcore_icon_thumbnails',\n 'cls' => 'pimcore_treenode_disabled',\n 'writeable' => $item->isWriteable(),\n ];\n }\n }\n\n foreach ($groups as $group) {\n $thumbnails[] = $group;\n }\n\n return $this->adminJson($thumbnails);\n }", "label": 1, "label_name": "safe"} -{"code": "const writeStream = async (filePath, data) => pipeline(data, external_node_fs_.createWriteStream(filePath));", "label": 1, "label_name": "safe"} -{"code": "int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t\tstruct msghdr *msg, size_t len, int flags)\n{\n\tint noblock = flags & MSG_DONTWAIT;\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tsize_t copied;\n\tint err;\n\n\tBT_DBG(\"sock %p sk %p len %zu\", sock, sk, len);\n\n\tif (flags & (MSG_OOB))\n\t\treturn -EOPNOTSUPP;\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb) {\n\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n\t\t\tmsg->msg_namelen = 0;\n\t\t\treturn 0;\n\t\t}\n\t\treturn err;\n\t}\n\n\tcopied = skb->len;\n\tif (len < copied) {\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 == 0) {\n\t\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\t\tif (bt_sk(sk)->skb_msg_name)\n\t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n\t\t\t\t\t\t&msg->msg_namelen);\n\t\telse\n\t\t\tmsg->msg_namelen = 0;\n\t}\n\n\tskb_free_datagram(sk, skb);\n\n\treturn err ? : copied;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " foreach ($grpusers as $u) {\r\n $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " function checkAuth()\n {\n return($this->auth->checkAuth());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function testTooBigArray()\n {\n $a = array();\n for ($i = 0; $i < 20; ++$i) {\n for ($j = 0; $j < 50; ++$j) {\n for ($k = 0; $k < 10; ++$k) {\n $a[$i][$j][$k] = 'value';\n }\n }\n }\n $a[20] = 'value';\n $a[21] = 'value1';\n $exception = $this->createException($a);\n\n $flattened = FlattenException::create($exception);\n $trace = $flattened->getTrace();\n $serializeTrace = serialize($trace);\n\n $this->assertContains('*SKIPPED over 10000 entries*', $serializeTrace);\n $this->assertNotContains('*value1*', $serializeTrace);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def __init__(self, *args, **kwargs):\n super(BasketShareForm, self).__init__(*args, **kwargs)\n\n try:\n self.fields[\"image\"] = GroupModelMultipleChoiceField(\n queryset=kwargs[\"initial\"][\"images\"],\n initial=kwargs[\"initial\"][\"selected\"],\n widget=forms.SelectMultiple(attrs={\"size\": 10}),\n )\n except Exception:\n self.fields[\"image\"] = GroupModelMultipleChoiceField(\n queryset=kwargs[\"initial\"][\"images\"],\n widget=forms.SelectMultiple(attrs={\"size\": 10}),\n )", "label": 0, "label_name": "vulnerable"} -{"code": "null!=ia){ja=fa.getAttribute(\"section\");ba=fa.getAttribute(\"subsection\");if(null==ja&&(ma=ia.indexOf(\"/\"),ja=ia.substring(0,ma),null==ba)){var qa=ia.indexOf(\"/\",ma+1);-1> 4) & 0xf) | ((buf[1] & 0x1) << 4);\n\tRAnalOp next_op;\n\n\t// calculate next instruction size (call recursively avr_op_analyze)\n\t// and free next_op's esil string (we dont need it now)\n\tavr_op_analyze (anal,\n\t\t\t&next_op,\n\t\t\top->addr + op->size, buf + op->size, len - op->size,\n\t\t\tcpu);\n\tr_strbuf_fini (&next_op.esil);\n\top->jump = op->addr + next_op.size + 2;\n\n\t// cycles\n\top->cycles = 1;\t// XXX: This is a bug, because depends on eval state,\n\t\t\t// so it cannot be really be known until this\n\t\t\t// instruction is executed by the ESIL interpreter!!!\n\t\t\t// In case of evaluating to true, this instruction\n\t\t\t// needs 2/3 cycles, elsewhere it needs only 1 cycle.\n\tESIL_A (\"r%d,r%d,^,!,\", r, d);\t\t\t// Rr == Rd\n\tESIL_A (\"?{,%\"PFMT64d\",pc,=,},\", op->jump);\t// ?true => jmp\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def failure_message_for_should\n if @actual.nil? then\n \"expected #{@expected.inspect}, but nothing was printed\"\n else\n \"expected #{@expected.inspect} to be printed; got:\\n#{@actual}\"\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": "CKEDITOR.htmlParser.basicWriter=CKEDITOR.tools.createClass({$:function(){this._={output:[]}},proto:{openTag:function(a){this._.output.push(\"<\",a)},openTagClose:function(a,e){e?this._.output.push(\" />\"):this._.output.push(\">\")},attribute:function(a,e){typeof e==\"string\"&&(e=CKEDITOR.tools.htmlEncodeAttr(e));this._.output.push(\" \",a,'=\"',e,'\"')},closeTag:function(a){this._.output.push(\"\")},text:function(a){this._.output.push(a)},comment:function(a){this._.output.push(\"<\\!--\",a,\"--\\>\")},write:function(a){this._.output.push(a)},", "label": 1, "label_name": "safe"} -{"code": "TfLiteStatus ResizeOutput(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 const TfLiteTensor* multipliers;\n TF_LITE_ENSURE_OK(\n context, GetInputSafe(context, node, kInputMultipliers, &multipliers));\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": 1, "label_name": "safe"} -{"code": " def extract_loc(self, locale, no_csv):\n self.extract_text()\n\n for loc in locale:\n loc_dir = os.path.join(TRANSLATIONS, loc)\n if os.path.isdir(loc_dir):\n self.update_catalog(loc)\n else:\n os.makedirs(loc_dir)\n self.init_catalog(loc)\n\n if not no_csv:\n base = os.path.join(TRANSLATIONS, loc, 'LC_MESSAGES')\n po = os.path.join(base, 'messages.po')\n csv = os.path.join(base, 'messages.csv')\n po2csv([po, csv])\n\n self.compile_catalog()", "label": 1, "label_name": "safe"} -{"code": "prepenv(const struct rule *rule)\n{\n\tstatic const char *safeset[] = {\n\t\t\"DISPLAY\", \"HOME\", \"LOGNAME\", \"MAIL\",\n\t\t\"PATH\", \"TERM\", \"USER\", \"USERNAME\",\n\t\tNULL\n\t};\n\tstruct env *env;\n\n\tenv = createenv(rule);\n\n\t/* if we started with blank, fill some defaults then apply rules */\n\tif (!(rule->options & KEEPENV))\n\t\tfillenv(env, safeset);\n\tif (rule->envlist)\n\t\tfillenv(env, rule->envlist);\n\n\treturn flattenenv(env);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " protected function now()\n {\n $dt = new DateTime();\n $dt->setTimezone(new DateTimeZone('UTC'));\n return $dt->format(DateTime::ISO8601);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def test_underscore_traversal(self):\n t = self.folder.t\n\n t.write('

    ')\n with self.assertRaises(NotFound):\n t()\n\n t.write('

    ')\n with self.assertRaises(NotFound):\n t()\n\n t.write('

    ')\n with self.assertRaises(NotFound):\n t()", "label": 0, "label_name": "vulnerable"} -{"code": " def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None):\n \"\"\"\n Returns a new SqliteAccountInfo that has just read the data from the file.\n\n :param dict env: Override Environment variables.\n \"\"\"\n # Override HOME to ensure hermetic tests\n with mock.patch('os.environ', env or {'HOME': self.home}):\n return SqliteAccountInfo(\n file_name=self.db_path if not env else None,\n last_upgrade_to_run=last_upgrade_to_run,\n )", "label": 0, "label_name": "vulnerable"} -{"code": " public function edit(Request $request, $id) {\n\n return $this->view('content::admin.content.edit', [\n 'content_id'=>$id\n ]);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " lex: function(text) {\n this.text = text;\n this.index = 0;\n this.tokens = [];\n\n while (this.index < this.text.length) {\n var ch = this.text.charAt(this.index);\n if (ch === '\"' || ch === '\\'') {\n this.readString(ch);\n } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {\n this.readNumber();\n } else if (this.isIdentifierStart(this.peekMultichar())) {\n this.readIdent();\n } else if (this.is(ch, '(){}[].,;:?')) {\n this.tokens.push({index: this.index, text: ch});\n this.index++;\n } else if (this.isWhitespace(ch)) {\n this.index++;\n } else {\n var ch2 = ch + this.peek();\n var ch3 = ch2 + this.peek(2);\n var op1 = OPERATORS[ch];\n var op2 = OPERATORS[ch2];\n var op3 = OPERATORS[ch3];\n if (op1 || op2 || op3) {\n var token = op3 ? ch3 : (op2 ? ch2 : ch);\n this.tokens.push({index: this.index, text: token, operator: true});\n this.index += token.length;\n } else {\n this.throwError('Unexpected next character ', this.index, this.index + 1);\n }\n }\n }\n return this.tokens;\n },", "label": 0, "label_name": "vulnerable"} -{"code": "0;NcommentModel->getById($this->request->getIntegerParam('comment_id'));\n\n if (empty($comment)) {\n throw new PageNotFoundException();\n }\n\n if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {\n throw new AccessForbiddenException();\n }\n\n if ($comment['task_id'] != $task['id']) {\n throw new AccessForbiddenException();\n }\n\n return $comment;\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic function __construct()\n\t{\n\t\tparent::__construct();\n\n\t\t// for flash data\n\t\t$this->load->library('session');\n\n\t\tif (!$this->fuel->config('admin_enabled')) show_404();\n\n\t\t$this->load->vars(array(\n\t\t\t'js' => '', \n\t\t\t'css' => css($this->fuel->config('xtra_css')), // use CSS function here because of the asset library path changes below\n\t\t\t'js_controller_params' => array(), \n\t\t\t'keyboard_shortcuts' => $this->fuel->config('keyboard_shortcuts')));\n\n\t\t// change assets path to admin\n\t\t$this->asset->assets_path = $this->fuel->config('fuel_assets_path');\n\n\t\t// set asset output settings\n\t\t$this->asset->assets_output = $this->fuel->config('fuel_assets_output');\n\t\t\n\t\t$this->lang->load('fuel');\n\t\t$this->load->helper('ajax');\n\t\t$this->load->library('form_builder');\n\n\t\t$this->load->module_model(FUEL_FOLDER, 'fuel_users_model');\n\n\t\t// set configuration paths for assets in case they are different from front end\n\t\t$this->asset->assets_module ='fuel';\n\t\t$this->asset->assets_folders = array(\n\t\t\t\t'images' => 'images/',\n\t\t\t\t'css' => 'css/',\n\t\t\t\t'js' => 'js/',\n\t\t\t);\n\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " public function getData()\n {\n $orderNo = $this->httpRequest->request->get('order_number');\n\n // strange exception specified by 2Checkout\n if ($this->getTestMode()) {\n $orderNo = '1';\n }\n\n $key = md5($this->getSecretWord().$this->getAccountNumber().$orderNo.$this->getAmount());\n if (strtolower($this->httpRequest->request->get('key')) !== $key) {\n throw new InvalidResponseException('Invalid key');\n }\n\n return $this->httpRequest->request->all();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function getNode($id)\n {\n if (!isset($this->nodes[$id])) {\n throw new InvalidArgumentException(sprintf('There is no node with id \"%s\".', $id));\n }\n\n return $this->nodes[$id];\n }", "label": 0, "label_name": "vulnerable"} -{"code": "Mocha.prototype.slow = function(slow) {\n this.suite.slow(slow);\n return this;\n};", "label": 1, "label_name": "safe"} -{"code": "mxTooltipHandler.prototype.reset=function(a,b,c){if(!this.ignoreTouchEvents||mxEvent.isMouseEvent(a.getEvent()))if(this.resetTimer(),c=null!=c?c:this.getStateForEvent(a),b&&this.isEnabled()&&null!=c&&(null==this.div||\"hidden\"==this.div.style.visibility)){var d=a.getSource(),e=a.getX(),f=a.getY(),g=a.isSource(c.shape)||a.isSource(c.text);this.thread=window.setTimeout(mxUtils.bind(this,function(){if(!this.graph.isEditing()&&!this.graph.popupMenuHandler.isMenuShowing()&&!this.graph.isMouseDown){var k=\nthis.graph.getTooltip(c,d,e,f);this.show(k,e,f);this.state=c;this.node=d;this.stateSource=g}}),this.delay)}};mxTooltipHandler.prototype.hide=function(){this.resetTimer();this.hideTooltip()};mxTooltipHandler.prototype.hideTooltip=function(){null!=this.div&&(this.div.style.visibility=\"hidden\",this.div.innerHTML=\"\")};", "label": 0, "label_name": "vulnerable"} -{"code": " public function testCascadingRemovalSpecialCaseCannotScrollOneBack()\n {\n $this->assertResult('
    ', '');\n }", "label": 1, "label_name": "safe"} -{"code": " public function isSMTP()\n {\n $this->Mailer = 'smtp';\n }", "label": 1, "label_name": "safe"} -{"code": " private function updateDeadline()\n {\n try {\n $due_date = self::getDueDate($this->zdb, $this->_member);\n\n if ($due_date != '') {\n $date_fin_update = $due_date;\n } else {\n $date_fin_update = new Expression('NULL');\n }\n\n $update = $this->zdb->update(Adherent::TABLE);\n $update->set(\n array('date_echeance' => $date_fin_update)\n )->where(\n Adherent::PK . '=' . $this->_member\n );\n $this->zdb->execute($update);\n return true;\n } catch (Throwable $e) {\n Analog::log(\n 'An error occurred updating member ' . $this->_member .\n '\\'s deadline |' .\n $e->getMessage(),\n Analog::ERROR\n );\n throw $e;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def current_user\n User.except_hidden.find_by_login(self.user)\n end", "label": 0, "label_name": "vulnerable"} -{"code": " getItemName: function($row) {\n return $row.attr(this.settings.nameAttribute);\n },", "label": 0, "label_name": "vulnerable"} -{"code": "func (x *WalletLedgerList) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[43]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label": 0, "label_name": "vulnerable"} -{"code": "var set = function set(obj, path, val) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var internalPath = path,\n objPart;\n options = _objectSpread({\n \"transformRead\": returnWhatWasGiven,\n \"transformKey\": returnWhatWasGiven,\n \"transformWrite\": returnWhatWasGiven\n }, options); // No object data\n\n if (obj === undefined || obj === null) {\n return;\n } // No path string\n\n\n if (!internalPath) {\n return;\n }\n\n internalPath = clean(internalPath); // Path is not a string, throw error\n\n if (typeof internalPath !== \"string\") {\n throw new Error(\"Path argument must be a string\");\n }\n\n if ((0, _typeof2[\"default\"])(obj) !== \"object\") {\n return;\n } // Path has no dot-notation, set key/value\n\n\n if (isNonCompositePath(internalPath)) {\n // Do not allow prototype pollution\n if (internalPath === \"__proto__\") return obj;\n obj = decouple(obj, options);\n obj[options.transformKey(unEscape(internalPath))] = val;\n return obj;\n }\n\n var newObj = decouple(obj, options);\n var pathParts = split(internalPath);\n var pathPart = pathParts.shift();\n var transformedPathPart = options.transformKey(pathPart); // Do not allow prototype pollution\n\n if (transformedPathPart === \"__proto__\") return obj;\n var childPart = newObj[transformedPathPart];\n\n if ((0, _typeof2[\"default\"])(childPart) !== \"object\") {\n // Create an object or array on the path\n if (String(parseInt(transformedPathPart, 10)) === transformedPathPart) {\n // This is an array index\n newObj[transformedPathPart] = [];\n } else {\n newObj[transformedPathPart] = {};\n }\n\n objPart = newObj[transformedPathPart];\n } else {\n objPart = childPart;\n }\n\n return set(newObj, transformedPathPart, set(objPart, pathParts.join('.'), val, options), options);\n};", "label": 1, "label_name": "safe"} -{"code": "\tprivate function _modifiedby( $option ) {\n\t\t$this->userQueryBuilder->addModifiedByConstraint( $option );\n\t}", "label": 1, "label_name": "safe"} -{"code": " public function testCDATA()\n {\n $this->config->set('HTML.Attr.Name.UseCDATA', true);\n $this->assertResult(\n 'BazBar'\n );\n }", "label": 1, "label_name": "safe"} -{"code": " void writeErr(size_t, const AsyncSocketException& ex) noexcept override {\n LOG(ERROR) << \"write error: \" << ex.what();\n EXPECT_NE(\n ex.getType(),\n AsyncSocketException::AsyncSocketExceptionType::SSL_ERROR);\n }", "label": 1, "label_name": "safe"} -{"code": " public function testProcess()\n {\n $container = new ContainerBuilder();\n $container->setAlias('bar', 'foo');\n $def = $container\n ->register('moo')\n ->setArguments(array(new Reference('bar')))\n ;\n\n $this->process($container);\n\n $arguments = $def->getArguments();\n $this->assertEquals('foo', (string) $arguments[0]);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " default List getPermissions() {\n List permissions = new ArrayList<>();\n permissions.add(\"*:*\");\n permissions.add(this.getName().replace('_', ':'));\n permissions.add(this.getName().substring(0, this.getName().indexOf('_')) + \":*\");\n return permissions;\n };", "label": 0, "label_name": "vulnerable"} -{"code": "vips_foreign_load_start( VipsImage *out, void *a, void *b )\n{\n\tVipsForeignLoad *load = VIPS_FOREIGN_LOAD( b );\n\tVipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load );\n\n\tif( !load->real ) {\n\t\tif( !(load->real = vips_foreign_load_temp( load )) )\n\t\t\treturn( NULL );\n\n#ifdef DEBUG\n\t\tprintf( \"vips_foreign_load_start: triggering ->load()\\n\" );\n#endif /*DEBUG*/\n\n\t\t/* Read the image in. This may involve a long computation and\n\t\t * will finish with load->real holding the decompressed image. \n\t\t *\n\t\t * We want our caller to be able to see this computation on\n\t\t * @out, so eval signals on ->real need to appear on ->out.\n\t\t */\n\t\tload->real->progress_signal = load->out;\n\n\t\t/* Note the load object on the image. Loaders can use \n\t\t * this to signal invalidate if they hit a load error. See\n\t\t * vips_foreign_load_invalidate() below.\n\t\t */\n\t\tg_object_set_qdata( G_OBJECT( load->real ), \n\t\t\tvips__foreign_load_operation, load ); \n\n\t\tif( class->load( load ) ||\n\t\t\tvips_image_pio_input( load->real ) ) \n\t\t\treturn( NULL );\n\n\t\t/* ->header() read the header into @out, load has read the\n\t\t * image into @real. They must match exactly in size, bands,\n\t\t * format and coding for the copy to work. \n\t\t *\n\t\t * Some versions of ImageMagick give different results between\n\t\t * Ping and Load for some formats, for example.\n\t\t */\n\t\tif( !vips_foreign_load_iscompat( load->real, out ) )\n\t\t\treturn( NULL );\n\n\t\t/* We have to tell vips that out depends on real. We've set\n\t\t * the demand hint below, but not given an input there.\n\t\t */\n\t\tvips_image_pipelinev( load->out, load->out->dhint, \n\t\t\tload->real, NULL );\n\t}\n\n\treturn( vips_region_new( load->real ) );\n}", "label": 0, "label_name": "vulnerable"} -{"code": " var optionsHTML = renderChoices(choices, function render(choice) {\n if (choice.isNested) {\n return tag('optgroup', { label: choice.label }, renderChoices(choice.choices, render), true);\n } else {\n return tag('option', { value: choice.value, selected: !!isSelected(f.value, choice.value) }, choice.label);\n }\n });\n var attrs = {\n name: name,\n id: f.id === false ? false : (f.id || true),\n classes: w.classes\n };\n if (isMultiple) {\n attrs.multiple = true;\n }\n return tag('select', [attrs, userAttrs, w.attrs || {}], optionsHTML, true);\n };\n return w;\n };", "label": 1, "label_name": "safe"} -{"code": "static void timer_enter_running(Timer *t) {\n _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;\n int r;\n\n assert(t);\n\n /* Don't start job if we are supposed to go down */\n if (unit_stop_pending(UNIT(t)))\n return;\n\n r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)),\n JOB_REPLACE, true, &error, NULL);\n if (r < 0)\n goto fail;\n\n dual_timestamp_get(&t->last_trigger);\n\n if (t->stamp_path)\n touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);\n\n timer_set_state(t, TIMER_RUNNING);\n return;\n\nfail:\n log_unit_warning(UNIT(t), \"Failed to queue unit startup job: %s\", bus_error_message(&error, r));\n timer_enter_dead(t, TIMER_FAILURE_RESOURCES);\n}", "label": 1, "label_name": "safe"} -{"code": "function addGroup($data) {\n\tif($data['editgroupid'] == 0 || $data['editgroupid'] == '')\n\t\t$data['editgroupid'] = 'NULL';\n\tif($data['type'] == \"user\") {\n\t\tif(! array_key_exists('custom', $data))\n\t\t\t$data['custom'] = 1;\n\t\telseif($data['custom'] == 0) {\n\t\t\t$ownerid = 'NULL';\n\t\t\t$data['editgroupid'] = 'NULL';\n\t\t}\n\t\tif($data['custom'])\n\t\t\t$ownerid = getUserlistID($data['owner']);\n\t\t$query = \"INSERT INTO usergroup \"\n\t\t\t\t . \"(name, \"\n\t\t\t\t . \"affiliationid, \"\n\t\t\t\t . \"ownerid, \"\n\t\t\t\t . \"editusergroupid, \"\n\t\t . \"custom, \"\n\t\t . \"initialmaxtime, \"\n\t\t . \"totalmaxtime, \";\n\t\tif(checkUserHasPerm('Set Overlapping Reservation Count'))\n\t\t\t$query .= \"overlapResCount, \";\n\t\t$query .= \"maxextendtime) \"\n\t\t\t\t . \"VALUES ('{$data['name']}', \"\n\t\t\t\t . \"{$data['affiliationid']}, \"\n\t\t\t\t . \"$ownerid, \"\n\t\t\t\t . \"{$data['editgroupid']}, \"\n\t\t . \"{$data['custom']}, \"\n\t\t . \"{$data['initialmax']}, \"\n\t\t . \"{$data['totalmax']}, \";\n\t\tif(checkUserHasPerm('Set Overlapping Reservation Count'))\n\t\t\t$query .= \"{$data['overlap']}, \";\n\t\t$query .= \"{$data['maxextend']})\";\n\t}\n\telse {\n\t\t$query = \"INSERT INTO resourcegroup \"\n\t\t\t\t . \"(name, \"\n\t\t\t\t . \"ownerusergroupid, \"\n\t\t . \"resourcetypeid) \"\n\t\t\t\t . \"VALUES ('{$data['name']}', \"\n\t\t . \"{$data['ownergroup']}, \"\n\t\t . \"'{$data['resourcetypeid']}')\";\n\t}\n\t$qh = doQuery($query, 305);\n\tclearPrivCache();\n\treturn mysql_affected_rows($GLOBALS['mysql_link_vcl']);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static void read_conf(FILE *conffile)\n{\n char *buffer, *line, *val;\n\n buffer = loadfile(conffile);\n for (line = strtok(buffer, \"\\r\\n\"); line; line = strtok(NULL, \"\\r\\n\")) {\n if (!strncmp(line, \"export \", 7))\n continue;\n val = strchr(line, '=');\n if (!val) {\n printf(\"invalid configuration line\\n\");\n break;\n }\n *val++ = '\\0';\n\n if (!strcmp(line, \"JSON_INDENT\"))\n conf.indent = atoi(val);\n if (!strcmp(line, \"JSON_COMPACT\"))\n conf.compact = atoi(val);\n if (!strcmp(line, \"JSON_ENSURE_ASCII\"))\n conf.ensure_ascii = atoi(val);\n if (!strcmp(line, \"JSON_PRESERVE_ORDER\"))\n conf.preserve_order = atoi(val);\n if (!strcmp(line, \"JSON_SORT_KEYS\"))\n conf.sort_keys = atoi(val);\n if (!strcmp(line, \"STRIP\"))\n conf.strip = atoi(val);\n if (!strcmp(line, \"HASHSEED\")) {\n conf.have_hashseed = 1;\n conf.hashseed = atoi(val);\n } else {\n conf.have_hashseed = 0;\n }\n }\n\n free(buffer);\n}", "label": 1, "label_name": "safe"} -{"code": " public function validate($string, $config, $context)\n {\n $string = trim($string);\n\n // early abort: '' and '0' (strings that convert to false) are invalid\n if (!$string) {\n return false;\n }\n\n $pattern = '/^(-?[A-Za-z_][A-Za-z_\\-0-9]*)$/';\n if (!preg_match($pattern, $string)) {\n return false;\n }\n return $string;\n }", "label": 1, "label_name": "safe"} -{"code": " it 'should have primary network (10.0.2.0)' do\n expect(subject.call(['10.0.2.0'])).to be_truthy\n end", "label": 0, "label_name": "vulnerable"} -{"code": " void writeBytes(const void* data, size_t length) {\n check(length);\n memcpy(ptr, data, length);\n ptr += length;\n }", "label": 1, "label_name": "safe"} -{"code": " def test_notfilelike_nocl_http11(self):\n to_send = \"GET /notfilelike_nocl HTTP/1.1\\n\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\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 ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed (no content-length)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label": 0, "label_name": "vulnerable"} -{"code": " it 'is_floats integers' do\n pp = <<-EOS\n $a = 3\n $b = false\n $o = is_float($a)\n if $o == $b {\n notify { 'output correct': }\n }\n EOS\n\n apply_manifest(pp, :catch_failures => true) do |r|\n expect(r.stdout).to match(/Notice: output correct/)\n end\n end\n it 'is_floats hashes' do\n pp = <<-EOS\n $a = {'aaa'=>'www.com'}\n $o = is_float($a)\n notice(inline_template('is_float is <%= @o.inspect %>'))\n EOS\n\n apply_manifest(pp, :catch_failures => true) do |r|\n expect(r.stdout).to match(/is_float is false/)\n end\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def update_params\n params.\n require(:article).\n permit(:allow_comments,\n :allow_pings,\n :body,\n :body_and_extended,\n :draft,\n :extended,\n :password,\n :permalink,\n :published_at,\n :text_filter_name,\n :title,\n :keywords)\n end", "label": 1, "label_name": "safe"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $column = $this->getColumn($project);\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $column,\n 'project' => $project,\n )));\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " protected function getStrategy()\n {\n return new HTMLPurifier_Strategy_MakeWellFormed();\n }", "label": 1, "label_name": "safe"} -{"code": "horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n\ttmsize_t stride = PredictorState(tif)->stride;\n\tuint32* wp = (uint32*) cp0;\n\ttmsize_t wc = cc / 4;\n\n if((cc%(4*stride))!=0)\n {\n TIFFErrorExt(tif->tif_clientdata, \"horAcc32\",\n \"%s\", \"cc%(4*stride))!=0\");\n return 0;\n }\n\n\tif (wc > stride) {\n\t\twc -= stride;\n\t\tdo {\n\t\t\tREPEAT4(stride, wp[stride] += wp[0]; wp++)\n\t\t\twc -= stride;\n\t\t} while (wc > 0);\n\t}\n\treturn 1;\n}", "label": 1, "label_name": "safe"} -{"code": " it \"should exist\" do\n expect(Puppet::Parser::Functions.function(\"is_bool\")).to eq(\"function_is_bool\")\n end", "label": 0, "label_name": "vulnerable"} -{"code": " $percent = round($percent, 0);\n } else {\n $percent = round($percent, 2); // school default\n }\n if ($ret == '%')\n return $percent;\n\n if (!$_openSIS['_makeLetterGrade']['grades'][$grade_scale_id])\n $_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] = DBGet(DBQuery('SELECT TITLE,ID,BREAK_OFF FROM report_card_grades WHERE SYEAR=\\'' . $cp[1]['SYEAR'] . '\\' AND SCHOOL_ID=\\'' . $cp[1]['SCHOOL_ID'] . '\\' AND GRADE_SCALE_ID=\\'' . $grade_scale_id . '\\' ORDER BY BREAK_OFF IS NOT NULL DESC,BREAK_OFF DESC,SORT_ORDER'));\n\n foreach ($_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] as $grade) {\n if ($does_breakoff == 'Y' ? $percent >= $programconfig[$staff_id][$course_period_id . '-' . $grade['ID']] && is_numeric($programconfig[$staff_id][$course_period_id . '-' . $grade['ID']]) : $percent >= $grade['BREAK_OFF'])\n return $ret == 'ID' ? $grade['ID'] : $grade['TITLE'];\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " return function sign(data, algo) {\n const pem = this[SYM_PRIV_PEM];\n if (pem === null)\n return new Error('No private key available');\n if (!algo || typeof algo !== 'string')\n algo = this[SYM_HASH_ALGO];\n try {\n return sign_(algo, data, pem);\n } catch (ex) {\n return ex;\n }\n };", "label": 1, "label_name": "safe"} -{"code": "static void oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx,\n\tstruct oz_usb_hdr *usb_hdr, int len)\n{\n\tstruct oz_data *data_hdr = (struct oz_data *)usb_hdr;\n\n\tswitch (data_hdr->format) {\n\tcase OZ_DATA_F_MULTIPLE_FIXED: {\n\t\t\tstruct oz_multiple_fixed *body =\n\t\t\t\t(struct oz_multiple_fixed *)data_hdr;\n\t\t\tu8 *data = body->data;\n\t\t\tint n;\n\t\t\tif (!body->unit_size)\n\t\t\t\tbreak;\n\t\t\tn = (len - sizeof(struct oz_multiple_fixed)+1)\n\t\t\t\t/ body->unit_size;\n\t\t\twhile (n--) {\n\t\t\t\toz_hcd_data_ind(usb_ctx->hport, body->endpoint,\n\t\t\t\t\tdata, body->unit_size);\n\t\t\t\tdata += body->unit_size;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase OZ_DATA_F_ISOC_FIXED: {\n\t\t\tstruct oz_isoc_fixed *body =\n\t\t\t\t(struct oz_isoc_fixed *)data_hdr;\n\t\t\tint data_len = len-sizeof(struct oz_isoc_fixed)+1;\n\t\t\tint unit_size = body->unit_size;\n\t\t\tu8 *data = body->data;\n\t\t\tint count;\n\t\t\tint i;\n\n\t\t\tif (!unit_size)\n\t\t\t\tbreak;\n\t\t\tcount = data_len/unit_size;\n\t\t\tfor (i = 0; i < count; i++) {\n\t\t\t\toz_hcd_data_ind(usb_ctx->hport,\n\t\t\t\t\tbody->endpoint, data, unit_size);\n\t\t\t\tdata += unit_size;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n}", "label": 1, "label_name": "safe"} -{"code": "\tpublic function update() {\n global $user;\n\n if (expSession::get('customer-signup')) expSession::set('customer-signup', false);\n if (isset($this->params['address_country_id'])) {\n $this->params['country'] = $this->params['address_country_id'];\n unset($this->params['address_country_id']);\n }\n if (isset($this->params['address_region_id'])) {\n $this->params['state'] = $this->params['address_region_id'];\n unset($this->params['address_region_id']);\n }\n\t\tif ($user->isLoggedIn()) {\n\t\t\t// check to see how many other addresses this user has already.\n\t\t\t$count = $this->address->find('count', 'user_id='.$user->id);\n\t\t\t// if this is first address save for this user we'll make this the default\n\t\t\tif ($count == 0)\n {\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1;\n }\n\t\t\t// associate this address with the current user.\n\t\t\t$this->params['user_id'] = $user->id;\n\t\t\t// save the object\n\t\t\t$this->address->update($this->params);\n\t\t}\n else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){\n //user is not logged in, but allow anonymous checkout is enabled so we'll check\n //a few things that we don't check in the parent 'stuff and create a user account.\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1;\n $this->address->update($this->params);\n }\n\t\texpHistory::back();\n\t}", "label": 1, "label_name": "safe"} -{"code": "(c=c.getParent());c=!c.$.offsetHeight}return!!(a^c)}};CKEDITOR.dom.walker.nodeType=function(a,b){return function(c){return!!(b^c.type==a)}};CKEDITOR.dom.walker.bogus=function(a){function b(a){return!h(a)&&!m(a)}return function(c){var f=CKEDITOR.env.needsBrFiller?c.is&&c.is(\"br\"):c.getText&&g.test(c.getText());if(f){f=c.getParent();c=c.getNext(b);f=f.isBlockBoundary()&&(!c||c.type==CKEDITOR.NODE_ELEMENT&&c.isBlockBoundary())}return!!(a^f)}};CKEDITOR.dom.walker.temp=function(a){return function(b){b.type!=", "label": 1, "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, "label_name": "safe"} -{"code": " public ExecutableResult Execute(string value)\n {\n try\n {\n Statics.ShouldPollXenStore = false;\n _logger.Log(String.Format(\"XenTools Update value: {0}\\r\\nWill resume in 60 seconds\", value));\n _sleeper.Sleep(60);\n _connectionChecker.Check();\n var agentUpdateInfo = _agentUpdateMessageHandler.Handle(value);\n _downloader.Download(agentUpdateInfo.url, Constants.XenToolsReleasePackage);\n _checksumValidator.Validate(agentUpdateInfo.signature, Constants.XenToolsReleasePackage);\n _unzipper.Unzip(Constants.XenToolsReleasePackage, Constants.XenToolsUnzipPath, \"\");\n _installer.Install(new Dictionary\n {\n {Constants.XenToolsSetupExecutablePath,\n String.Format(\"/S /norestart /D={0}\", Constants.XenToolsPath)}\n });\n _serviceRestarter.Restart(\"xensvc\");\r\n if (_serviceRestarter.ServiceExists(\"XenServerVssProvider\"))\r\n _serviceRestarter.Restart(\"XenServerVssProvider\");\r\n Statics.ShouldPollXenStore = true;\n return new ExecutableResult();\n }\n catch (Exception ex)\n {\n _logger.Log(String.Format(\"Exception was : {0}\\nStackTrace Was: {1}\", ex.Message, ex.StackTrace));\n return new ExecutableResult { Error = new List { \"Update failed\" }, ExitCode = \"1\" };\n }\n finally\n {\n _finalizer.Finalize(new List{Constants.XenToolsUnzipPath,Constants.XenToolsReleasePackage});\n }\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "TEST_CASE(\"Start rule with ignore operator test\", \"[general]\")\n{\n parser parser(R\"(\n ~ROOT <- _\n _ <- ' '\n )\");\n\n bool ret = parser;\n REQUIRE(ret == false);\n}", "label": 1, "label_name": "safe"} -{"code": "find_link_ref(struct link_ref **references, uint8_t *name, size_t length)\n{\n\tunsigned int hash = hash_link_ref(name, length);\n\tstruct link_ref *ref = NULL;\n\n\tref = references[hash % REF_TABLE_SIZE];\n\n\twhile (ref != NULL) {\n\t\tif (ref->id == hash && ref->label->size == length) {\n\t\t\tif (strncasecmp((char *)ref->label->data, (char *) name, length) == 0) {\n\t\t\t\treturn ref;\n\t\t\t}\n\t\t}\n\n\t\tref = ref->next;\n\t}\n\n\treturn NULL;\n}", "label": 1, "label_name": "safe"} -{"code": " private function findVariables()\n {\n $variables = array();\n\n foreach ($_SERVER as $key => $value) {\n if (0 === strpos($key, $this->prefix)) {\n $variables[$key] = $value;\n }\n }\n\n ksort($variables);\n\n return $variables;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\"keydown\",mxUtils.bind(this,function(N){mxEvent.isConsumed(N)||((mxEvent.isControlDown(N)||mxClient.IS_MAC&&mxEvent.isMetaDown(N))&&13==N.keyCode?(I.click(),mxEvent.consume(N)):27==N.keyCode&&(u.click(),mxEvent.consume(N)))}));I.focus();I.className=\"geCommentEditBtn gePrimaryBtn\";ta.appendChild(I);U.insertBefore(ta,R);ia.style.display=\"none\";R.style.display=\"none\";la.focus()}function f(ja,U){U.innerText=\"\";ja=new Date(ja.modifiedDate);var J=b.timeSince(ja);null==J&&(J=mxResources.get(\"lessThanAMinute\"));\nmxUtils.write(U,mxResources.get(\"timeAgo\",[J],\"{1} ago\"));U.setAttribute(\"title\",ja.toLocaleDateString()+\" \"+ja.toLocaleTimeString())}function g(ja){var U=document.createElement(\"img\");U.className=\"geCommentBusyImg\";U.src=IMAGE_PATH+\"/spin.gif\";ja.appendChild(U);ja.busyImg=U}function m(ja){ja.style.border=\"1px solid red\";ja.removeChild(ja.busyImg)}function q(ja){ja.style.border=\"\";ja.removeChild(ja.busyImg)}function y(ja,U,J,V,P){function R(T,Q,Z){var na=document.createElement(\"li\");na.className=", "label": 1, "label_name": "safe"} -{"code": " public function __sleep()\n {\n return array('token', 'parent', 'children', 'collectors', 'ip', 'method', 'url', 'time');\n }", "label": 0, "label_name": "vulnerable"} -{"code": " topic: (function () {\n var x = { a: 1 };\n dotty.remove(x, \"a\");\n return x;\n })(),", "label": 1, "label_name": "safe"} -{"code": "\tpublic function update() {\n global $user;\n\n if (expSession::get('customer-signup')) expSession::set('customer-signup', false);\n if (isset($this->params['address_country_id'])) {\n $this->params['country'] = $this->params['address_country_id'];\n unset($this->params['address_country_id']);\n }\n if (isset($this->params['address_region_id'])) {\n $this->params['state'] = $this->params['address_region_id'];\n unset($this->params['address_region_id']);\n }\n\t\tif ($user->isLoggedIn()) {\n\t\t\t// check to see how many other addresses this user has already.\n\t\t\t$count = $this->address->find('count', 'user_id='.$user->id);\n\t\t\t// if this is first address save for this user we'll make this the default\n\t\t\tif ($count == 0)\n {\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1;\n }\n\t\t\t// associate this address with the current user.\n\t\t\t$this->params['user_id'] = $user->id;\n\t\t\t// save the object\n\t\t\t$this->address->update($this->params);\n\t\t}\n else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){\n //user is not logged in, but allow anonymous checkout is enabled so we'll check\n //a few things that we don't check in the parent 'stuff and create a user account.\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1;\n $this->address->update($this->params);\n }\n\t\texpHistory::back();\n\t}", "label": 1, "label_name": "safe"} -{"code": "\t\ttwitch.show = function () {\n\t\t\ttwitchContainer.style.display = '';\n\t\t};", "label": 0, "label_name": "vulnerable"} -{"code": "mrb_remove_method(mrb_state *mrb, struct RClass *c, mrb_sym mid)\n{\n mt_tbl *h;\n\n MRB_CLASS_ORIGIN(c);\n h = c->mt;\n\n if (h && mt_del(mrb, h, mid)) return;\n mrb_name_error(mrb, mid, \"method '%n' not defined in %C\", mid, c);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "v.apply(this,arguments)};m.getLinkForCell=function(){return null};var y=m.view.getState(q);k=m.getAllConnectionConstraints(y);for(var A=0;null!=k&&An_col_offset = n->n_col_offset + col_offset;\n for (i = 0; i < NCH(n); ++i) {\n if (n->n_lineno && n->n_lineno < CHILD(n, i)->n_lineno) {\n /* Shifting column offsets unnecessary if there's been newlines. */\n col_offset = 0;\n }\n fstring_shift_node_locations(CHILD(n, i), lineno, col_offset);\n }\n n->n_lineno = n->n_lineno + lineno;\n}", "label": 1, "label_name": "safe"} -{"code": " public function testAutoCloseColgroup()\n {\n $this->assertResult(\n '
    ',\n '
    '\n );\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic int decryptWithAd(byte[] ad, byte[] ciphertext,\n\t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n\t\t\tint length) throws ShortBufferException, BadPaddingException {\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 (length > space)\n\t\t\tthrow new ShortBufferException();\n\t\tif (plaintextOffset > plaintext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = plaintext.length - plaintextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the ciphertext 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(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (length < 16)\n\t\t\tNoise.throwBadTagException();\n\t\tint dataLen = length - 16;\n\t\tif (dataLen > space)\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tpoly.update(ciphertext, ciphertextOffset, dataLen);\n\t\tfinish(ad, dataLen);\n\t\tint temp = 0;\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\ttemp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]);\n\t\tif ((temp & 0xFF) != 0)\n\t\t\tNoise.throwBadTagException();\n\t\tencrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);\n\t\treturn dataLen;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def _redirect_safe(self, url, default=None):\n \"\"\"Redirect if url is on our PATH\n\n Full-domain redirects are allowed if they pass our CORS origin checks.\n\n Otherwise use default (self.base_url if unspecified).\n \"\"\"\n if default is None:\n default = self.base_url\n # protect chrome users from mishandling unescaped backslashes.\n # \\ is not valid in urls, but some browsers treat it as /\n # instead of %5C, causing `\\\\` to behave as `//`\n url = url.replace(\"\\\\\", \"%5C\")\n parsed = urlparse(url)\n if parsed.netloc or not (parsed.path + '/').startswith(self.base_url):\n # require that next_url be absolute path within our path\n allow = False\n # OR pass our cross-origin check\n if parsed.netloc:\n # if full URL, run our cross-origin check:\n origin = '%s://%s' % (parsed.scheme, parsed.netloc)\n origin = origin.lower()\n if self.allow_origin:\n allow = self.allow_origin == origin\n elif self.allow_origin_pat:\n allow = bool(self.allow_origin_pat.match(origin))\n if not allow:\n # not allowed, use default\n self.log.warning(\"Not allowing login redirect to %r\" % url)\n url = default\n self.redirect(url)", "label": 1, "label_name": "safe"} -{"code": "func (m *MockRequester) GetRequestedAudience() fosite.Arguments {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetRequestedAudience\")\n\tret0, _ := ret[0].(fosite.Arguments)\n\treturn ret0\n}", "label": 1, "label_name": "safe"} -{"code": "\"pagecount\"==F?null!=c.pages?c.pages.length:1:M.apply(this,arguments)};var n=e.labelLinkClicked;e.labelLinkClicked=function(F,G,N){var J=G.getAttribute(\"href\");if(null==J||!e.isCustomLink(J)||!mxEvent.isTouchEvent(N)&&mxEvent.isPopupTrigger(N))n.apply(this,arguments);else{if(!e.isEnabled()||null!=F&&e.isCellLocked(F.cell))e.customLinkClicked(J),e.getRubberband().reset();mxEvent.consume(N)}};this.editor.getOrCreateFilename=function(){var F=c.defaultFilename,G=c.getCurrentFile();null!=G&&(F=null!=G.getTitle()?\nG.getTitle():F);return F};var x=this.actions.get(\"print\");x.setEnabled(!mxClient.IS_IOS||!navigator.standalone);x.visible=x.isEnabled();if(!this.editor.chromeless||this.editor.editable)this.keyHandler.bindAction(70,!0,\"findReplace\"),this.keyHandler.bindAction(67,!0,\"copyStyle\",!0),this.keyHandler.bindAction(86,!0,\"pasteStyle\",!0),this.keyHandler.bindAction(77,!0,\"editGeometry\",!0),this.keyHandler.bindAction(88,!0,\"insertText\",!0),this.keyHandler.bindAction(75,!0,\"insertRectangle\"),this.keyHandler.bindAction(75,", "label": 1, "label_name": "safe"} -{"code": "b){a==f?(this.getValue()||this.isChanged())&&b.setAttribute(\"alt\",this.getValue()):4==a?b.setAttribute(\"alt\",this.getValue()):8==a&&b.removeAttribute(\"alt\")}},{type:\"hbox\",children:[{id:\"basic\",type:\"vbox\",children:[{type:\"hbox\",requiredContent:\"img{width,height}\",widths:[\"50%\",\"50%\"],children:[{type:\"vbox\",padding:1,children:[{type:\"text\",width:\"45px\",id:\"txtWidth\",label:c.lang.common.width,onKeyUp:w,onChange:function(){i.call(this,\"advanced:txtdlgGenStyle\")},validate:function(){var a=this.getValue().match(v);\n(a=!!(a&&0!==parseInt(a[1],10)))||alert(c.lang.common.invalidWidth);return a},setup:y,commit:function(a,b,d){var c=this.getValue();a==f?(c?b.setStyle(\"width\",CKEDITOR.tools.cssLength(c)):b.removeStyle(\"width\"),!d&&b.removeAttribute(\"width\")):4==a?c.match(k)?b.setStyle(\"width\",CKEDITOR.tools.cssLength(c)):(a=this.getDialog().originalElement,\"true\"==a.getCustomData(\"isReady\")&&b.setStyle(\"width\",a.$.width+\"px\")):8==a&&(b.removeAttribute(\"width\"),b.removeStyle(\"width\"))}},{type:\"text\",id:\"txtHeight\",", "label": 1, "label_name": "safe"} -{"code": "b.mode==App.MODE_DEVICE?mxResources.get(\"device\"):b.mode==App.MODE_BROWSER&&mxResources.get(\"browser\");if(!mxClient.IS_CHROMEAPP&&!EditorUi.isElectronApp)if(l=function(v){t.style.marginBottom=\"24px\";var x=document.createElement(\"a\");x.style.display=\"inline-block\";x.style.color=\"gray\";x.style.cursor=\"pointer\";x.style.marginTop=\"6px\";mxUtils.write(x,mxResources.get(\"signOut\"));t.style.marginBottom=\"16px\";u.style.paddingBottom=\"18px\";mxEvent.addListener(x,\"click\",function(){b.confirm(mxResources.get(\"areYouSure\"),\nfunction(){v()})});u.appendChild(x)},b.mode==App.MODE_GOOGLE&&null!=b.drive){var m=b.drive.getUsersList();if(0getMockHttpResponse('UpdateCardSuccess.txt');\n $response = new Response($this->getMockRequest(), $httpResponse->json());\n\n $this->assertTrue($response->isSuccessful());\n $this->assertFalse($response->isRedirect());\n $this->assertNull($response->getTransactionReference());\n $this->assertSame('cus_1MZeNih5LdKxDq', $response->getCardReference());\n $this->assertNull($response->getMessage());\n }", "label": 0, "label_name": "vulnerable"} -{"code": "function isDate(value) {\n\treturn toString.call(value) === \"[object Date]\";\n}", "label": 1, "label_name": "safe"} -{"code": " function get_allowed_files_extensions_for_upload($fileTypes = 'images', $returnAsArray = false)\n {\n\n $are_allowed = '';\n switch ($fileTypes) {\n\n case 'img':\n case 'image':\n case 'images':\n $are_allowed .= ',png,gif,jpg,jpeg,tiff,bmp,svg,webp,ico';\n break;\n case 'audio':\n case 'audios':\n $are_allowed .= ',mp3,mp4,ogg,wav,flac';\n break;\n case 'video':\n case 'videos':\n $are_allowed .= ',avi,asf,mpg,mpeg,mp4,flv,mkv,webm,ogg,ogv,3gp,3g2,wma,mov,wmv';\n break;\n case 'file':\n case 'files':\n $are_allowed .= ',css,json,zip,gzip,psd,csv,7z';\n break;\n case 'documents':\n case 'doc':\n $are_allowed .= ',doc,docx,pdf,odt,rtf,txt,pps,ppt,pptx,xls,xlsx';\n break;\n case 'archives':\n case 'arc':\n case 'arch':\n $are_allowed .= ',zip,zipx,gzip,rar,gz,7z,cbr,tar.gz';\n break;\n case 'all':\n $are_allowed .= ',*';\n break;\n case '*':\n $are_allowed .= ',*';\n break;\n default:\n $are_allowed .= ',' . $fileTypes;\n }\n\n if($are_allowed){\n $are_allowed = explode(',',$are_allowed);\n array_unique($are_allowed);\n $are_allowed = array_filter($are_allowed);\n\n if ($returnAsArray) {\n return $are_allowed;\n }\n\n $are_allowed = implode(',', $are_allowed);\n }\n\n if ($returnAsArray) {\n return [];\n }\n\n return $are_allowed;\n }", "label": 1, "label_name": "safe"} -{"code": " public function getRemovingPasses()\n {\n return $this->removingPasses;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];", "label": 0, "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.i18 || dir.name, info.i18 || 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": 1, "label_name": "safe"} -{"code": " private function hash_hmac_sha1($key, $data) {\n if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) {\n return hash_hmac('sha1', $data, $key, true);\n } else {\n $blocksize = 64;\n $hashfunc = 'sha1';\n if (strlen($key) > $blocksize) {\n $key = pack('H*', $hashfunc($key));\n }\n\n $key = str_pad($key, $blocksize, chr(0x00));\n $ipad = str_repeat(chr(0x36), $blocksize);\n $opad = str_repeat(chr(0x5c), $blocksize);\n $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));\n\n return $hash;\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function save($check_notify = false)\n {\n if (isset($_POST['email_recipients']) && is_array($_POST['email_recipients'])) {\n $this->email_recipients = base64_encode(serialize($_POST['email_recipients']));\n }\n\n return parent::save($check_notify);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "int verify_iovec(struct msghdr *m, struct iovec *iov, struct sockaddr_storage *address, int mode)\n{\n\tint size, ct, err;\n\n\tif (m->msg_namelen) {\n\t\tif (mode == VERIFY_READ) {\n\t\t\tvoid __user *namep;\n\t\t\tnamep = (void __user __force *) m->msg_name;\n\t\t\terr = move_addr_to_kernel(namep, m->msg_namelen,\n\t\t\t\t\t\t address);\n\t\t\tif (err < 0)\n\t\t\t\treturn err;\n\t\t}\n\t\tif (m->msg_name)\n\t\t\tm->msg_name = address;\n\t} else {\n\t\tm->msg_name = NULL;\n\t}\n\n\tsize = m->msg_iovlen * sizeof(struct iovec);\n\tif (copy_from_user(iov, (void __user __force *) m->msg_iov, size))\n\t\treturn -EFAULT;\n\n\tm->msg_iov = iov;\n\terr = 0;\n\n\tfor (ct = 0; ct < m->msg_iovlen; ct++) {\n\t\tsize_t len = iov[ct].iov_len;\n\n\t\tif (len > INT_MAX - err) {\n\t\t\tlen = INT_MAX - err;\n\t\t\tiov[ct].iov_len = len;\n\t\t}\n\t\terr += len;\n\t}\n\n\treturn err;\n}", "label": 1, "label_name": "safe"} -{"code": "\t\tpublic static function upload_user_avatar() {\n\t\t\t$user_id = get_current_user_id();\n\n\t\t\tif ( ! $user_id ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t$file = $_FILES['lp-upload-avatar'];\n\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();\n\n\t\t\tadd_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\n\t\t\t$file_info_arr = explode( '.', $file['name'] );\n\t\t\t$file_info_arr_length = count( $file_info_arr );\n\t\t\t$file_ext_index = $file_info_arr_length - 1;\n\t\t\t$file_ext = $file_info_arr[ $file_ext_index ];\n\t\t\t$file['name'] = $user_id . '.' . $file_ext;\n\n\t\t\t// Delete old image if exists\n\t\t\t$path_img = get_user_meta( $user_id, '_lp_profile_picture', true );\n\t\t\tif ( $path_img ) {\n\t\t\t\t$path = $upload_dir['basedir'] . '/' . $path_img;\n\t\t\t\tif ( file_exists( $path ) ) {\n\t\t\t\t\t@unlink( $path );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$result = wp_handle_upload(\n\t\t\t\t$file,\n\t\t\t\tarray(\n\t\t\t\t\t'test_form' => false,\n\t\t\t\t)\n\t\t\t);\n\n\t\t\tremove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\t\t\tif ( is_array( $result ) ) {\n\t\t\t\t$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );\n\t\t\t\tupdate_user_meta( $user_id, '_lp_profile_picture', $result['name'] );\n\t\t\t\tunset( $result['file'] );\n\t\t\t} else {\n\t\t\t\t$result = array(\n\t\t\t\t\t'error' => __( 'Profile picture upload failed', 'learnpress' ),\n\t\t\t\t);\n\t\t\t}\n\t\t\tlearn_press_send_json( $result );\n\t\t}", "label": 1, "label_name": "safe"} -{"code": "a.styles[\"font-style\"]}]],underline:[\"u\",[\"span\",function(a){return\"underline\"==a.styles[\"text-decoration\"]}]],strike:[\"s\",\"strike\",[\"span\",function(a){return\"line-through\"==a.styles[\"text-decoration\"]}]],subscript:[\"sub\"],superscript:[\"sup\"]},b=c.config,a=c.lang.basicstyles;d(\"Bold\",a.bold,\"bold\",b.coreStyles_bold);d(\"Italic\",a.italic,\"italic\",b.coreStyles_italic);d(\"Underline\",a.underline,\"underline\",b.coreStyles_underline);d(\"Strike\",a.strike,\"strike\",b.coreStyles_strike);d(\"Subscript\",a.subscript,", "label": 1, "label_name": "safe"} -{"code": " public function testAllowed()\n {\n $this->config->set('CSS.AllowedFonts', array('serif', 'Times New Roman'));\n\n $this->assertDef('serif');\n $this->assertDef('sans-serif', false);\n $this->assertDef('serif, sans-serif', 'serif');\n $this->assertDef('Times New Roman', \"'Times New Roman'\");\n $this->assertDef(\"'Times New Roman'\");\n $this->assertDef('foo', false);\n }", "label": 1, "label_name": "safe"} -{"code": " public function parseMultiFile($file)\n {\n if (!file_exists($file)) {\n return false;\n }\n $ret = array();\n $fh = fopen($file, 'r');\n if (!$fh) {\n return false;\n }\n while (!feof($fh)) {\n $ret[] = $this->parseHandle($fh);\n }\n fclose($fh);\n return $ret;\n }", "label": 1, "label_name": "safe"} -{"code": "v*x.width+A),x.y+x.height-p)},function(x,p){var v=Math.max(0,Math.min(1,mxUtils.getValue(this.state.style,\"position\",ja.prototype.position)));this.state.style.base=Math.round(Math.max(0,Math.min(x.width,p.x-x.x-v*x.width)))},!1)];mxUtils.getValue(c.style,mxConstants.STYLE_ROUNDED,!1)&&l.push(kb(c));return l},internalStorage:function(c){var l=[fb(c,[\"dx\",\"dy\"],function(x){var p=Math.max(0,Math.min(x.width,mxUtils.getValue(this.state.style,\"dx\",ab.prototype.dx))),v=Math.max(0,Math.min(x.height,mxUtils.getValue(this.state.style,\n\"dy\",ab.prototype.dy)));return new mxPoint(x.x+p,x.y+v)},function(x,p){this.state.style.dx=Math.round(Math.max(0,Math.min(x.width,p.x-x.x)));this.state.style.dy=Math.round(Math.max(0,Math.min(x.height,p.y-x.y)))},!1)];mxUtils.getValue(c.style,mxConstants.STYLE_ROUNDED,!1)&&l.push(kb(c));return l},module:function(c){return[fb(c,[\"jettyWidth\",\"jettyHeight\"],function(l){var x=Math.max(0,Math.min(l.width,mxUtils.getValue(this.state.style,\"jettyWidth\",va.prototype.jettyWidth))),p=Math.max(0,Math.min(l.height,", "label": 0, "label_name": "vulnerable"} -{"code": "func GenerateCryptoString(n int) (string, error) {\n\tconst chars = \"123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\tret := make([]byte, n)\n\tfor i := range ret {\n\t\tnum, err := crand.Int(crand.Reader, big.NewInt(int64(len(chars))))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tret[i] = chars[num.Int64()]\n\t}\n\n\treturn string(ret), nil\n}", "label": 1, "label_name": "safe"} -{"code": "spnego_gss_complete_auth_token(\n\t\tOM_uint32 *minor_status,\n\t\tconst gss_ctx_id_t context_handle,\n\t\tgss_buffer_t input_message_buffer)\n{\n\tOM_uint32 ret;\n\tret = gss_complete_auth_token(minor_status,\n\t\t\t\t context_handle,\n\t\t\t\t input_message_buffer);\n\treturn (ret);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "static void follow_dotdot(struct nameidata *nd)\n{\n\tif (!nd->root.mnt)\n\t\tset_root(nd);\n\n\twhile(1) {\n\t\tstruct dentry *old = nd->path.dentry;\n\n\t\tif (nd->path.dentry == nd->root.dentry &&\n\t\t nd->path.mnt == nd->root.mnt) {\n\t\t\tbreak;\n\t\t}\n\t\tif (nd->path.dentry != nd->path.mnt->mnt_root) {\n\t\t\t/* rare case of legitimate dget_parent()... */\n\t\t\tnd->path.dentry = dget_parent(nd->path.dentry);\n\t\t\tdput(old);\n\t\t\tbreak;\n\t\t}\n\t\tif (!follow_up(&nd->path))\n\t\t\tbreak;\n\t}\n\tfollow_mount(&nd->path);\n\tnd->inode = nd->path.dentry->d_inode;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "async function SubmitOrder(req, res, buysell)\n{\n try\n {\n const dataParsed = url.parse(req.url);\n if (!dataParsed || !dataParsed.query || !req.headers['apisign']) throw new Error('Bad request');\n\n const queryStr = querystring.parse(dataParsed.query);\n if (!queryStr.apikey || !queryStr.nonce || !queryStr.market || !queryStr.quantity || !queryStr.rate) throw new Error('Bad request. Required parameter (apikey or nonce or market or quantity or rate) not found.');\n \n const currency = queryStr.market.split('-');\n if (!currency.length || currency.length != 2) throw new Error('Bad request. Parameter currency is invalid.');\n \n const coin = await utils.GetCoinFromTicker(currency[1]); //, coin => {\n if (!coin || !coin.name) \n return onError(req, res, 'Coin ticker not found');\n\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\n \n CheckAPIkey(queryStr.apikey, req.headers['apisign'], fullUrl, ret => {\n try\n {\n if (ret.success == false) throw new Error(ret.message);\n if (ret.key.write == 0) throw new Error('apikey disabled for write');\n \n const request = {\n session_status: {active: true, id: ret.key.userid},\n body: {order: buysell, coin: coin.name, amount: queryStr.quantity, price: queryStr.rate},\n callback: function(ret)\n {\n if (!ret || ret.result != true)\n return onError(req, res, ret ? ret.message || 'Unexpected error': 'Unexpected error');\n \n return onSuccess(req, res, ret.data);\n }\n };\n orders.SubmitOrder(request, null);\n }\n catch(e) {\n return onError(req, res, e.message);\n }\n })\n //}); \n }\n catch(e) {\n return onError(req, res, e.message);\n }\n \n}", "label": 1, "label_name": "safe"} -{"code": "int HexInStream::overrun(int itemSize, int nItems, bool wait) {\n if (itemSize > bufSize)\n throw Exception(\"HexInStream overrun: max itemSize exceeded\");\n\n if (end - ptr != 0)\n memmove(start, ptr, end - ptr);\n\n end -= ptr - start;\n offset += ptr - start;\n ptr = start;\n\n while (end < ptr + itemSize) {\n int n = in_stream.check(2, 1, wait);\n if (n == 0) return 0;\n const U8* iptr = in_stream.getptr();\n const U8* eptr = in_stream.getend();\n int length = min((eptr - iptr)/2, start + bufSize - end);\n\n U8* optr = (U8*) end;\n for (int i=0; i end - ptr)\n nItems = (end - ptr) / itemSize;\n\n return nItems;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "int regexec(Reprog *prog, const char *sp, Resub *sub, int eflags)\n{\n\tResub scratch;\n\tint i;\n\n\tif (!sub)\n\t\tsub = &scratch;\n\n\tsub->nsub = prog->nsub;\n\tfor (i = 0; i < MAXSUB; ++i)\n\t\tsub->sub[i].sp = sub->sub[i].ep = NULL;\n\n\treturn !match(prog->start, sp, sp, prog->flags | eflags, sub);\n}", "label": 0, "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[std::min(maxSaltLength, 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": 1, "label_name": "safe"} -{"code": " em: (content: string) => {\n const em = document.createElement(\"em\");\n em.textContent = content;\n return em;\n },", "label": 1, "label_name": "safe"} -{"code": " $scope.save = function() {\n var form = this.fsForm;\n RequisitionsService.startTiming();\n RequisitionsService.saveForeignSourceDefinition($scope.foreignSourceDef).then(\n function() { // success\n growl.success('The definition for the requisition ' + $scope.foreignSource + ' has been saved.');\n form.$dirty = false;\n },\n $scope.errorHandler\n );\n };", "label": 0, "label_name": "vulnerable"} -{"code": "\tprivate static async Task ResponsePointsBalance(EAccess access, string botNames) {\n\t\tif (!Enum.IsDefined(access)) {\n\t\t\tthrow new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess));\n\t\t}\n\n\t\tif (string.IsNullOrEmpty(botNames)) {\n\t\t\tthrow new ArgumentNullException(nameof(botNames));\n\t\t}\n\n\t\tHashSet? bots = Bot.GetBots(botNames);\n\n\t\tif ((bots == null) || (bots.Count == 0)) {\n\t\t\treturn access >= EAccess.Owner ? FormatStaticResponse(string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)) : null;\n\t\t}\n\n\t\tIList results = await Utilities.InParallel(bots.Select(bot => bot.Commands.ResponsePointsBalance(access))).ConfigureAwait(false);\n\n\t\tList responses = new(results.Where(static result => !string.IsNullOrEmpty(result))!);\n\n\t\treturn responses.Count > 0 ? string.Join(Environment.NewLine, responses) : null;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *,\n\t\tinfop, int, options, struct rusage __user *, ru)\n{\n\tstruct rusage r;\n\tstruct waitid_info info = {.status = 0};\n\tlong err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL);\n\tint signo = 0;\n\tif (err > 0) {\n\t\tsigno = SIGCHLD;\n\t\terr = 0;\n\t}\n\n\tif (!err) {\n\t\tif (ru && copy_to_user(ru, &r, sizeof(struct rusage)))\n\t\t\treturn -EFAULT;\n\t}\n\tif (!infop)\n\t\treturn err;\n\n\tuser_access_begin();\n\tunsafe_put_user(signo, &infop->si_signo, Efault);\n\tunsafe_put_user(0, &infop->si_errno, Efault);\n\tunsafe_put_user(info.cause, &infop->si_code, Efault);\n\tunsafe_put_user(info.pid, &infop->si_pid, Efault);\n\tunsafe_put_user(info.uid, &infop->si_uid, Efault);\n\tunsafe_put_user(info.status, &infop->si_status, Efault);\n\tuser_access_end();\n\treturn err;\nEfault:\n\tuser_access_end();\n\treturn -EFAULT;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "seamless_process(STREAM s)\n{\n\tunsigned int pkglen;\n\tchar *buf;\n\tstruct stream packet = *s;\n\n\tif (!s_check(s))\n\t{\n\t\trdp_protocol_error(\"seamless_process(), stream is in unstable state\", &packet);\n\t}\n\n\tpkglen = s->end - s->p;\n\t/* str_handle_lines requires null terminated strings */\n\tbuf = xmalloc(pkglen + 1);\n\tSTRNCPY(buf, (char *) s->p, pkglen + 1);\n\tstr_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL);\n\n\txfree(buf);\n}", "label": 1, "label_name": "safe"} -{"code": " getDownloadUrl(id, accessToken) {\n return this.importExport.getDownloadUrl(id, accessToken);\n },", "label": 0, "label_name": "vulnerable"} -{"code": " public function setUp()\n {\n parent::setUp();\n $this->config->set('HTML.SafeScripting', array('http://localhost/foo.js'));\n }", "label": 1, "label_name": "safe"} -{"code": "def _inject_metadata_into_fs(metadata, fs, execute=None):\n metadata = dict([(m.key, m.value) for m in metadata])\n _inject_file_into_fs(fs, 'meta.js', jsonutils.dumps(metadata))", "label": 1, "label_name": "safe"} -{"code": " def test_invalid(self, args, message):\n with pytest.raises(SystemExit, match=re.escape(message)):\n qutebrowser._validate_untrusted_args(args)", "label": 1, "label_name": "safe"} -{"code": "static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_blkcipher rblkcipher;\n\n\tstrncpy(rblkcipher.type, \"blkcipher\", sizeof(rblkcipher.type));\n\tstrncpy(rblkcipher.geniv, alg->cra_blkcipher.geniv ?: \"\",\n\t\tsizeof(rblkcipher.geniv));\n\n\trblkcipher.blocksize = alg->cra_blocksize;\n\trblkcipher.min_keysize = alg->cra_blkcipher.min_keysize;\n\trblkcipher.max_keysize = alg->cra_blkcipher.max_keysize;\n\trblkcipher.ivsize = alg->cra_blkcipher.ivsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,\n\t\t sizeof(struct crypto_report_blkcipher), &rblkcipher))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label": 1, "label_name": "safe"} -{"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;\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 TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = input->dims->data[0];\n output_size->data[1] = input->dims->data[1];\n output_size->data[2] = input->dims->data[2];\n output_size->data[3] = input->dims->data[3];\n\n return context->ResizeTensor(context, output, output_size);\n}", "label": 1, "label_name": "safe"} -{"code": "function set (obj, path, value) {\n if(!obj) throw new Error('libnested.set: first arg must be an object')\n if(isBasic(path)) return obj[path] = value\n for(var i = 0; i < path.length; i++) {\n if (isPrototypePolluted(path[i]))\n continue\n\n if(i === path.length - 1)\n obj[path[i]] = value\n else if(null == obj[path[i]])\n obj = (obj[path[i]] = isNonNegativeInteger(path[i+1]) ? [] : {})\n else\n obj = obj[path[i]]\n }\n return value\n}", "label": 1, "label_name": "safe"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $filter = $this->getCustomFilter($project);\n\n $this->response->html($this->helper->layout->project('custom_filter/remove', array(\n 'project' => $project,\n 'filter' => $filter,\n 'title' => t('Remove a custom filter')\n )));\n }", "label": 1, "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?\n\"1\":null},G.getVerticesAndEdges())},{install:function(J){this.listener=function(){J(Editor.sketchMode)};E.addListener(\"sketchModeChanged\",this.listener)},destroy:function(){E.removeListener(this.listener)}});C.appendChild(P)}return C};var t=Menus.prototype.init;Menus.prototype.init=function(){t.apply(this,arguments);var C=this.editorUi,E=C.editor.graph;C.actions.get(\"editDiagram\").label=mxResources.get(\"formatXml\")+\"...\";C.actions.get(\"createShape\").label=mxResources.get(\"shape\")+\"...\";C.actions.get(\"outline\").label=", "label": 1, "label_name": "safe"} -{"code": " function wrapmessage(title, message, count, ago, persistent) {\n let html = '


    ' + title + '

    ' + message + '

    ';\n\n let additional = '';\n\n if (count > 1) additional += client.translate('Event repeated %1 times.', count) + ' ';\n let units = client.translate('minutes');\n if (ago > 60) {\n ago = ago / 60;\n ago = Math.round((ago + Number.EPSILON) * 10) / 10;\n units = client.translate('hours');\n }\n if (ago == 0) { ago = client.translate('less than 1'); }\n if (!persistent && ago) additional += client.translate('Last recorded %1 %2 ago.', ago, units);\n\n if (additional) html += '

    ' + additional + '

    '\n return html;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "hstoreArrayToPairs(ArrayType *a, int *npairs)\n{\n\tDatum\t *key_datums;\n\tbool\t *key_nulls;\n\tint\t\t\tkey_count;\n\tPairs\t *key_pairs;\n\tint\t\t\tbufsiz;\n\tint\t\t\ti,\n\t\t\t\tj;\n\n\tdeconstruct_array(a,\n\t\t\t\t\t TEXTOID, -1, false, 'i',\n\t\t\t\t\t &key_datums, &key_nulls, &key_count);\n\n\tif (key_count == 0)\n\t{\n\t\t*npairs = 0;\n\t\treturn NULL;\n\t}\n\n\t/*\n\t * A text array uses at least eight bytes per element, so any overflow in\n\t * \"key_count * sizeof(Pairs)\" is small enough for palloc() to catch.\n\t * However, credible improvements to the array format could invalidate\n\t * that assumption. Therefore, use an explicit check rather than relying\n\t * on palloc() to complain.\n\t */\n\tif (key_count > MaxAllocSize / sizeof(Pairs))\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),\n\t\t\t errmsg(\"number of pairs (%d) exceeds the maximum allowed (%d)\",\n\t\t\t\t\t key_count, (int) (MaxAllocSize / sizeof(Pairs)))));\n\n\tkey_pairs = palloc(sizeof(Pairs) * key_count);\n\n\tfor (i = 0, j = 0; i < key_count; i++)\n\t{\n\t\tif (!key_nulls[i])\n\t\t{\n\t\t\tkey_pairs[j].key = VARDATA(key_datums[i]);\n\t\t\tkey_pairs[j].keylen = VARSIZE(key_datums[i]) - VARHDRSZ;\n\t\t\tkey_pairs[j].val = NULL;\n\t\t\tkey_pairs[j].vallen = 0;\n\t\t\tkey_pairs[j].needfree = 0;\n\t\t\tkey_pairs[j].isnull = 1;\n\t\t\tj++;\n\t\t}\n\t}\n\n\t*npairs = hstoreUniquePairs(key_pairs, j, &bufsiz);\n\n\treturn key_pairs;\n}", "label": 1, "label_name": "safe"} -{"code": "static char *get_pid_environ_val(pid_t pid,char *val){\n char temp[500];\n int i=0;\n int foundit=0;\n FILE *fp;\n\n sprintf(temp,\"/proc/%d/environ\",pid);\n\n fp=fopen(temp,\"r\");\n if(fp==NULL)\n return NULL;\n\n \n for(;;){\n temp[i]=fgetc(fp); \n\n if(foundit==1 && (temp[i]==0 || temp[i]=='\\0' || temp[i]==EOF)){\n char *ret;\n temp[i]=0;\n ret=malloc(strlen(temp)+10);\n sprintf(ret,\"%s\",temp);\n fclose(fp);\n return ret;\n }\n\n switch(temp[i]){\n case EOF:\n fclose(fp);\n return NULL;\n case '=':\n temp[i]=0;\n if(!strcmp(temp,val)){\n\tfoundit=1;\n }\n i=0;\n break;\n case '\\0':\n i=0;\n break;\n default:\n i++;\n }\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should autorequire the file it manages\" do\n catalog = Puppet::Resource::Catalog.new\n file = Puppet::Type.type(:file).new(:name => \"/tmp/path\")\n catalog.add_resource file\n catalog.add_resource file_line\n\n relationship = file_line.autorequire.find do |rel|\n (rel.source.to_s == \"File[/tmp/path]\") and (rel.target.to_s == file_line.to_s)\n end\n expect(relationship).to be_a Puppet::Relationship\n end", "label": 0, "label_name": "vulnerable"} -{"code": "bool ArcMemory::Read(void *Data,size_t Size,size_t &Result)\n{\n if (!Loaded)\n return false;\n Result=(size_t)Min(Size,ArcData.Size()-SeekPos);\n memcpy(Data,&ArcData[(size_t)SeekPos],Result);\n SeekPos+=Result;\n return true;\n}", "label": 1, "label_name": "safe"} -{"code": " protected function getFormattedContext()\n {\n return implode(' in ', array_reverse($this->context));\n }", "label": 1, "label_name": "safe"} -{"code": " def create_code_for_user(cls, user, next=None):\n if not user.is_active:\n return None\n\n login_code = LoginCode(user=user)\n if next is not None:\n login_code.next = next\n login_code.save()\n return login_code", "label": 1, "label_name": "safe"} -{"code": " def test_received_nonsense_nothing(self):\n data = b\"\\r\\n\\r\\n\"\n result = self.parser.received(data)\n self.assertEqual(result, 4)\n self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", "label": 1, "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, "label_name": "safe"} -{"code": "window.parent.document.domain;break}catch(c){a=a?a.replace(/.+?(?:\\.|$)/,\"\"):document.domain;if(!a)break;document.domain=a}return!!a},eventsBuffer:function(a,c){function d(){e=(new Date).getTime();g=false;c()}var g,e=0;return{input:function(){if(!g){var c=(new Date).getTime()-e;c Union[Endpoint, ParseError]:\n \"\"\" Construct an endpoint from the OpenAPI data \"\"\"\n\n if data.operationId is None:\n return ParseError(data=data, detail=\"Path operations with operationId are not yet supported\")\n\n endpoint = Endpoint(\n path=path,\n method=method,\n description=data.description,\n name=data.operationId,\n requires_security=bool(data.security),\n tag=tag,\n )\n\n result = Endpoint._add_parameters(endpoint, data)\n if isinstance(result, ParseError):\n return result\n result = Endpoint._add_responses(result, data.responses)\n if isinstance(result, ParseError):\n return result\n result = Endpoint._add_body(result, data)\n\n return result", "label": 0, "label_name": "vulnerable"} -{"code": " protected PublicKey engineGeneratePublic(\n KeySpec keySpec)\n throws InvalidKeySpecException\n {\n if (keySpec instanceof DHPublicKeySpec)\n {\n try\n {\n return new BCDHPublicKey((DHPublicKeySpec)keySpec);\n }\n catch (IllegalArgumentException e)\n {\n throw new InvalidKeySpecException(e.getMessage(), e);\n }\n }\n\n return super.engineGeneratePublic(keySpec);\n }", "label": 1, "label_name": "safe"} -{"code": "null,null,null,10,null,null,!1,null,0'],{type:\"text/html\"})});navigator.clipboard.write([d])[\"catch\"](m)};EditorUi.prototype.copyCells=function(d,f){var g=this.editor.graph;if(g.isSelectionEmpty())d.innerHTML=\"\";else{var m=", "label": 0, "label_name": "vulnerable"} -{"code": " public static function all_in_array()\r\n {\r\n global $DB;\r\n global $website;\r\n $out = array();\r\n\r\n $DB->query('SELECT *\r\n FROM nv_webuser_groups\r\n WHERE website = '.protect($website->id));\r\n\r\n $rs = $DB->result();\r\n\r\n foreach($rs as $row)\r\n $out[$row->id] = $row->name;\r\n\r\n return $out;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"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 ' + 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 ' + 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 ' + r.foreignSource + ' has been created.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label": 0, "label_name": "vulnerable"} -{"code": " function setAuth($username)\n {\n $this->log('Auth::setAuth() called.', AUTH_LOG_DEBUG);\n\n // #10729 - Regenerate session id here only if generating at login only\n // Don't do it if we are regenerating on every request so we don't\n // regenerate it twice in one request.\n if (!$this->regenerateSessionId) {\n // #2021 - Change the session id to avoid session fixation attacks php 4.3.3 >\n session_regenerate_id(true);\n }\n\n if (!isset($this->session) || !is_array($this->session)) {\n $this->session = array();\n }\n\n if (!isset($this->session['data'])) {\n $this->session['data'] = array();\n }\n\n $this->session['sessionip'] = isset($this->server['REMOTE_ADDR'])\n ? $this->server['REMOTE_ADDR']\n : '';\n $this->session['sessionuseragent'] = isset($this->server['HTTP_USER_AGENT'])\n ? $this->server['HTTP_USER_AGENT']\n : '';\n $this->session['sessionforwardedfor'] = isset($this->server['HTTP_X_FORWARDED_FOR'])\n ? $this->server['HTTP_X_FORWARDED_FOR']\n : '';\n\n // This should be set by the container to something more safe\n // Like md5(passwd.microtime)\n if(empty($this->session['challengekey'])) {\n $this->session['challengekey'] = md5($username.microtime());\n }\n\n $this->session['challengecookie'] = md5($this->session['challengekey'].microtime());\n setcookie('authchallenge', $this->session['challengecookie'], 0, '/');\n\n $this->session['registered'] = true;\n $this->session['username'] = $username;\n $this->session['timestamp'] = time();\n $this->session['idle'] = time();\n }", "label": 0, "label_name": "vulnerable"} -{"code": " it 'should create a warning' do\n pending('rspec-puppet support for testing warning()')\n end", "label": 0, "label_name": "vulnerable"} -{"code": " git.isRepositoryClean = function (cb) {\n return cb(new Error('Not clean'));\n };", "label": 0, "label_name": "vulnerable"} -{"code": "func (*DeleteGroupRequest) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{17}\n}", "label": 0, "label_name": "vulnerable"} -{"code": " def calculated_content_type\n @calculated_content_type ||= type_from_file_command.chomp\n end", "label": 1, "label_name": "safe"} -{"code": " public function setFlashCookieObject($name, $object, $time = 60)\n {\n setcookie($name, json_encode($object, JSON_THROW_ON_ERROR), $this->getCookieOptions($time));\n\n return $this;\n }", "label": 1, "label_name": "safe"} -{"code": " it \"should compile when an explicitly undef variable is passed (NOTE THIS MAY NOT BE DESIRABLE)\" do\n Puppet[:code] = <<-'ENDofPUPPETcode'\n $foo = undef\n validate_string($foo)\n ENDofPUPPETcode\n scope.compiler.compile\n end", "label": 0, "label_name": "vulnerable"} -{"code": " protected function getFoo2Service()\n {\n return $this->services['Foo\\\\Foo'] = new \\Foo\\Foo();\n }", "label": 1, "label_name": "safe"} -{"code": "\t\t\t$tableNames[$table] = $DB->tableName( $table );\n\t\t}\n\n\t\treturn $tableNames;\n\t}", "label": 1, "label_name": "safe"} -{"code": "typeof fa.getAttribute&&null!=fa.getAttribute(\"title\")&&sa.push({img:fa.getAttribute(\"img\"),libs:fa.getAttribute(\"libs\"),clibs:fa.getAttribute(\"clibs\"),title:fa.getAttribute(\"title\")}),fa=fa.nextSibling;F(sa)}});var ra=function(fa,ca,ba){la.style.display=\"\";Ea.stop();W=!1;if(V)V=!1;else if(ca)aa.innerHTML=ca;else{ba=ba||{};ca=0;for(var ja in ba)ca+=ba[ja].length;0==fa.length&&0==ca?aa.innerHTML=mxUtils.htmlEntities(mxResources.get(\"noDiagrams\")):B(fa,!1,O,0==ca?null:ba)}};J(P);var wa=null;mxEvent.addListener(Oa,", "label": 0, "label_name": "vulnerable"} -{"code": "static int snd_ctl_elem_user_put(struct snd_kcontrol *kcontrol,\n\t\t\t\t struct snd_ctl_elem_value *ucontrol)\n{\n\tint change;\n\tstruct user_element *ue = kcontrol->private_data;\n\n\tmutex_lock(&ue->card->user_ctl_lock);\n\tchange = memcmp(&ucontrol->value, ue->elem_data, ue->elem_data_size) != 0;\n\tif (change)\n\t\tmemcpy(ue->elem_data, &ucontrol->value, ue->elem_data_size);\n\tmutex_unlock(&ue->card->user_ctl_lock);\n\treturn change;\n}", "label": 1, "label_name": "safe"} -{"code": " def self.prefetch(resources)\n @user_privs = query_user_privs\n @db_privs = query_db_privs\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should return false if IP octets out of range\" do\n result = scope.function_is_ip_address([\"1.1.1.300\"])\n expect(result).to(eq(false))\n end", "label": 0, "label_name": "vulnerable"} -{"code": " it \"should add modules whose ensure is present\" do\n @filetype.expects(:read).at_least_once.returns(%Q{APACHE2_OPTS=\"\"})\n @filetype.expects(:write).with(%Q{APACHE2_OPTS=\"-D INFO\"})\n\n @info.stubs(:should).with(:ensure).returns(:present)\n provider_class.prefetch(\"info\" => @info)\n\n provider_class.flush\n end", "label": 0, "label_name": "vulnerable"} -{"code": "int jpg_validate(jas_stream_t *in)\n{\n\tuchar buf[JPG_MAGICLEN];\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\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\n\t/* Did we read enough data? */\n\tif (n < JPG_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\t/* Does this look like JPEG? */\n\tif (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testRemove()\n {\n $bag = new ParameterBag(array(\n 'foo' => 'foo',\n 'bar' => 'bar',\n ));\n $bag->remove('foo');\n $this->assertEquals(array('bar' => 'bar'), $bag->all(), '->remove() removes a parameter');\n $bag->remove('BAR');\n $this->assertEquals(array(), $bag->all(), '->remove() converts key to lowercase before removing');\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def get_pacemaker_version()\n begin\n stdout, stderror, retval = run_cmd(\n PCSAuth.getSuperuserSession, PACEMAKERD, \"-$\"\n )\n rescue\n stdout = []\n end\n if retval == 0\n match = /(\\d+)\\.(\\d+)\\.(\\d+)/.match(stdout.join())\n if match\n return match[1..3].collect { | x | x.to_i }\n end\n end\n return nil\nend", "label": 0, "label_name": "vulnerable"} -{"code": " public function testAutoCloseListItem()\n {\n $this->assertResult(\n '
    1. Item 1
    2. Item 2
    ',\n '
    1. Item 1
    2. Item 2
    '\n );\n }", "label": 1, "label_name": "safe"} -{"code": "function generate_key($size)\n{\n if (\n is_callable('openssl_random_pseudo_bytes')\n and !(version_compare(PHP_VERSION, '5.3.4') < 0 and defined('PHP_WINDOWS_VERSION_MAJOR'))\n )\n {\n return substr(\n str_replace(\n array('+', '/'),\n '',\n base64_encode(openssl_random_pseudo_bytes($size+10))\n ),\n 0,\n $size\n );\n }\n else\n {\n $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';\n $l = strlen($alphabet)-1;\n $key = '';\n for ($i=0; $i<$size; $i++)\n {\n $key.= $alphabet[mt_rand(0, $l)];\n }\n return $key;\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": "var get = (module.exports.get = function get(object, path) {\n if (typeof path === \"string\") {\n path = path.split(\".\");\n }\n\n if (!(path instanceof Array) || path.length === 0) {\n return;\n }\n\n path = path.slice();\n\n var key = path.shift();\n\n if (typeof object !== \"object\" || object === null) {\n return;\n }\n\n if (path.length === 0) {\n return object[key];\n }\n\n if (path.length) {\n return get(object[key], path);\n }\n});", "label": 1, "label_name": "safe"} -{"code": " $scope.provision = function() {\n $scope.isSaving = true;\n growl.info('The node ' + _.escape($scope.node.nodeLabel) + ' is being added to requisition ' + _.escape($scope.node.foreignSource) + '. Please wait...');\n var successMessage = 'The node ' + _.escape($scope.node.nodeLabel) + ' has been added to requisition ' + _.escape($scope.node.foreignSource);\n RequisitionsService.quickAddNode($scope.node).then(\n function() { // success\n $scope.reset();\n bootbox.dialog({\n message: successMessage,\n title: 'Success',\n buttons: {\n main: {\n label: 'Ok',\n className: 'btn-secondary'\n }\n }\n });\n },\n $scope.errorHandler\n );\n };", "label": 1, "label_name": "safe"} -{"code": "\tpublic function escape($input)\n\t{\n\t\t// Ensure we have valid correctly encoded string..\n\t\t// http://stackoverflow.com/questions/1412239/why-call-mb-convert-encoding-to-sanitize-text\n\t\t$input = mb_convert_encoding($input, \"UTF-8\", \"UTF-8\");\n\t\t// why are we using html entities? this -> http://stackoverflow.com/a/110576/992171\n\t\treturn htmlentities($input, ENT_QUOTES, 'UTF-8');\n\t}", "label": 1, "label_name": "safe"} -{"code": "App.prototype.descriptorChanged = function()\n{\n\tvar file = this.getCurrentFile();\n\t\n\tif (file != null)\n\t{\n\t\tif (this.fname != null)\n\t\t{\n\t\t\tthis.fnameWrapper.style.display = 'block';\n\t\t\tthis.fname.innerHTML = '';\n\t\t\tvar filename = (file.getTitle() != null) ? file.getTitle() : this.defaultFilename;\n\t\t\tmxUtils.write(this.fname, filename);\n\t\t\tthis.fname.setAttribute('title', filename + ' - ' + mxResources.get('rename'));\n\t\t}\n\t\t\n\t\tvar graph = this.editor.graph;\n\t\tvar editable = file.isEditable() && !file.invalidChecksum;\n\t\t\n\t\tif (graph.isEnabled() && !editable)\n\t\t{\n\t\t\tgraph.reset();\n\t\t}\n\t\t\n\t\tgraph.setEnabled(editable);\n\t\t\n\t\t// Ignores title and hash for revisions\n\t\tif (urlParams['rev'] == null)\n\t\t{\n\t\t\tthis.updateDocumentTitle();\n\t\t\tvar newHash = file.getHash();\n\t\t\t\n\t\t\tif (newHash.length > 0)\n\t\t\t{\n\t\t\t\twindow.location.hash = newHash;\n\t\t\t}\n\t\t\telse if (window.location.hash.length > 0)\n\t\t\t{\n\t\t\t\twindow.location.hash = '';\n\t\t\t}\n\t\t}\n\t}\n\t\n\tthis.updateUi();\n\t\n\t// Refresh if editable state has changed\n\tif (this.format != null && (file == null ||\n\t\tthis.fileEditable != file.isEditable()) &&\n\t\tthis.editor.graph.isSelectionEmpty())\n\t{\n\t\tthis.format.refresh();\n\t\tthis.fileEditable = (file != null) ? file.isEditable() : null;\n\t}\n\t\n\tthis.fireEvent(new mxEventObject('fileDescriptorChanged', 'file', file));\n};", "label": 0, "label_name": "vulnerable"} -{"code": " def make_homeserver(self, reactor, clock):\n\n hs = self.setup_test_homeserver(\n \"red\", federation_http_client=None, federation_client=Mock(),\n )\n\n self.event_source = hs.get_event_sources().sources[\"typing\"]\n\n hs.get_federation_handler = Mock()\n\n async def get_user_by_access_token(token=None, allow_guest=False):\n return {\n \"user\": UserID.from_string(self.auth_user_id),\n \"token_id\": 1,\n \"is_guest\": False,\n }\n\n hs.get_auth().get_user_by_access_token = get_user_by_access_token\n\n async def _insert_client_ip(*args, **kwargs):\n return None\n\n hs.get_datastore().insert_client_ip = _insert_client_ip\n\n def get_room_members(room_id):\n if room_id == self.room_id:\n return defer.succeed([self.user])\n else:\n return defer.succeed([])\n\n @defer.inlineCallbacks\n def fetch_room_distributions_into(\n room_id, localusers=None, remotedomains=None, ignore_user=None\n ):\n members = yield get_room_members(room_id)\n for member in members:\n if ignore_user is not None and member == ignore_user:\n continue\n\n if hs.is_mine(member):\n if localusers is not None:\n localusers.add(member)\n else:\n if remotedomains is not None:\n remotedomains.add(member.domain)\n\n hs.get_room_member_handler().fetch_room_distributions_into = (\n fetch_room_distributions_into\n )\n\n return hs", "label": 1, "label_name": "safe"} -{"code": " public function testSameInstanceWhenSameProtocol()\n {\n $r = new Response();\n $this->assertSame($r, $r->withProtocolVersion('1.1'));\n }", "label": 1, "label_name": "safe"} -{"code": "d.style.height=\"300px\";d.style.width=\"300px\";d.style.display=\"inline-flex\";d.style.justifyContent=\"center\";d.style.alignItems=\"center\";d.style.position=\"absolute\";var g=document.createElement(\"img\");g.onload=function(){function C(){l.model.setStyle(x,y+m())}l=new Graph(k);l.autoExtend=!1;l.autoScroll=!1;l.setGridEnabled(!1);l.setEnabled(!0);l.setPanning(!1);l.setConnectable(!1);l.getRubberband().setEnabled(!1);l.graphHandler.allowLivePreview=!1;var E=l.createVertexHandler;l.createVertexHandler=function(){var K=\nE.apply(this,arguments);K.livePreview=!1;return K};if(null!=f)try{if(\"inset\"==f.substring(0,5)){var G=x.geometry,P=g.width,J=g.height,F=(300-P)/2,H=(300-J)/2,S=f.match(/\\(([^)]+)\\)/)[1].split(/[ ,]+/),V=parseFloat(S[0]),M=parseFloat(S[1]),W=parseFloat(S[2]),U=parseFloat(S[3]);isFinite(V)&&isFinite(M)&&isFinite(W)&&isFinite(U)?(G.x=U/100*P+F,G.y=V/100*J+H,G.width=(100-M)/100*P+F-G.x,G.height=(100-W)/100*J+H-G.y,\"round\"==S[4]?\"50%\"==S[5]?I.setAttribute(\"checked\",\"checked\"):(q=parseInt(S[5]),t.value=", "label": 1, "label_name": "safe"} -{"code": " public function testReservedForPhp7()\n {\n if (PHP_VERSION_ID >= 70000) {\n $this->markTestSkipped('PHP7 already prevents using reserved names.');\n }\n\n set_error_handler(function () { return false; });\n $e = error_reporting(0);\n trigger_error('', E_USER_NOTICE);\n\n class_exists('Test\\\\'.__NAMESPACE__.'\\\\Float', true);\n\n error_reporting($e);\n restore_error_handler();\n\n $lastError = error_get_last();\n unset($lastError['file'], $lastError['line']);\n\n $xError = array(\n 'type' => E_USER_DEPRECATED,\n 'message' => 'Test\\Symfony\\Component\\Debug\\Tests\\Float uses a reserved class name (Float) that will break on PHP 7 and higher',\n );\n\n $this->assertSame($xError, $lastError);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "def feed_authorindex():\n shift = 0\n off = int(request.args.get(\"offset\") or 0)\n entries = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('id'))\\\n .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters())\\\n .group_by(func.upper(func.substr(db.Authors.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_author',\n pagination=pagination)", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\t\tscope.returnThis = function() {\n\t\t\t\t\t\treturn this;\n\t\t\t\t\t};", "label": 1, "label_name": "safe"} -{"code": " /*package*/ Secret(String value) {\n this.value = value;\n }", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": "SFTPWrapper.prototype.ext_openssh_fsync = function(handle, cb) {\n return this._stream.ext_openssh_fsync(handle, cb);\n};", "label": 0, "label_name": "vulnerable"} -{"code": " function removeUser($username)\n {\n $this->log('Auth::removeUser() called.', AUTH_LOG_DEBUG);\n $this->_loadStorage();\n return $this->storage->removeUser($username);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def test_progress(self, driver, live_server, upload_file, freeze_upload_folder):\n driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//input[@name='save']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n assert \"save\" in driver.page_source\n\n driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//button[@name='save_continue']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n response = json.loads(driver.find_elements(By.CSS_SELECTOR, \"pre\")[0].text)\n assert response[\"POST\"][\"progress\"] == \"1\"", "label": 1, "label_name": "safe"} -{"code": " public static function data($vars){\r\n $file = GX_THEME.'/'.$vars.'/themeinfo.php';\r\n $handle = fopen($file, 'r');\r\n $data = fread($handle, filesize($file));\r\n fclose($handle);\r\n preg_match('/\\* Name: (.*)\\n\\*/U', $data, $matches);\r\n $d['name'] = $matches[1];\r\n preg_match('/\\* Desc: (.*)\\n\\*/U', $data, $matches);\r\n $d['desc'] = $matches[1];\r\n preg_match('/\\* Version: (.*)\\n\\*/U', $data, $matches);\r\n $d['version'] = $matches[1];\r\n preg_match('/\\* Build: (.*)\\n\\*/U', $data, $matches);\r\n $d['build'] = $matches[1];\r\n preg_match('/\\* Developer: (.*)\\n\\*/U', $data, $matches);\r\n $d['developer'] = $matches[1];\r\n preg_match('/\\* URI: (.*)\\n\\*/U', $data, $matches);\r\n $d['url'] = $matches[1];\r\n preg_match('/\\* License: (.*)\\n\\*/U', $data, $matches);\r\n $d['license'] = $matches[1];\r\n preg_match('/\\* Icon: (.*)\\n\\*/U', $data, $matches);\r\n $d['icon'] = $matches[1];\r\n return $d;\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": " public static function getBlockSizeInBits($hash) {\n if (isset(static::$hashInfo[$hash]['BlockSize'])) {\n return static::$hashInfo[$hash]['BlockSize'];\n }\n return 0;\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function delete() {\n\t global $user;\n\n $count = $this->address->find('count', 'user_id=' . $user->id);\n if($count > 1)\n { \n $address = new address($this->params['id']);\n\t if ($user->isAdmin() || ($user->id == $address->user_id)) {\n if ($address->is_billing)\n {\n $billAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $billAddress->is_billing = true;\n $billAddress->save();\n }\n if ($address->is_shipping) \n {\n $shipAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $shipAddress->is_shipping = true;\n $shipAddress->save();\n }\n\t parent::delete();\n\t }\n }\n else\n {\n flash(\"error\", gt(\"You must have at least one address.\"));\n }\n\t expHistory::back();\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " function hostbasedCb(buf, cb) {\n var signature = privateKey.sign(buf);\n if (signature instanceof Error) {\n signature.message = 'Error while signing data with privateKey: '\n + signature.message;\n signature.level = 'client-authentication';\n self.emit('error', signature);\n return tryNextAuth();\n }\n\n cb(signature);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def agent_read_access?\n agent_access?('read')\n end", "label": 1, "label_name": "safe"} -{"code": "kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args)\n{\n\tif (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE))\n\t\treturn -EINVAL;\n\tif (args->gsi >= KVM_MAX_IRQ_ROUTES)\n\t\treturn -EINVAL;\n\n\tif (args->flags & KVM_IRQFD_FLAG_DEASSIGN)\n\t\treturn kvm_irqfd_deassign(kvm, args);\n\n\treturn kvm_irqfd_assign(kvm, args);\n}", "label": 1, "label_name": "safe"} -{"code": "eb);this.updateSvgLinks(Da,ua,!0);this.addForeignObjectWarning(eb,Da);return Da}finally{Qa&&(this.useCssTransforms=!0,this.view.revalidate(),this.sizeDidChange())}};Graph.prototype.addForeignObjectWarning=function(z,L){if(\"0\"!=urlParams[\"svg-warning\"]&&0cra_blocksize;\n\trhash.digestsize = salg->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, "label_name": "vulnerable"} -{"code": "z.y,t.width/L,t.height/L,\"fillColor=none;strokeColor=red;\")}));c.actions.addAction(\"testCheckFile\",mxUtils.bind(this,function(){var t=null!=c.pages&&null!=c.getCurrentFile()?c.getCurrentFile().getAnonymizedXmlForPages(c.pages):\"\";t=new TextareaDialog(c,\"Paste Data:\",t,function(z){if(0generator->generateInt(-1, PHP_INT_MAX);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static function main()\n {\n\n PHPUnit_TextUI_TestRunner::run(self::suite());\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected function processBmp()\n {\n $format = 'bmp';\n $compression = \\Imagick::COMPRESSION_UNDEFINED;\n\n $imagick = $this->image->getCore();\n $imagick->setFormat($format);\n $imagick->setImageFormat($format);\n $imagick->setCompression($compression);\n $imagick->setImageCompression($compression);\n\n return $imagick->getImagesBlob();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "bool ItemStackMetadata::setString(const std::string &name, const std::string &var)\n{\n\tstd::string clean_name = name;\n\tstd::string clean_var = var;\n\tsanitize_string(clean_name);\n\tsanitize_string(clean_var);\n\n\tbool result = Metadata::setString(clean_name, clean_var);\n\tif (clean_name == TOOLCAP_KEY)\n\t\tupdateToolCapabilities();\n\treturn result;\n}", "label": 1, "label_name": "safe"} -{"code": " public function test_encode_noChange()\n {\n $this->assertEncode('abc012-_~.');\n }", "label": 1, "label_name": "safe"} -{"code": " def testLSTMBlockCellErrorHandling(self):\n forget_bias = 1\n cell_clip = 0\n use_peephole = False\n x = constant_op.constant(0.837607, shape=[28, 29], dtype=dtypes.float32)\n cs_prev = constant_op.constant(0, shape=[28, 17], dtype=dtypes.float32)\n h_prev = constant_op.constant(\n 0.592631638, shape=[28, 17], dtype=dtypes.float32)\n w = constant_op.constant(0.887386262, shape=[46, 68], dtype=dtypes.float32)\n wci = constant_op.constant(0, shape=[], dtype=dtypes.float32)\n wcf = constant_op.constant(0, shape=[17], dtype=dtypes.float32)\n wco = constant_op.constant(\n 0.592631638, shape=[28, 17], dtype=dtypes.float32)\n b = constant_op.constant(0.75259006, shape=[68], dtype=dtypes.float32)\n with self.assertRaises(errors_impl.InvalidArgumentError):\n self.evaluate(\n gen_rnn_ops.lstm_block_cell(\n x=x,\n cs_prev=cs_prev,\n h_prev=h_prev,\n w=w,\n wci=wci,\n wcf=wcf,\n wco=wco,\n b=b,\n forget_bias=forget_bias,\n cell_clip=cell_clip,\n use_peephole=use_peephole))", "label": 1, "label_name": "safe"} -{"code": "GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP)\n{\n\tint i, j, ret;\n\tunsigned char count;\n\n\tif(flag) {\n\t\tscd->curbit = 0;\n\t\tscd->lastbit = 0;\n\t\tscd->last_byte = 0;\n\t\tscd->done = FALSE;\n\t\treturn 0;\n\t}\n\n\tif((scd->curbit + code_size) >= scd->lastbit) {\n\t\tif(scd->done) {\n\t\t\tif(scd->curbit >= scd->lastbit) {\n\t\t\t\t/* Oh well */\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\n\t\tscd->buf[0] = scd->buf[scd->last_byte - 2];\n\t\tscd->buf[1] = scd->buf[scd->last_byte - 1];\n\n\t\tif((count = GetDataBlock(fd, &scd->buf[2], ZeroDataBlockP)) <= 0) {\n\t\t\tscd->done = TRUE;\n\t\t}\n\n\t\tscd->last_byte = 2 + count;\n\t\tscd->curbit = (scd->curbit - scd->lastbit) + 16;\n\t\tscd->lastbit = (2 + count) * 8;\n\t}\n\n\tret = 0;\n\tfor (i = scd->curbit, j = 0; j < code_size; ++i, ++j) {\n\t\tret |= ((scd->buf[i / 8] & (1 << (i % 8))) != 0) << j;\n\t}\n\n\tscd->curbit += code_size;\n\n\treturn ret;\n}", "label": 0, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " public function test_loadArray()\n {\n // references can be *really* wonky!\n\n $context_manual = new HTMLPurifier_Context();\n $context_load = new HTMLPurifier_Context();\n\n $var1 = 1;\n $var2 = 2;\n\n $context_manual->register('var1', $var1);\n $context_manual->register('var2', $var2);\n\n // you MUST set up the references when constructing the array,\n // otherwise the registered version will be a copy\n $array = array(\n 'var1' => &$var1,\n 'var2' => &$var2\n );\n\n $context_load->loadArray($array);\n $this->assertIdentical($context_manual, $context_load);\n\n $var1 = 10;\n $var2 = 20;\n\n $this->assertIdentical($context_manual, $context_load);\n\n }", "label": 1, "label_name": "safe"} -{"code": " public static function header($vars=\"\"){\r\n header(\"Cache-Control: must-revalidate,max-age=300,s-maxage=900\");\r\n $offset = 60 * 60 * 24 * 3;\r\n $ExpStr = \"Expires: \" . gmdate(\"D, d M Y H:i:s\", time() + $offset) . \" GMT\";\r\n header($ExpStr);\r\n header(\"Content-Type: text/html; charset=utf-8\");\r\n\r\n if (isset($vars)) {\r\n # code...\r\n $GLOBALS['data'] = $vars;\r\n self::theme('header', $vars);\r\n }else{\r\n self::theme('header');\r\n }\r\n\r\n }\r", "label": 0, "label_name": "vulnerable"} -{"code": "S&&S(M)}}))}catch(L){null!=S&&S(L)}}),N,sa)}catch(Ua){null!=S&&S(Ua)}};Editor.crcTable=[];for(var D=0;256>D;D++)for(var t=D,F=0;8>F;F++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[D]=t;Editor.updateCRC=function(u,J,N,W){for(var S=0;S>>8;return u};Editor.crc32=function(u){for(var J=-1,N=0;N>>8^Editor.crcTable[(J^u.charCodeAt(N))&255];return(J^-1)>>>0};Editor.writeGraphModelToPng=function(u,J,N,W,S){function P(sa,Ba){var ta=", "label": 1, "label_name": "safe"} -{"code": "TfLiteStatus Prepare(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* start;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kStartTensor, &start));\n const TfLiteTensor* limit;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kLimitTensor, &limit));\n const TfLiteTensor* delta;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDeltaTensor, &delta));\n // Make sure all the inputs are scalars.\n TF_LITE_ENSURE_EQ(context, NumDimensions(start), 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(limit), 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(delta), 0);\n\n // Currently only supports int32 and float.\n // TODO(b/117912892): Support quantization as well.\n const auto dtype = start->type;\n if (dtype != kTfLiteFloat32 && dtype != kTfLiteInt32) {\n context->ReportError(context, \"Unknown index output data type: %s\",\n TfLiteTypeGetName(dtype));\n return kTfLiteError;\n }\n\n TF_LITE_ENSURE_TYPES_EQ(context, limit->type, dtype);\n TF_LITE_ENSURE_TYPES_EQ(context, delta->type, dtype);\n\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n output->type = dtype;\n\n if (IsConstantTensor(start) && IsConstantTensor(limit) &&\n IsConstantTensor(delta)) {\n return ResizeOutput(context, start, limit, delta, output);\n }\n\n SetTensorToDynamic(output);\n return kTfLiteOk;\n}", "label": 1, "label_name": "safe"} -{"code": " it \"yields a session with the provided options\" do\n session.with(safe: true) do |safe|\n safe.options[:safe].should eq true\n end\n end", "label": 1, "label_name": "safe"} -{"code": " private function EOF()\n {\n $this->state = null;\n $this->tree->emitToken(\n array(\n 'type' => self::EOF\n )\n );\n }", "label": 1, "label_name": "safe"} -{"code": "def _sanitize(value: str) -> str:\n return re.sub(r\"[^\\w _-]+\", \"\", value)", "label": 0, "label_name": "vulnerable"} -{"code": "!1;null!=H&&(S=\"1\"==x.getCurrentCellStyle(H).treeMoving);return S}function t(H){var S=!1;null!=H&&(H=A.getParent(H),S=x.view.getState(H),S=\"tree\"==(null!=S?S.style:x.getCellStyle(H)).containerType);return S}function D(H){var S=!1;null!=H&&(H=A.getParent(H),S=x.view.getState(H),x.view.getState(H),S=null!=(null!=S?S.style:x.getCellStyle(H)).childLayout);return S}function c(H){H=x.view.getState(H);if(null!=H){var S=x.getIncomingTreeEdges(H.cell);if(0H.getCenterX())return mxConstants.DIRECTION_WEST}}return mxConstants.DIRECTION_EAST}function e(H,S){S=null!=S?S:!0;x.model.beginUpdate();try{var U=x.model.getParent(H),Q=x.getIncomingTreeEdges(H),W=x.cloneCells([Q[0],H]);x.model.setTerminal(W[0],x.model.getTerminal(Q[0],", "label": 0, "label_name": "vulnerable"} -{"code": " private function markupDeclarationOpenState()\n {\n /* If the next two characters are both U+002D HYPHEN-MINUS (-)\n characters, consume those two characters, create a comment token whose\n data is the empty string, and switch to the comment state. */\n if($this->character($this->char + 1, 2) === '--') {\n $this->char += 2;\n $this->state = 'comment';\n $this->token = array(\n 'data' => null,\n 'type' => self::COMMENT\n );\n\n /* Otherwise if the next seven chacacters are a case-insensitive match\n for the word \"DOCTYPE\", then consume those characters and switch to the\n DOCTYPE state. */\n } elseif(strtolower($this->character($this->char + 1, 7)) === 'doctype') {\n $this->char += 7;\n $this->state = 'doctype';\n\n /* Otherwise, is is a parse error. Switch to the bogus comment state.\n The next character that is consumed, if any, is the first character\n that will be in the comment. */\n } else {\n $this->char++;\n $this->state = 'bogusComment';\n }\n }", "label": 1, "label_name": "safe"} -{"code": " public function testProcess()\n {\n $container = new ContainerBuilder();\n $container->register('a')->addArgument(new Reference('b'));\n $container->register('b')->addArgument(new Reference('a'));\n\n $this->process($container);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "int mesg_make_query (u_char *qname, uint16_t qtype, uint16_t qclass,\n\t\t uint32_t id, int rd, u_char *buf, int buflen) {\n\tchar *fn = \"mesg_make_query()\";\n\tu_char *ucp;\n\tint i, written_len;\n\tMesg_Hdr *hdr;\n\n\tif (T.debug > 4) { \n\t\tsyslog (LOG_DEBUG, \"%s: (qtype: %s, id: %d): start\", fn,\n\t\t\tstring_rtype (qtype), id);\n }\n\thdr = (Mesg_Hdr *) buf;\n\n\t/* write header */\n\thdr->id = id;\n\thdr->opcode = OP_QUERY;\n\thdr->rcode = RC_OK;\n\thdr->rd = rd;\n\thdr->qr = hdr->aa = hdr->tc = hdr->ra = hdr->zero = 0;\n\thdr->qdcnt = ntohs (1);\n\thdr->ancnt = hdr->nscnt = hdr->arcnt = ntohs (0);\n\n\twritten_len = sizeof (Mesg_Hdr);\n\tucp = (u_char *) (hdr + 1);\n\n\t/* write qname */\n\tif (T.debug > 4)\n\t\tsyslog (LOG_DEBUG, \"%s: qname offset = %zd\", fn, ucp - buf);\n\n\ti = dname_copy (qname, ucp, buflen - written_len);\n\tif (i < 0)\n\t\treturn -1;\n\n\twritten_len += i;\n\tucp += i;\n\n\t/* write qtype / qclass */\n\tif (T.debug > 4)\n\t\tsyslog (LOG_DEBUG, \"%s: qtype/qclass offset = %zd\",\n\t\t\tfn, ucp - buf);\n\n\twritten_len += sizeof (uint16_t) * 2;\n\tif (written_len > buflen)\n\t\treturn -1;\n\n\tPUTSHORT (qtype, ucp);\n\tPUTSHORT (qclass, ucp);\n\n\treturn written_len;\n}", "label": 1, "label_name": "safe"} -{"code": "\t\t\t\t\t\t\t\t\t\t\ttitle : $('input:checked', uitype).val(),\n\t\t\t\t\t\t\t\t\t\t\ttext : 'confirmReq',\n\t\t\t\t\t\t\t\t\t\t\taccept : {\n\t\t\t\t\t\t\t\t\t\t\t\tlabel : 'btnApply',\n\t\t\t\t\t\t\t\t\t\t\t\tcallback : function() { \n\t\t\t\t\t\t\t\t\t\t\t\t\tsave();\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\tcancel : {\n\t\t\t\t\t\t\t\t\t\t\t\tlabel : 'btnCancel',\n\t\t\t\t\t\t\t\t\t\t\t\tcallback : function(){}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\treturn;\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\t\tif (!((c >= 48 && c <= 57) || (c >= 96 && c <= 105))) {\n\t\t\t\t\t\t\t\t\t\te.preventDefault();\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\t.filter(':first').focus();\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tresizable();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\treset.hover(function() { reset.toggleClass('ui-state-hover'); }).click(resetView);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t})", "label": 0, "label_name": "vulnerable"} -{"code": " def to_simple(self, data, options):\n \"\"\"\n For a piece of data, attempts to recognize it and provide a simplified\n form of something complex.\n \n This brings complex Python data structures down to native types of the\n serialization format(s).\n \"\"\"\n if isinstance(data, (list, tuple)):\n return [self.to_simple(item, options) for item in data]\n if isinstance(data, dict):\n return dict((key, self.to_simple(val, options)) for (key, val) in data.iteritems())\n elif isinstance(data, Bundle):\n return dict((key, self.to_simple(val, options)) for (key, val) in data.data.iteritems())\n elif hasattr(data, 'dehydrated_type'):\n if getattr(data, 'dehydrated_type', None) == 'related' and data.is_m2m == False:\n if data.full:\n return self.to_simple(data.fk_resource, options)\n else:\n return self.to_simple(data.value, options)\n elif getattr(data, 'dehydrated_type', None) == 'related' and data.is_m2m == True:\n if data.full:\n return [self.to_simple(bundle, options) for bundle in data.m2m_bundles]\n else:\n return [self.to_simple(val, options) for val in data.value]\n else:\n return self.to_simple(data.value, options)\n elif isinstance(data, datetime.datetime):\n return self.format_datetime(data)\n elif isinstance(data, datetime.date):\n return self.format_date(data)\n elif isinstance(data, datetime.time):\n return self.format_time(data)\n elif isinstance(data, bool):\n return data\n elif type(data) in (long, int, float):\n return data\n elif data is None:\n return None\n else:\n return force_unicode(data)", "label": 0, "label_name": "vulnerable"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " def clean_text(text)\n text.gsub(/[\\u0000-\\u0008\\u000b-\\u000c\\u000e-\\u001F\\u007f]/, \".\".freeze)\n end", "label": 1, "label_name": "safe"} -{"code": " public function get($columns = ['*'])\n {\n if (!is_null($this->cacheMinutes)) {\n $results = $this->getCached($columns);\n }\n else {\n $results = $this->getFresh($columns);\n }\n\n $models = $this->getModels($results ?: []);\n\n return $this->model->newCollection($models);\n }", "label": 1, "label_name": "safe"} -{"code": " public function remove()\n {\n $project = $this->getProject();\n $this->checkCSRFParam();\n $column_id = $this->request->getIntegerParam('column_id');\n\n if ($this->columnModel->remove($column_id)) {\n $this->flash->success(t('Column removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this column.'));\n }\n\n $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));\n }", "label": 0, "label_name": "vulnerable"} -{"code": " protected function _mkfile($path, $name)\n {\n $path = $this->_joinPath($path, $name);\n return $this->connect->put($path, '') ? $path : false;\n/*\n if ($this->tmp) {\n $path = $this->_joinPath($path, $name);\n $local = $this->getTempFile();\n $res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);\n unlink($local);\n return $res ? $path : false;\n }\n\n return false;\n */\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public void handle(HttpServletRequest request, 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 Element body = env.element(\"body\");\n\n // First handle any new subscriptions\n List requests = new ArrayList();\n\n List elements = body.elements(\"subscribe\");\n for (Element e : elements)\n {\n requests.add(new SubscriptionRequest(e.attributeValue(\"topic\")));\n }\n\n ServletLifecycle.beginRequest(request);\n try\n {\n ServletContexts.instance().setRequest(request);\n\n Manager.instance().initializeTemporaryConversation();\n ServletLifecycle.resumeConversation(request);\n\n for (SubscriptionRequest req : requests)\n {\n req.subscribe();\n }\n\n // Then handle any unsubscriptions\n List unsubscribeTokens = new ArrayList();\n\n elements = body.elements(\"unsubscribe\");\n for (Element e : elements) \n {\n unsubscribeTokens.add(e.attributeValue(\"token\"));\n }\n\n for (String token : unsubscribeTokens) \n {\n RemoteSubscriber subscriber = SubscriptionRegistry.instance().\n getSubscription(token);\n if (subscriber != null)\n {\n subscriber.unsubscribe();\n }\n }\n }\n finally\n {\n Lifecycle.endRequest();\n }\n\n // Package up the response\n marshalResponse(requests, response.getOutputStream());\n }", "label": 1, "label_name": "safe"} -{"code": " $message = 'Uncaught '.$exception->getMessage();\n if ($exception instanceof ContextErrorException) {\n $e['context'] = $exception->getContext();\n }\n } else {\n $message = 'Uncaught Exception: '.$exception->getMessage();\n }\n if ($this->loggedErrors & $e['type']) {\n $this->loggers[$e['type']][0]->log($this->loggers[$e['type']][1], $message, $e);\n }\n }\n if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {\n foreach ($this->getFatalErrorHandlers() as $handler) {\n if ($e = $handler->handleError($error, $exception)) {\n $exception = $e;\n break;\n }\n }\n }\n if (empty($this->exceptionHandler)) {\n throw $exception; // Give back $exception to the native handler\n }\n try {\n call_user_func($this->exceptionHandler, $exception);\n } catch (\\Exception $handlerException) {\n } catch (\\Throwable $handlerException) {\n }\n if (isset($handlerException)) {\n $this->exceptionHandler = null;\n $this->handleException($handlerException);\n }\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\t\t\t\t$this->_writeBackup($tmpDir . 'plugin' . DS, $plugin['Plugin']['name'], $encoding);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// ZIP\u5727\u7e2e\u3057\u3066\u51fa\u529b\n\t\t$bcZip = new BcZip();\n\t\t$bcZip->create($tmpDir, $distPath);\n\t\t\n\t\theader(\"Cache-Control: no-store\");\n\t\theader(\"Content-Type: application/zip\");\n\t\theader(\"Content-Disposition: attachment; filename=\" . basename($distPath) . \";\");\n\t\theader(\"Content-Length: \" . filesize($distPath));\n\t\twhile (ob_get_level()) { ob_end_clean(); }\n\t\techo readfile($distPath);\n\t\t\n\t\tunlink($distPath);\n\t\t$this->_resetTmpSchemaFolder();\n\t\treturn true;\n\t}", "label": 1, "label_name": "safe"} -{"code": " public String toString() {\n if (query == null) {\n return path;\n }\n return path + '?' + query;\n }", "label": 1, "label_name": "safe"} -{"code": " $result[] = is_int($key) ? $formattedValue : sprintf(\"'%s' => %s\", $key, $formattedValue);\n }\n\n return implode(', ', $result);\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public function make($string)\n {\n return clone $this->clone;\n }", "label": 1, "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 if (type == kGenericOptimized) {\n optimized_ops::Floor(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } else {\n reference_ops::Floor(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n }\n\n return kTfLiteOk;\n}", "label": 1, "label_name": "safe"} -{"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, "label_name": "vulnerable"} -{"code": " public void Saml2ArtifactBinding_Unbind_FromGet_ArtifactIsntHashOfEntityId()\n {\n var issuer = new EntityId(\"https://idp.example.com\");\n var artifact = Uri.EscapeDataString(\n Convert.ToBase64String(\n Saml2ArtifactBinding.CreateArtifact(\n new EntityId(\"https://this.entityid.is.invalid\"),\n 0x1234)));\n\n var relayState = \"relayState\";\n\n var r = new HttpRequestData(\n \"GET\",\n new Uri($\"http://example.com/path/acs?SAMLart={artifact}&RelayState={relayState}\"),\n null,\n null,\n new StoredRequestState(issuer, null, null, null));\n\n StubServer.LastArtifactResolutionSoapActionHeader = null;\n\n var result = Saml2Binding.Get(Saml2BindingType.Artifact).Unbind(r, StubFactory.CreateOptions());\n\n var xmlDocument = XmlHelpers.XmlDocumentFromString(\n \" \");\n\n var expected = new UnbindResult(xmlDocument.DocumentElement, relayState, TrustLevel.None);\n\n result.Should().BeEquivalentTo(expected);\n StubServer.LastArtifactResolutionWasSigned.Should().BeFalse();\n }", "label": 0, "label_name": "vulnerable"} -{"code": "App.Actions.DB.update_db_databasename_hint = function(elm, hint) {\n if (hint.trim() == '') {\n $(elm).parent().find('.hint').html('');\n } \n $(elm).parent().find('.hint').text(GLOBAL.DB_DBNAME_PREFIX + hint);\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public function testEmptyString()\n {\n $this->assertTextOutput('', '');\n }", "label": 1, "label_name": "safe"} -{"code": " public function testPreserveIDWhenEnabled()\n {\n $this->assertResult('
    Preserve the ID.
    ');\n }", "label": 1, "label_name": "safe"} -{"code": "\tList cleanForKeySlow(String key) {\n\t\tkey = StringUtils.trin(StringUtils.goLowerCase(key));\n\t\tkey = key.replaceAll(\"_|\\\\.\", \"\");\n\t\t// key = replaceSmart(key, \"partition\", \"package\");\n\t\tkey = replaceSmart(key, \"sequenceparticipant\", \"participant\");\n\t\tkey = replaceSmart(key, \"sequenceactor\", \"actor\");\n\t\tkey = key.replaceAll(\"activityarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"objectarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"classarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"componentarrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"statearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"usecasearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"sequencearrow\", \"arrow\");\n\t\tkey = key.replaceAll(\"align$\", \"alignment\");\n\t\tfinal Matcher2 mm = stereoPattern.matcher(key);\n\t\tfinal List result = new ArrayList<>();\n\t\twhile (mm.find()) {\n\t\t\tfinal String s = mm.group(1);\n\t\t\tresult.add(key.replaceAll(stereoPatternString, \"\") + \"<<\" + s + \">>\");\n\t\t}\n\t\tif (result.size() == 0)\n\t\t\tresult.add(key);\n\n\t\treturn Collections.unmodifiableList(result);\n\t}", "label": 1, "label_name": "safe"} -{"code": " protected function _mkdir($path, $name)\n {\n $path = $this->_joinPath($path, $name);\n if ($this->connect->mkdir($path) === false) {\n return false;\n }\n\n $this->options['dirMode'] && $this->connect->chmod($this->options['dirMode'], $path);\n return $path;\n }", "label": 0, "label_name": "vulnerable"} -{"code": " $text = sanitize_text_field($agent);\r\n $agents[] = $text;\r\n }\r\n }\r\n \r\n if (sizeof($agents) > 1)\r\n {\r\n sort( $agents );\r\n $agents = array_unique($agents, SORT_STRING);\r\n }\r\n \r\n $banned_user_agent_data = implode(PHP_EOL, $agents);\r\n $aio_wp_security->configs->set_value('aiowps_banned_user_agents',$banned_user_agent_data);\r\n $_POST['aiowps_banned_user_agents'] = ''; //Clear the post variable for the banned address list\r\n return 1;\r\n }\r", "label": 0, "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, "label_name": "vulnerable"} -{"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, "label_name": "safe"} -{"code": " public function removePathPrefix($path)\n {\n $pathPrefix = $this->getPathPrefix();\n\n if ($pathPrefix === null) {\n return $path;\n }\n\n return substr($path, strlen($pathPrefix));\n }", "label": 0, "label_name": "vulnerable"} -{"code": "\tpublic function formatList( $articles, $start, $count ) {\n\t\t$filteredCount = 0;\n\t\t$items = [];\n\n\t\tfor ( $i = $start; $i < $start + $count; $i++ ) {\n\t\t\t$article = $articles[$i];\n\n\t\t\tif ( empty( $article ) || empty( $article->mTitle ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$pageText = null;\n\t\t\tif ( $this->includePageText ) {\n\t\t\t\t$pageText = $this->transcludePage( $article, $filteredCount );\n\t\t\t} else {\n\t\t\t\t$filteredCount++;\n\t\t\t}\n\n\t\t\t$this->rowCount = $filteredCount++;\n\n\t\t\t$parts = explode( '/', $article->mTitle );\n\t\t\t$item = $this->formatItem( $article, $pageText );\n\t\t\t$items = $this->nestItem( $parts, $items, $item );\n\t\t}\n\n\t\treturn $this->getListStart() . $this->implodeItems( $items ) . $this->listEnd;\n\t}", "label": 1, "label_name": "safe"} -{"code": " def ajax_move_mails\n Log.add_info(request, params.inspect)\n\n return unless request.post?\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, "label_name": "safe"} -{"code": " public function delete()\n {\n $this->validateFileName();\n\n list($name, $extension) = $this->model->getFileNameParts();\n\n return $this->datasource->delete(\n $this->model->getObjectTypeDirName(),\n $name,\n $extension\n );\n }", "label": 1, "label_name": "safe"} -{"code": "func Render(tmpl string, s *types.Step) (types.StepSlice, error) {\n\tbuffer := new(bytes.Buffer)\n\tconfig := new(types.Build)\n\n\tvelaFuncs := funcHandler{envs: convertPlatformVars(s.Environment)}\n\ttemplateFuncMap := map[string]interface{}{\n\t\t\"vela\": velaFuncs.returnPlatformVar,\n\t}\n\t// modify Masterminds/sprig functions\n\t// to remove OS functions\n\t//\n\t// https://masterminds.github.io/sprig/os.html\n\tsf := sprig.TxtFuncMap()\n\tdelete(sf, \"env\")\n\tdelete(sf, \"expandenv\")\n\n\t// parse the template with Masterminds/sprig functions\n\t//\n\t// https://pkg.go.dev/github.com/Masterminds/sprig?tab=doc#TxtFuncMap\n\tt, err := template.New(s.Name).Funcs(sf).Funcs(templateFuncMap).Parse(tmpl)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to parse template %s: %v\", s.Template.Name, err)\n\t}\n\n\t// apply the variables to the parsed template\n\terr = t.Execute(buffer, s.Template.Variables)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to execute template %s: %v\", s.Template.Name, err)\n\t}\n\n\t// unmarshal the template to the pipeline\n\terr = yaml.Unmarshal(buffer.Bytes(), config)\n\tif err != nil {\n\t\treturn types.StepSlice{}, fmt.Errorf(\"unable to unmarshal yaml: %v\", err)\n\t}\n\n\t// ensure all templated steps have template prefix\n\tfor index, newStep := range config.Steps {\n\t\tconfig.Steps[index].Name = fmt.Sprintf(\"%s_%s\", s.Name, newStep.Name)\n\t}\n\n\treturn config.Steps, nil\n}", "label": 1, "label_name": "safe"} -{"code": " public function testDataWithCard()\n {\n $card = $this->getValidCard();\n $this->request->setCard($card);\n $data = $this->request->getData();\n\n $this->assertSame($card['number'], $data['card']['number']);\n }", "label": 0, "label_name": "vulnerable"} -{"code": "int mongo_env_write_socket( mongo *conn, const void *buf, int len ) {\n const char *cbuf = buf;\n int flags = 0;\n\n while ( len ) {\n int sent = send( conn->sock, cbuf, len, flags );\n if ( sent == -1 ) {\n __mongo_set_error( conn, MONGO_IO_ERROR, NULL, WSAGetLastError() );\n conn->connected = 0;\n return MONGO_ERROR;\n }\n cbuf += sent;\n len -= sent;\n }\n\n return MONGO_OK;\n}", "label": 0, "label_name": "vulnerable"} -{"code": "inline TfLiteStatus ValidateTensorIndexingSafe(const TfLiteContext* context,\n int index, int max_size,\n const int* tensor_indices,\n int* tensor_index) {\n if (index < 0 || index >= max_size) {\n TF_LITE_KERNEL_LOG(const_cast(context),\n \"Invalid tensor index %d (not in [0, %d))\\n\", index,\n max_size);\n return kTfLiteError;\n }\n if (tensor_indices[index] == kTfLiteOptionalTensor) {\n TF_LITE_KERNEL_LOG(const_cast(context),\n \"Tensor at index %d was optional but was expected\\n\",\n index);\n return kTfLiteError;\n }\n\n *tensor_index = tensor_indices[index];\n return kTfLiteOk;\n}", "label": 1, "label_name": "safe"} -{"code": "integerify(void * B, size_t r)\n{\n uint32_t * X = (uint32_t *)((uintptr_t)(B) + (2 * r - 1) * 64);\n\n return (((uint64_t)(X[13]) << 32) + X[0]);\n}", "label": 0, "label_name": "vulnerable"} -{"code": "function usercheck_init_noacess(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 and underscores';\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 return;\r\n }\r\n\r\n var pqr = i.value;\r\n if (i.value.length >= 3)\r\n ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_noacess, usercheck_error);\r\n}\r", "label": 0, "label_name": "vulnerable"} -{"code": "lspci_process(STREAM s)\n{\n\tunsigned int pkglen;\n\tstatic char *rest = NULL;\n\tchar *buf;\n\tstruct stream packet = *s;\n\n\tif (!s_check(s))\n\t{\n\t\trdp_protocol_error(\"lspci_process(), stream is in unstable state\", &packet);\n\t}\n\n\tpkglen = s->end - s->p;\n\t/* str_handle_lines requires null terminated strings */\n\tbuf = xmalloc(pkglen + 1);\n\tSTRNCPY(buf, (char *) s->p, pkglen + 1);\n\tstr_handle_lines(buf, &rest, lspci_process_line, NULL);\n\txfree(buf);\n}", "label": 1, "label_name": "safe"} -{"code": " protected function transformAttrToAssoc($node_map)\n {\n // NamedNodeMap is documented very well, so we're using undocumented\n // features, namely, the fact that it implements Iterator and\n // has a ->length attribute\n if ($node_map->length === 0) {\n return array();\n }\n $array = array();\n foreach ($node_map as $attr) {\n $array[$attr->name] = $attr->value;\n }\n return $array;\n }", "label": 1, "label_name": "safe"} -{"code": " public DHParameterSpec ike2048()\n {\n final BigInteger p = new BigInteger(\n \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74\"\n + \"020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437\"\n + \"4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed\"\n + \"ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05\"\n + \"98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb\"\n + \"9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b\"\n + \"e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718\"\n + \"3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff\", 16);\n final BigInteger g = new BigInteger(\"2\");\n return new DHParameterSpec(p, g);\n }", "label": 1, "label_name": "safe"} -{"code": " protected function processDataUrl()\n {\n $mime = $this->image->mime ? $this->image->mime : 'image/png';\n\n return sprintf('data:%s;base64,%s',\n $mime,\n base64_encode($this->process($this->image, $mime, $this->quality))\n );\n }", "label": 0, "label_name": "vulnerable"} -{"code": " context.suite = function(title){\n if (suites.length > 1) suites.shift();\n var suite = Suite.create(suites[0], title);\n suites.unshift(suite);\n return suite;\n };", "label": 0, "label_name": "vulnerable"} -{"code": "function timingSafeEquals(a, b) {\n if (a.length !== b.length) {\n timingSafeEqual(a, a);\n return false;\n }\n return timingSafeEqual(a, b);\n}", "label": 1, "label_name": "safe"} -{"code": " 'readYAML': function(test) {\n test.expect(4);\n var obj;\n obj = grunt.file.readYAML('test/fixtures/utf8.yaml');\n test.deepEqual(obj, this.object, 'file should be read as utf8 by default and parsed correctly.');\n\n obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml', {encoding: 'iso-8859-1'});\n test.deepEqual(obj, this.object, 'file should be read using the specified encoding.');\n\n test.throws(function() {\n obj = grunt.file.readYAML('test/fixtures/error.yaml');\n }, function(err) {\n return err.message.indexOf('undefined') === -1;\n }, 'error thrown should not contain undefined.');\n\n grunt.file.defaultEncoding = 'iso-8859-1';\n obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml');\n test.deepEqual(obj, this.object, 'changing the default encoding should work.');\n test.done();\n },", "label": 0, "label_name": "vulnerable"} -{"code": "!0);V.init()}))})})}));d.actions.put(\"liveImage\",new Action(\"Live image...\",function(){var n=d.getCurrentFile();null!=n&&d.spinner.spin(document.body,mxResources.get(\"loading\"))&&d.getPublicUrl(d.getCurrentFile(),function(y){d.spinner.stop();null!=y?(y=new EmbedDialog(d,''),d.showDialog(y.container,450,240,!0,!0),y.init()):d.handleError({message:mxResources.get(\"invalidPublicUrl\")})})}));d.actions.put(\"embedImage\",", "label": 0, "label_name": "vulnerable"} -{"code": " public void shouldCheckConnectionWithEscapedRepoUrl() {\n assertThatThrownBy(() -> hgCommand.checkConnection(new UrlArgument(echoingAliasFor(\"id\"))))\n .isExactlyInstanceOf(CommandLineException.class)\n .hasMessageContaining(\"repository --config\")\n .hasMessageContaining(\"not found\");\n }", "label": 1, "label_name": "safe"} -{"code": " protected function setUp()\n {\n static::$functions = [];\n static::$fopen = null;\n static::$fread = null;\n parent::setUp();\n $this->security = new ExposedSecurity();\n $this->security->derivationIterations = 1000; // speed up test running\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public void translate(GeyserSession session, ServerSetSubtitleTextPacket packet) {\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.SUBTITLE);\n titlePacket.setText(text);\n titlePacket.setXuid(\"\");\n titlePacket.setPlatformOnlineId(\"\");\n session.sendUpstreamPacket(titlePacket);\n }", "label": 1, "label_name": "safe"} -{"code": "void FormatConverter::InitSparseToDenseConverter(\n std::vector shape, std::vector traversal_order,\n std::vector format, std::vector dense_size,\n std::vector> segments,\n std::vector> indices, std::vector block_map) {\n dense_shape_ = std::move(shape);\n traversal_order_ = std::move(traversal_order);\n block_map_ = std::move(block_map);\n format_ = std::move(format);\n\n dense_size_ = 1;\n for (int i = 0; i < dense_shape_.size(); i++) {\n dense_size_ *= dense_shape_[i];\n }\n\n dim_metadata_.resize(2 * format_.size());\n for (int i = 0; i < format_.size(); i++) {\n if (format_[i] == kTfLiteDimDense) {\n dim_metadata_[2 * i] = {dense_size[i]};\n } else {\n dim_metadata_[2 * i] = std::move(segments[i]);\n dim_metadata_[2 * i + 1] = std::move(indices[i]);\n }\n }\n\n int original_rank = dense_shape_.size();\n int block_dim = 0;\n\n blocked_shape_.resize(original_rank);\n block_size_.resize(block_map_.size());\n for (int i = 0; i < original_rank; i++) {\n if (block_dim < block_map_.size() && block_map_[block_dim] == i) {\n int orig_dim = traversal_order_[original_rank + block_dim];\n block_size_[block_dim] = dense_size[orig_dim];\n blocked_shape_[i] = dense_shape_[i] / dense_size[orig_dim];\n block_dim++;\n } else {\n blocked_shape_[i] = dense_shape_[i];\n }\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " function edit_option_master() {\n expHistory::set('editable', $this->params);\n\n $params = isset($this->params['id']) ? $this->params['id'] : $this->params;\n $record = new option_master($params);\n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label": 1, "label_name": "safe"} -{"code": "\tpublic FromSkinparamToStyle(String key) {\n\n\t\tif (key.contains(\"<<\")) {\n\t\t\tfinal StringTokenizer st = new StringTokenizer(key, \"<>\");\n\t\t\tthis.key = st.nextToken();\n\t\t\tthis.stereo = st.hasMoreTokens() ? st.nextToken() : null;\n\t\t} else {\n\t\t\tthis.key = key;\n\t\t\tthis.stereo = null;\n\t\t}\n\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": " def mget(*keys)\n options = (keys.pop if keys.last.is_a? Hash) || {}\n if keys.any?\n # Marshalling gets extended before Namespace does, so we need to pass options further\n if singleton_class.ancestors.include? Marshalling\n super(*keys.map {|key| interpolate(key) }, options)\n else\n super(*keys.map {|key| interpolate(key) })\n end\n end\n end", "label": 0, "label_name": "vulnerable"} -{"code": " def do_send\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n begin\n email = Email.find(params[:id])\n\n if email.status != Email::STATUS_DRAFT\n # Ignore clicked Send button twice or more at once.\n raise('ERROR:' + 'Specified E-mail is not a draft.')\n end\n\n mail_account = MailAccount.find(email.mail_account_id)\n if mail_account.user_id != @login_user.id\n raise('ERROR:' + t('msg.need_to_be_owner'))\n end\n\n sent_folder = MailFolder.get_for(@login_user, mail_account.id, MailFolder::XTYPE_SENT)\n email.do_smtp(mail_account)\n\n attrs = ActionController::Parameters.new({status: Email::STATUS_TRANSMITTED, mail_folder_id: sent_folder.id, sent_at: Time.now})\n email.update_attributes(attrs.permit(Email::PERMIT_BASE))\n\n flash[:notice] = t('msg.transmit_success')\n rescue => evar\n Log.add_error(request, evar)\n flash[:notice] = 'ERROR:' + t('msg.transmit_failed') + '
    ' + evar.to_s\n end\n\n render(:partial => 'common/flash_notice', :layout => false)\n end", "label": 1, "label_name": "safe"} -{"code": "\tstep: function(gotoEnd){\n\t\tvar t = now();\n\n\t\tif ( gotoEnd || t >= this.options.duration + this.startTime ) {\n\t\t\tthis.now = this.end;\n\t\t\tthis.pos = this.state = 1;\n\t\t\tthis.update();\n\n\t\t\tthis.options.curAnim[ this.prop ] = true;\n\n\t\t\tvar done = true;\n\t\t\tfor ( var i in this.options.curAnim )\n\t\t\t\tif ( this.options.curAnim[i] !== true )\n\t\t\t\t\tdone = false;\n\n\t\t\tif ( done ) {\n\t\t\t\tif ( this.options.display != null ) {\n\t\t\t\t\t// Reset the overflow\n\t\t\t\t\tthis.elem.style.overflow = this.options.overflow;\n\n\t\t\t\t\t// Reset the display\n\t\t\t\t\tthis.elem.style.display = this.options.display;\n\t\t\t\t\tif ( jQuery.css(this.elem, \"display\") == \"none\" )\n\t\t\t\t\t\tthis.elem.style.display = \"block\";\n\t\t\t\t}\n\n\t\t\t\t// Hide the element if the \"hide\" operation was done\n\t\t\t\tif ( this.options.hide )\n\t\t\t\t\tjQuery(this.elem).hide();\n\n\t\t\t\t// Reset the properties, if the item has been hidden or shown\n\t\t\t\tif ( this.options.hide || this.options.show )\n\t\t\t\t\tfor ( var p in this.options.curAnim )\n\t\t\t\t\t\tjQuery.attr(this.elem.style, p, this.options.orig[p]);\n\t\t\t\t\t\n\t\t\t\t// Execute the complete function\n\t\t\t\tthis.options.complete.call( this.elem );\n\t\t\t}\n\n\t\t\treturn false;\n\t\t} else {\n\t\t\tvar n = t - this.startTime;\n\t\t\tthis.state = n / this.options.duration;\n\n\t\t\t// Perform the easing function, defaults to swing\n\t\t\tthis.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? \"swing\" : \"linear\")](this.state, n, 0, 1, this.options.duration);\n\t\t\tthis.now = this.start + ((this.end - this.start) * this.pos);\n\n\t\t\t// Perform the next step of the animation\n\t\t\tthis.update();\n\t\t}\n\n\t\treturn true;\n\t}", "label": 0, "label_name": "vulnerable"} -{"code": "ast_for_comp_op(struct compiling *c, const node *n)\n{\n /* comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'\n |'is' 'not'\n */\n REQ(n, comp_op);\n if (NCH(n) == 1) {\n n = CHILD(n, 0);\n switch (TYPE(n)) {\n case LESS:\n return Lt;\n case GREATER:\n return Gt;\n case EQEQUAL: /* == */\n return Eq;\n case LESSEQUAL:\n return LtE;\n case GREATEREQUAL:\n return GtE;\n case NOTEQUAL:\n return NotEq;\n case NAME:\n if (strcmp(STR(n), \"in\") == 0)\n return In;\n if (strcmp(STR(n), \"is\") == 0)\n return Is;\n /* fall through */\n default:\n PyErr_Format(PyExc_SystemError, \"invalid comp_op: %s\",\n STR(n));\n return (cmpop_ty)0;\n }\n }\n else if (NCH(n) == 2) {\n /* handle \"not in\" and \"is not\" */\n switch (TYPE(CHILD(n, 0))) {\n case NAME:\n if (strcmp(STR(CHILD(n, 1)), \"in\") == 0)\n return NotIn;\n if (strcmp(STR(CHILD(n, 0)), \"is\") == 0)\n return IsNot;\n /* fall through */\n default:\n PyErr_Format(PyExc_SystemError, \"invalid comp_op: %s %s\",\n STR(CHILD(n, 0)), STR(CHILD(n, 1)));\n return (cmpop_ty)0;\n }\n }\n PyErr_Format(PyExc_SystemError, \"invalid comp_op: has %d children\",\n NCH(n));\n return (cmpop_ty)0;\n}", "label": 1, "label_name": "safe"} -{"code": "def help_page(page_slug: str) -> str:\n \"\"\"Fava's included documentation.\"\"\"\n if page_slug not in HELP_PAGES:\n abort(404)\n html = markdown2.markdown_path(\n (resource_path(\"help\") / (page_slug + \".md\")),\n extras=[\"fenced-code-blocks\", \"tables\", \"header-ids\"],\n )\n return render_template(\n \"_layout.html\",\n active_page=\"help\",\n page_slug=page_slug,\n help_html=render_template_string(\n html,\n beancount_version=beancount_version,\n fava_version=fava_version,\n ),\n HELP_PAGES=HELP_PAGES,\n )", "label": 0, "label_name": "vulnerable"} -{"code": " public WebSocketEventListener(List endpoints)\n : this(endpoints, new WebSocketListenerOptions())\n {\n }", "label": 0, "label_name": "vulnerable"} -{"code": " public static function verify($gresponse)\n {\n new self();\n $recaptcha = new \\ReCaptcha\\ReCaptcha(self::$secret);\n $resp = $recaptcha->verify($gresponse, $_SERVER['REMOTE_ADDR']);\n if ($resp->isSuccess()) {\n return true;\n } else {\n return false;\n }\n }", "label": 1, "label_name": "safe"} -{"code": " def GetAction2( // use GetActionRateLimited instead!\n rateLimits: RateLimits,\n minAuthnStrength: MinAuthnStrength = MinAuthnStrength.Normal,\n )(f: GetRequest => Result): Action[Unit] =\n PlainApiAction(cc.parsers.empty, rateLimits, minAuthnStrength)(f)", "label": 1, "label_name": "safe"} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\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 switch (input1->type) {\n case kTfLiteInt32: {\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_div.\",\n TfLiteTypeGetName(input1->type));\n return kTfLiteError;\n }\n }\n}", "label": 0, "label_name": "vulnerable"} -{"code": " public static function referenceFixtures () {\n return array (\n 'contacts' => 'Contacts',\n 'tags' => 'Tags',\n );\n }", "label": 1, "label_name": "safe"} -{"code": "enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method)\n{\n char q_user[SHORT_STRING], q_pass[SHORT_STRING];\n char buf[STRING];\n int rc;\n\n if (mutt_bit_isset(idata->capabilities, LOGINDISABLED))\n {\n mutt_message(_(\"LOGIN disabled on this server.\"));\n return IMAP_AUTH_UNAVAIL;\n }\n\n if (mutt_account_getuser(&idata->conn->account) < 0)\n return IMAP_AUTH_FAILURE;\n if (mutt_account_getpass(&idata->conn->account) < 0)\n return IMAP_AUTH_FAILURE;\n\n mutt_message(_(\"Logging in...\"));\n\n imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user);\n imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass);\n\n /* don't print the password unless we're at the ungodly debugging level\n * of 5 or higher */\n\n if (DebugLevel < IMAP_LOG_PASS)\n mutt_debug(2, \"Sending LOGIN command for %s...\\n\", idata->conn->account.user);\n\n snprintf(buf, sizeof(buf), \"LOGIN %s %s\", q_user, q_pass);\n rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS);\n\n if (!rc)\n {\n mutt_clear_error(); /* clear \"Logging in...\". fixes #3524 */\n return IMAP_AUTH_SUCCESS;\n }\n\n mutt_error(_(\"Login failed.\"));\n return IMAP_AUTH_FAILURE;\n}", "label": 0, "label_name": "vulnerable"} -{"code": " handler: function ({log}) {\n this.connector = new PassiveConnector(this);\n return this.connector.setupServer()\n .then((server) => {\n const {port} = server.address();\n\n return this.reply(229, `EPSV OK (|||${port}|)`);\n })\n .catch((err) => {\n log.error(err);\n return this.reply(err.code || 425, err.message);\n });\n },", "label": 1, "label_name": "safe"} +{"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 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\"