text
stringlengths
478
227k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CreateStatistics(CreateStatsStmt *stmt) { int16 attnums[STATS_MAX_DIMENSIONS]; int nattnums = 0; int numcols; char *namestr; NameData stxname; Oid statoid; Oid namespaceId; Oid stxowner = GetUserId(); HeapTuple htup; Datum values[Natts_pg_statistic_ext]; bool nulls[Natts_pg_statistic_ext]; Datum datavalues[Natts_pg_statistic_ext_data]; bool datanulls[Natts_pg_statistic_ext_data]; int2vector *stxkeys; List *stxexprs = NIL; Datum exprsDatum; Relation statrel; Relation datarel; Relation rel = NULL; Oid relid; ObjectAddress parentobject, myself; Datum types[4]; /* one for each possible type of statistic */ int ntypes; ArrayType *stxkind; bool build_ndistinct; bool build_dependencies; bool build_mcv; bool build_expressions; bool requested_type = false; int i; ListCell *cell; ListCell *cell2; Assert(IsA(stmt, CreateStatsStmt)); /* * Examine the FROM clause. Currently, we only allow it to be a single * simple table, but later we'll probably allow multiple tables and JOIN * syntax. The grammar is already prepared for that, so we have to check * here that what we got is what we can support. */ if (list_length(stmt->relations) != 1) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("only a single relation is allowed in CREATE STATISTICS"))); foreach(cell, stmt->relations) { Node *rln = (Node *) lfirst(cell); if (!IsA(rln, RangeVar)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("only a single relation is allowed in CREATE STATISTICS"))); /* * CREATE STATISTICS will influence future execution plans but does * not interfere with currently executing plans. So it should be * enough to take only ShareUpdateExclusiveLock on relation, * conflicting with ANALYZE and other DDL that sets statistical * information, but not with normal queries. */ rel = relation_openrv((RangeVar *) rln, ShareUpdateExclusiveLock); /* Restrict to allowed relation types */ if (rel->rd_rel->relkind != RELKIND_RELATION && rel->rd_rel->relkind != RELKIND_MATVIEW && rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE && rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("relation \"%s\" is not a table, foreign table, or materialized view", RelationGetRelationName(rel)))); /* You must own the relation to create stats on it */ if (!pg_class_ownercheck(RelationGetRelid(rel), stxowner)) aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind), RelationGetRelationName(rel)); /* Creating statistics on system catalogs is not allowed */ if (!allowSystemTableMods && IsSystemRelation(rel)) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied: \"%s\" is a system catalog", RelationGetRelationName(rel)))); } Assert(rel); relid = RelationGetRelid(rel); /* * If the node has a name, split it up and determine creation namespace. * If not (a possibility not considered by the grammar, but one which can * occur via the "CREATE TABLE ... (LIKE)" command), then we put the * object in the same namespace as the relation, and cons up a name for * it. */ if (stmt->defnames) namespaceId = QualifiedNameGetCreationNamespace(stmt->defnames, &namestr); else { namespaceId = RelationGetNamespace(rel); namestr = ChooseExtendedStatisticName(RelationGetRelationName(rel), ChooseExtendedStatisticNameAddition(stmt->exprs), "stat", namespaceId); } namestrcpy(&stxname, namestr); /* * Deal with the possibility that the statistics object already exists. */ if (SearchSysCacheExists2(STATEXTNAMENSP, CStringGetDatum(namestr), ObjectIdGetDatum(namespaceId))) { if (stmt->if_not_exists) { ereport(NOTICE, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("statistics object \"%s\" already exists, skipping", namestr))); relation_close(rel, NoLock); return InvalidObjectAddress; } ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("statistics object \"%s\" already exists", namestr))); } /* * Make sure no more than STATS_MAX_DIMENSIONS columns are used. There * might be duplicates and so on, but we'll deal with those later. */ numcols = list_length(stmt->exprs); if (numcols > STATS_MAX_DIMENSIONS) ereport(ERROR, (errcode(ERRCODE_TOO_MANY_COLUMNS), errmsg("cannot have more than %d columns in statistics", STATS_MAX_DIMENSIONS))); /* * Convert the expression list to a simple array of attnums, but also keep * a list of more complex expressions. While at it, enforce some * constraints - we don't allow extended statistics on system attributes, * and we require the data type to have less-than operator. * * There are many ways how to "mask" a simple attribute refenrece as an * expression, for example "(a+0)" etc. We can't possibly detect all of * them, but we handle at least the simple case with attribute in parens. * There'll always be a way around this, if the user is determined (like * the "(a+0)" example), but this makes it somewhat consistent with how * indexes treat attributes/expressions. */ foreach(cell, stmt->exprs) { StatsElem *selem = lfirst_node(StatsElem, cell); if (selem->name) /* column reference */ { char *attname; HeapTuple atttuple; Form_pg_attribute attForm; TypeCacheEntry *type; attname = selem->name; atttuple = SearchSysCacheAttName(relid, attname); if (!HeapTupleIsValid(atttuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("column \"%s\" does not exist", attname))); attForm = (Form_pg_attribute) GETSTRUCT(atttuple); /* Disallow use of system attributes in extended stats */ if (attForm->attnum <= 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("statistics creation on system columns is not supported"))); /* Disallow data types without a less-than operator */ type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR); if (type->lt_opr == InvalidOid) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class", attname, format_type_be(attForm->atttypid)))); attnums[nattnums] = attForm->attnum; nattnums++; ReleaseSysCache(atttuple); } else if (IsA(selem->expr, Var)) /* column reference in parens */ { Var *var = (Var *) selem->expr; TypeCacheEntry *type; /* Disallow use of system attributes in extended stats */ if (var->varattno <= 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("statistics creation on system columns is not supported"))); /* Disallow data types without a less-than operator */ type = lookup_type_cache(var->vartype, TYPECACHE_LT_OPR); if (type->lt_opr == InvalidOid) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class", get_attname(relid, var->varattno, false), format_type_be(var->vartype)))); attnums[nattnums] = var->varattno; nattnums++; } else /* expression */ { Node *expr = selem->expr; Oid atttype; TypeCacheEntry *type; Bitmapset *attnums = NULL; int k; Assert(expr != NULL); /* Disallow expressions referencing system attributes. */ pull_varattnos(expr, 1, &attnums); k = -1; while ((k = bms_next_member(attnums, k)) >= 0) { AttrNumber attnum = k + FirstLowInvalidHeapAttributeNumber; if (attnum <= 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("statistics creation on system columns is not supported"))); } /* * Disallow data types without a less-than operator. * * We ignore this for statistics on a single expression, in which * case we'll build the regular statistics only (and that code can * deal with such data types). */ if (list_length(stmt->exprs) > 1) { atttype = exprType(expr); type = lookup_type_cache(atttype, TYPECACHE_LT_OPR); if (type->lt_opr == InvalidOid) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("expression cannot be used in multivariate statistics because its type %s has no default btree operator class", format_type_be(atttype)))); } stxexprs = lappend(stxexprs, expr); } } /* * Parse the statistics kinds. * * First check that if this is the case with a single expression, there * are no statistics kinds specified (we don't allow that for the simple * CREATE STATISTICS form). */ if ((list_length(stmt->exprs) == 1) && (list_length(stxexprs) == 1)) { /* statistics kinds not specified */ if (list_length(stmt->stat_types) > 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("when building statistics on a single expression, statistics kinds may not be specified"))); } /* OK, let's check that we recognize the statistics kinds. */ build_ndistinct = false; build_dependencies = false; build_mcv = false; foreach(cell, stmt->stat_types) { char *type = strVal((Value *) lfirst(cell)); if (strcmp(type, "ndistinct") == 0) { build_ndistinct = true; requested_type = true; } else if (strcmp(type, "dependencies") == 0) { build_dependencies = true; requested_type = true; } else if (strcmp(type, "mcv") == 0) { build_mcv = true; requested_type = true; } else ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("unrecognized statistics kind \"%s\"", type))); } /* * If no statistic type was specified, build them all (but only when the * statistics is defined on more than one column/expression). */ if ((!requested_type) && (numcols >= 2)) { build_ndistinct = true; build_dependencies = true; build_mcv = true; } /* * When there are non-trivial expressions, build the expression stats * automatically. This allows calculating good estimates for stats that * consider per-clause estimates (e.g. functional dependencies). */ build_expressions = (list_length(stxexprs) > 0); /* * Check that at least two columns were specified in the statement, or * that we're building statistics on a single expression. */ if ((numcols < 2) && (list_length(stxexprs) != 1)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("extended statistics require at least 2 columns"))); /* * Sort the attnums, which makes detecting duplicates somewhat easier, and * it does not hurt (it does not matter for the contents, unlike for * indexes, for example). */ qsort(attnums, nattnums, sizeof(int16), compare_int16); /* * Check for duplicates in the list of columns. The attnums are sorted so * just check consecutive elements. */ for (i = 1; i < nattnums; i++) { if (attnums[i] == attnums[i - 1]) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), errmsg("duplicate column name in statistics definition"))); } /* * Check for duplicate expressions. We do two loops, counting the * occurrences of each expression. This is O(N^2) but we only allow small * number of expressions and it's not executed often. * * XXX We don't cross-check attributes and expressions, because it does * not seem worth it. In principle we could check that expressions don't * contain trivial attribute references like "(a)", but the reasoning is * similar to why we don't bother with extracting columns from * expressions. It's either expensive or very easy to defeat for * determined user, and there's no risk if we allow such statistics (the * statistics is useless, but harmless). */ foreach(cell, stxexprs) { Node *expr1 = (Node *) lfirst(cell); int cnt = 0; foreach(cell2, stxexprs) { Node *expr2 = (Node *) lfirst(cell2); if (equal(expr1, expr2)) cnt += 1; } /* every expression should find at least itself */ Assert(cnt >= 1); if (cnt > 1) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), errmsg("duplicate expression in statistics definition"))); } /* Form an int2vector representation of the sorted column list */ stxkeys = buildint2vector(attnums, nattnums); /* construct the char array of enabled statistic types */ ntypes = 0; if (build_ndistinct) types[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT); if (build_dependencies) types[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES); if (build_mcv) types[ntypes++] = CharGetDatum(STATS_EXT_MCV); if (build_expressions) types[ntypes++] = CharGetDatum(STATS_EXT_EXPRESSIONS); Assert(ntypes > 0 && ntypes <= lengthof(types)); stxkind = construct_array(types, ntypes, CHAROID, 1, true, TYPALIGN_CHAR); /* convert the expressions (if any) to a text datum */ if (stxexprs != NIL) { char *exprsString; exprsString = nodeToString(stxexprs); exprsDatum = CStringGetTextDatum(exprsString); pfree(exprsString); } else exprsDatum = (Datum) 0; statrel = table_open(StatisticExtRelationId, RowExclusiveLock); /* * Everything seems fine, so let's build the pg_statistic_ext tuple. */ memset(values, 0, sizeof(values)); memset(nulls, false, sizeof(nulls)); statoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId, Anum_pg_statistic_ext_oid); values[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid); values[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid); values[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname); values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId); values[Anum_pg_statistic_ext_stxstattarget - 1] = Int32GetDatum(-1); values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner); values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys); values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind); values[Anum_pg_statistic_ext_stxexprs - 1] = exprsDatum; if (exprsDatum == (Datum) 0) nulls[Anum_pg_statistic_ext_stxexprs - 1] = true; /* insert it into pg_statistic_ext */ htup = heap_form_tuple(statrel->rd_att, values, nulls); CatalogTupleInsert(statrel, htup); heap_freetuple(htup); relation_close(statrel, RowExclusiveLock); /* * Also build the pg_statistic_ext_data tuple, to hold the actual * statistics data. */ datarel = table_open(StatisticExtDataRelationId, RowExclusiveLock); memset(datavalues, 0, sizeof(datavalues)); memset(datanulls, false, sizeof(datanulls)); datavalues[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(statoid); /* no statistics built yet */ datanulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = true; datanulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = true; datanulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = true; datanulls[Anum_pg_statistic_ext_data_stxdexpr - 1] = true; /* insert it into pg_statistic_ext_data */ htup = heap_form_tuple(datarel->rd_att, datavalues, datanulls); CatalogTupleInsert(datarel, htup); heap_freetuple(htup); relation_close(datarel, RowExclusiveLock); InvokeObjectPostCreateHook(StatisticExtRelationId, statoid, 0); /* * Invalidate relcache so that others see the new statistics object. */ CacheInvalidateRelcache(rel); relation_close(rel, NoLock); /* * Add an AUTO dependency on each column used in the stats, so that the * stats object goes away if any or all of them get dropped. */ ObjectAddressSet(myself, StatisticExtRelationId, statoid); /* add dependencies for plain column references */ for (i = 0; i < nattnums; i++) { ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]); recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO); } /* * If there are no dependencies on a column, give the statistics object an * auto dependency on the whole table. In most cases, this will be * redundant, but it might not be if the statistics expressions contain no * Vars (which might seem strange but possible). This is consistent with * what we do for indexes in index_create. * * XXX We intentionally don't consider the expressions before adding this * dependency, because recordDependencyOnSingleRelExpr may not create any * dependencies for whole-row Vars. */ if (!nattnums) { ObjectAddressSet(parentobject, RelationRelationId, relid); recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO); } /* * Store dependencies on anything mentioned in statistics expressions, * just like we do for index expressions. */ if (stxexprs) recordDependencyOnSingleRelExpr(&myself, (Node *) stxexprs, relid, DEPENDENCY_NORMAL, DEPENDENCY_AUTO, false); /* * Also add dependencies on namespace and owner. These are required * because the stats object might have a different namespace and/or owner * than the underlying table(s). */ ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId); recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL); recordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner); /* * XXX probably there should be a recordDependencyOnCurrentExtension call * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP * STATISTICS, which is more work than it seems worth. */ /* Add any requested comment */ if (stmt->stxcomment != NULL) CreateComments(statoid, StatisticExtRelationId, 0, stmt->stxcomment); /* Return stats object's address */ return myself; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension. Previously, if an extension script did CREATE OR REPLACE and there was an existing object not belonging to the extension, it would overwrite the object and adopt it into the extension. This is problematic, first because the overwrite is probably unintentional, and second because we didn't change the object's ownership. Thus a hostile user could create an object in advance of an expected CREATE EXTENSION command, and would then have ownership rights on an extension object, which could be modified for trojan-horse-type attacks. Hence, forbid CREATE OR REPLACE of an existing object unless it already belongs to the extension. (Note that we've always forbidden replacing an object that belongs to some other extension; only the behavior for previously-free-standing objects changes here.) For the same reason, also fail CREATE IF NOT EXISTS when there is an existing object that doesn't belong to the extension. Our thanks to Sven Klemm for reporting this problem. Security: CVE-2022-2625'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static chunk * connection_read_header_more(connection *con, chunkqueue *cq, chunk *c, const size_t olen) { /*(should not be reached by HTTP/2 streams)*/ /*if (r->http_version == HTTP_VERSION_2) return NULL;*/ /*(However, new connections over TLS may become HTTP/2 connections via ALPN * and return from this routine with r->http_version == HTTP_VERSION_2) */ if ((NULL == c || NULL == c->next) && con->is_readable > 0) { con->read_idle_ts = log_epoch_secs; if (0 != con->network_read(con, cq, MAX_READ_LIMIT)) { request_st * const r = &con->request; connection_set_state_error(r, CON_STATE_ERROR); } /* check if switched to HTTP/2 (ALPN "h2" during TLS negotiation) */ request_st * const r = &con->request; if (r->http_version == HTTP_VERSION_2) return NULL; } if (cq->first != cq->last && 0 != olen) { const size_t clen = chunkqueue_length(cq); size_t block = (olen + (16384-1)) & (16384-1); block += (block - olen > 1024 ? 0 : 16384); chunkqueue_compact_mem(cq, block > clen ? clen : block); } /* detect if data is added to chunk */ c = cq->first; return (c && (size_t)c->offset + olen < buffer_string_length(c->mem)) ? c : NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': '[core] fix merging large headers across mult reads (fixes #3059) (thx mitd) x-ref: "Connections stuck in Close_Wait causing 100% cpu usage" https://redmine.lighttpd.net/issues/3059'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int read_request_line(request_rec *r, apr_bucket_brigade *bb) { const char *ll; const char *uri; const char *pro; unsigned int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */ char http[5]; apr_size_t len; int num_blank_lines = 0; int max_blank_lines = r->server->limit_req_fields; core_server_config *conf = ap_get_core_module_config(r->server->module_config); int strict = conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT; int enforce_strict = !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY); if (max_blank_lines <= 0) { max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS; } /* Read past empty lines until we get a real request line, * a read error, the connection closes (EOF), or we timeout. * * We skip empty lines because browsers have to tack a CRLF on to the end * of POSTs to support old CERN webservers. But note that we may not * have flushed any previous response completely to the client yet. * We delay the flush as long as possible so that we can improve * performance for clients that are pipelining requests. If a request * is pipelined then we won't block during the (implicit) read() below. * If the requests aren't pipelined, then the client is still waiting * for the final buffer flush from us, and we will block in the implicit * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will * have to block during a read. */ do { apr_status_t rv; /* ensure ap_rgetline allocates memory each time thru the loop * if there are empty lines */ r->the_request = NULL; rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2), &len, r, 0, bb); if (rv != APR_SUCCESS) { r->request_time = apr_time_now(); /* ap_rgetline returns APR_ENOSPC if it fills up the * buffer before finding the end-of-line. This is only going to * happen if it exceeds the configured limit for a request-line. */ if (APR_STATUS_IS_ENOSPC(rv)) { r->status = HTTP_REQUEST_URI_TOO_LARGE; r->proto_num = HTTP_VERSION(1,0); r->protocol = apr_pstrdup(r->pool, "HTTP/1.0"); } else if (APR_STATUS_IS_TIMEUP(rv)) { r->status = HTTP_REQUEST_TIME_OUT; } else if (APR_STATUS_IS_EINVAL(rv)) { r->status = HTTP_BAD_REQUEST; } return 0; } } while ((len <= 0) && (++num_blank_lines < max_blank_lines)); if (APLOGrtrace5(r)) { ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r, "Request received from client: %s", ap_escape_logitem(r->pool, r->the_request)); } r->request_time = apr_time_now(); ll = r->the_request; r->method = ap_getword_white(r->pool, &ll); uri = ap_getword_white(r->pool, &ll); /* Provide quick information about the request method as soon as known */ r->method_number = ap_method_number_of(r->method); if (r->method_number == M_GET && r->method[0] == 'H') { r->header_only = 1; } ap_parse_uri(r, uri); if (ll[0]) { r->assbackwards = 0; pro = ll; len = strlen(ll); } else { r->assbackwards = 1; pro = "HTTP/0.9"; len = 8; if (conf->http09_enable == AP_HTTP09_DISABLE) { r->status = HTTP_VERSION_NOT_SUPPORTED; r->protocol = apr_pstrmemdup(r->pool, pro, len); /* If we deny 0.9, send error message with 1.x */ r->assbackwards = 0; r->proto_num = HTTP_VERSION(0, 9); r->connection->keepalive = AP_CONN_CLOSE; ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401) "HTTP/0.9 denied by server configuration"); return 0; } } r->protocol = apr_pstrmemdup(r->pool, pro, len); /* Avoid sscanf in the common case */ if (len == 8 && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P' && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.' && apr_isdigit(pro[7])) { r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0'); } else { if (strict) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418) "Invalid protocol '%s'", r->protocol); if (enforce_strict) { r->status = HTTP_BAD_REQUEST; return 0; } } if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor) && (strcasecmp("http", http) == 0) && (minor < HTTP_VERSION(1, 0)) ) { /* don't allow HTTP/0.1000 */ r->proto_num = HTTP_VERSION(major, minor); } else { r->proto_num = HTTP_VERSION(1, 0); } } if (strict) { int err = 0; if (ap_has_cntrl(r->the_request)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02420) "Request line must not contain control characters"); err = HTTP_BAD_REQUEST; } if (r->parsed_uri.fragment) { /* RFC3986 3.5: no fragment */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421) "URI must not contain a fragment"); err = HTTP_BAD_REQUEST; } else if (r->parsed_uri.user || r->parsed_uri.password) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422) "URI must not contain a username/password"); err = HTTP_BAD_REQUEST; } else if (r->method_number == M_INVALID) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423) "Invalid HTTP method string: %s", r->method); err = HTTP_NOT_IMPLEMENTED; } else if (r->assbackwards == 0 && r->proto_num < HTTP_VERSION(1, 0)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02424) "HTTP/0.x does not take a protocol"); err = HTTP_BAD_REQUEST; } if (err && enforce_strict) { r->status = err; return 0; } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': '*) SECURITY: CVE-2015-0253 (cve.mitre.org) core: Fix a crash introduced in with ErrorDocument 400 pointing to a local URL-path with the INCLUDES filter active, introduced in 2.4.11. PR 57531. [Yann Ylavic] Submitted By: ylavic Committed By: covener git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1664205 13f79535-47bb-0310-9956-ffa450edef68'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status Examples::CreateSparseFeatureRepresentation( const DeviceBase::CpuWorkerThreads& worker_threads, const int num_examples, const int num_sparse_features, const ModelWeights& weights, const OpInputList& sparse_example_indices_inputs, const OpInputList& sparse_feature_indices_inputs, const OpInputList& sparse_feature_values_inputs, std::vector<Example>* const examples) { mutex mu; Status result; // Guarded by mu auto parse_partition = [&](const int64 begin, const int64 end) { // The static_cast here is safe since begin and end can be at most // num_examples which is an int. for (int i = static_cast<int>(begin); i < end; ++i) { auto example_indices = sparse_example_indices_inputs[i].template flat<int64>(); auto feature_indices = sparse_feature_indices_inputs[i].template flat<int64>(); // Parse features for each example. Features for a particular example // are at the offsets (start_id, end_id] int start_id = -1; int end_id = 0; for (int example_id = 0; example_id < num_examples; ++example_id) { start_id = end_id; while (end_id < example_indices.size() && example_indices(end_id) == example_id) { ++end_id; } Example::SparseFeatures* const sparse_features = &(*examples)[example_id].sparse_features_[i]; if (start_id < example_indices.size() && example_indices(start_id) == example_id) { sparse_features->indices.reset(new UnalignedInt64Vector( &(feature_indices(start_id)), end_id - start_id)); if (sparse_feature_values_inputs.size() > i) { auto feature_weights = sparse_feature_values_inputs[i].flat<float>(); sparse_features->values.reset(new UnalignedFloatVector( &(feature_weights(start_id)), end_id - start_id)); } // If features are non empty. if (end_id - start_id > 0) { // TODO(sibyl-Aix6ihai): Write this efficiently using vectorized // operations from eigen. for (int64 k = 0; k < sparse_features->indices->size(); ++k) { const int64 feature_index = (*sparse_features->indices)(k); if (!weights.SparseIndexValid(i, feature_index)) { mutex_lock l(mu); result = errors::InvalidArgument( "Found sparse feature indices out of valid range: ", (*sparse_features->indices)(k)); return; } } } } else { // Add a Tensor that has size 0. sparse_features->indices.reset( new UnalignedInt64Vector(&(feature_indices(0)), 0)); // If values exist for this feature group. if (sparse_feature_values_inputs.size() > i) { auto feature_weights = sparse_feature_values_inputs[i].flat<float>(); sparse_features->values.reset( new UnalignedFloatVector(&(feature_weights(0)), 0)); } } } } }; // For each column, the cost of parsing it is O(num_examples). We use // num_examples here, as empirically Shard() creates the right amount of // threads based on the problem size. // TODO(sibyl-Aix6ihai): Tune this as a function of dataset size. const int64 kCostPerUnit = num_examples; Shard(worker_threads.num_threads, worker_threads.workers, num_sparse_features, kCostPerUnit, parse_partition); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Add several missing validations in SDCA PiperOrigin-RevId: 372172877 Change-Id: Id366da962432e18dcbfac847d11e98488bebb70a'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DefragTimeoutTest(void) { int i; int ret = 0; /* Setup a small numberr of trackers. */ if (ConfSet("defrag.trackers", "16") != 1) { printf("ConfSet failed: "); goto end; } DefragInit(); /* Load in 16 packets. */ for (i = 0; i < 16; i++) { Packet *p = BuildTestPacket(i, 0, 1, 'A' + i, 16); if (p == NULL) goto end; Packet *tp = Defrag(NULL, NULL, p, NULL); SCFree(p); if (tp != NULL) { SCFree(tp); goto end; } } /* Build a new packet but push the timestamp out by our timeout. * This should force our previous fragments to be timed out. */ Packet *p = BuildTestPacket(99, 0, 1, 'A' + i, 16); if (p == NULL) goto end; p->ts.tv_sec += (defrag_context->timeout + 1); Packet *tp = Defrag(NULL, NULL, p, NULL); if (tp != NULL) { SCFree(tp); goto end; } DefragTracker *tracker = DefragLookupTrackerFromHash(p); if (tracker == NULL) goto end; if (tracker->id != 99) goto end; SCFree(p); ret = 1; end: DefragDestroy(); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) { int i; int ret = 0; DefragInit(); /* * Build the packets. */ int id = 1; Packet *packets[17]; memset(packets, 0x00, sizeof(packets)); /* * Original fragments. */ /* A*24 at 0. */ packets[0] = BuildTestPacket(id, 0, 1, 'A', 24); /* B*15 at 32. */ packets[1] = BuildTestPacket(id, 32 >> 3, 1, 'B', 16); /* C*24 at 48. */ packets[2] = BuildTestPacket(id, 48 >> 3, 1, 'C', 24); /* D*8 at 80. */ packets[3] = BuildTestPacket(id, 80 >> 3, 1, 'D', 8); /* E*16 at 104. */ packets[4] = BuildTestPacket(id, 104 >> 3, 1, 'E', 16); /* F*24 at 120. */ packets[5] = BuildTestPacket(id, 120 >> 3, 1, 'F', 24); /* G*16 at 144. */ packets[6] = BuildTestPacket(id, 144 >> 3, 1, 'G', 16); /* H*16 at 160. */ packets[7] = BuildTestPacket(id, 160 >> 3, 1, 'H', 16); /* I*8 at 176. */ packets[8] = BuildTestPacket(id, 176 >> 3, 1, 'I', 8); /* * Overlapping subsequent fragments. */ /* J*32 at 8. */ packets[9] = BuildTestPacket(id, 8 >> 3, 1, 'J', 32); /* K*24 at 48. */ packets[10] = BuildTestPacket(id, 48 >> 3, 1, 'K', 24); /* L*24 at 72. */ packets[11] = BuildTestPacket(id, 72 >> 3, 1, 'L', 24); /* M*24 at 96. */ packets[12] = BuildTestPacket(id, 96 >> 3, 1, 'M', 24); /* N*8 at 128. */ packets[13] = BuildTestPacket(id, 128 >> 3, 1, 'N', 8); /* O*8 at 152. */ packets[14] = BuildTestPacket(id, 152 >> 3, 1, 'O', 8); /* P*8 at 160. */ packets[15] = BuildTestPacket(id, 160 >> 3, 1, 'P', 8); /* Q*16 at 176. */ packets[16] = BuildTestPacket(id, 176 >> 3, 0, 'Q', 16); default_policy = policy; /* Send all but the last. */ for (i = 0; i < 9; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) { goto end; } } int overlap = 0; for (; i < 16; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) { overlap++; } } if (!overlap) { goto end; } /* And now the last one. */ Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL); if (reassembled == NULL) { goto end; } if (IPV4_GET_HLEN(reassembled) != 20) { goto end; } if (IPV4_GET_IPLEN(reassembled) != 20 + 192) { goto end; } if (memcmp(GET_PKT_DATA(reassembled) + 20, expected, expected_len) != 0) { goto end; } SCFree(reassembled); /* Make sure all frags were returned back to the pool. */ if (defrag_context->frag_pool->outstanding != 0) { goto end; } ret = 1; end: for (i = 0; i < 17; i++) { SCFree(packets[i]); } DefragDestroy(); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Phase2() final { Local<Context> context_handle = Deref(context); Context::Scope context_scope{context_handle}; Local<Object> object = Local<Object>::Cast(Deref(reference)); result = Unmaybe(object->Delete(context_handle, key->CopyInto())); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-913'], 'message': 'Don't invoke accessors or proxies via Reference functions'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { int value; UINT error; UINT32 ChannelId; wStream* data_out; ChannelId = drdynvc_read_variable_uint(s, cbChId); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp, cbChId, ChannelId); if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId))) { WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error); return error; } data_out = Stream_New(NULL, 4); if (!data_out) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03); Stream_Write_UINT8(data_out, value); drdynvc_write_variable_uint(data_out, ChannelId); error = drdynvc_send(drdynvc, data_out); if (error) WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]", WTSErrorToString(error), error); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix for #4866: Added additional length checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int nft_setelem_parse_data(struct nft_ctx *ctx, struct nft_set *set, struct nft_data_desc *desc, struct nft_data *data, struct nlattr *attr) { int err; err = nft_data_init(ctx, data, NFT_DATA_VALUE_MAXLEN, desc, attr); if (err < 0) return err; if (desc->type != NFT_DATA_VERDICT && desc->len != set->dlen) { nft_data_release(data, desc->type); return -EINVAL; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: nf_tables: stricter validation of element data Make sure element data type and length do not mismatch the one specified by the set declaration. Fixes: 7d7402642eaf ("netfilter: nf_tables: variable sized set element keys / data") Reported-by: Hugues ANGUELKOV <hanguelkov@randorisec.fr> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void notify_inserters_if_bounded() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (has_capacity() || has_memory_limit()) { // Notify all inserters. The removal of an element // may make memory available for many inserters // to insert new elements full_.notify_all(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Prevent nullptr deref in validation of indexes in map ops. PiperOrigin-RevId: 387738023 Change-Id: I83d18d36a7b82ffd2a40b5124a4e5b4c72238f27'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/, const std::string& params, const std::string& provider) const { if(provider == "base" || provider.empty()) return std::unique_ptr<PK_Ops::Signature>(new DSA_Signature_Operation(*this, params)); throw Provider_Not_Found(algo_name(), provider); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Address DSA/ECDSA side channel'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int yr_re_fast_exec( uint8_t* code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args, int* matches) { RE_REPEAT_ANY_ARGS* repeat_any_args; uint8_t* code_stack[MAX_FAST_RE_STACK]; uint8_t* input_stack[MAX_FAST_RE_STACK]; int matches_stack[MAX_FAST_RE_STACK]; uint8_t* ip = code; uint8_t* input = input_data; uint8_t* next_input; uint8_t* next_opcode; uint8_t mask; uint8_t value; int i; int stop; int input_incr; int sp = 0; int bytes_matched; int max_bytes_matched; max_bytes_matched = flags & RE_FLAGS_BACKWARDS ? (int) input_backwards_size : (int) input_forwards_size; input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1; if (flags & RE_FLAGS_BACKWARDS) input--; code_stack[sp] = code; input_stack[sp] = input; matches_stack[sp] = 0; sp++; while (sp > 0) { sp--; ip = code_stack[sp]; input = input_stack[sp]; bytes_matched = matches_stack[sp]; stop = FALSE; while(!stop) { if (*ip == RE_OPCODE_MATCH) { if (flags & RE_FLAGS_EXHAUSTIVE) { FAIL_ON_ERROR(callback( flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data, bytes_matched, flags, callback_args)); break; } else { if (matches != NULL) *matches = bytes_matched; return ERROR_SUCCESS; } } if (bytes_matched >= max_bytes_matched) break; switch(*ip) { case RE_OPCODE_LITERAL: if (*input == *(ip + 1)) { bytes_matched++; input += input_incr; ip += 2; } else { stop = TRUE; } break; case RE_OPCODE_MASKED_LITERAL: value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; if ((*input & mask) == value) { bytes_matched++; input += input_incr; ip += 3; } else { stop = TRUE; } break; case RE_OPCODE_ANY: bytes_matched++; input += input_incr; ip += 1; break; case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1); next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS); for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++) { next_input = input + i * input_incr; if (bytes_matched + i >= max_bytes_matched) break; if ( *(next_opcode) != RE_OPCODE_LITERAL || (*(next_opcode) == RE_OPCODE_LITERAL && *(next_opcode + 1) == *next_input)) { if (sp >= MAX_FAST_RE_STACK) return -4; code_stack[sp] = next_opcode; input_stack[sp] = next_input; matches_stack[sp] = bytes_matched + i; sp++; } } input += input_incr * repeat_any_args->min; bytes_matched += repeat_any_args->min; ip = next_opcode; break; default: assert(FALSE); } } } if (matches != NULL) *matches = -1; return ERROR_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void copy_fields(const FieldMatchContext *fm, AVFrame *dst, const AVFrame *src, int field) { int plane; for (plane = 0; plane < 4 && src->data[plane]; plane++) av_image_copy_plane(dst->data[plane] + field*dst->linesize[plane], dst->linesize[plane] << 1, src->data[plane] + field*src->linesize[plane], src->linesize[plane] << 1, get_width(fm, src, plane), get_height(fm, src, plane) / 2); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MagickPathExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False during convert or mogrify */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length < 2) { if (chunk) chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream","`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 13) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 15) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 17) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { /* Interpolate */ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelChannel() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } /* To do: Rewrite using Get/Set***PixelChannel() */ else { /* Interpolate */ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { /* Interpolate */ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneMNGImage();"); return(image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Skip MNG CLIP chunk with out-of-range object IDs'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: nfsreq_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; register const uint32_t *dp; nfs_type type; int v3; uint32_t proc; uint32_t access_flags; struct nfsv3_sattr sa3; ND_PRINT((ndo, "%d", length)); nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */ goto trunc; v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3); proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: case NFSPROC_SETATTR: case NFSPROC_READLINK: case NFSPROC_FSSTAT: case NFSPROC_FSINFO: case NFSPROC_PATHCONF: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefh(ndo, dp, v3) != NULL) return; break; case NFSPROC_LOOKUP: case NFSPROC_CREATE: case NFSPROC_MKDIR: case NFSPROC_REMOVE: case NFSPROC_RMDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefhn(ndo, dp, v3) != NULL) return; break; case NFSPROC_ACCESS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[0]); access_flags = EXTRACT_32BITS(&dp[0]); if (access_flags & ~NFSV3ACCESS_FULL) { /* NFSV3ACCESS definitions aren't up to date */ ND_PRINT((ndo, " %04x", access_flags)); } else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) { ND_PRINT((ndo, " NFS_ACCESS_FULL")); } else { char separator = ' '; if (access_flags & NFSV3ACCESS_READ) { ND_PRINT((ndo, " NFS_ACCESS_READ")); separator = '|'; } if (access_flags & NFSV3ACCESS_LOOKUP) { ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_MODIFY) { ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXTEND) { ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_DELETE) { ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXECUTE) ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator)); } return; } break; case NFSPROC_READ: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); } else { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes @ %u", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_WRITE: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64, EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { dp += 3; ND_TCHECK(dp[0]); ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(dp)))); } } else { ND_TCHECK(dp[3]); ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)", EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_SYMLINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; if (parsefn(ndo, dp) == NULL) break; if (v3 && ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_MKNOD: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_TCHECK(*dp); type = (nfs_type)EXTRACT_32BITS(dp); dp++; if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type))); if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u/%u", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); dp += 2; } if (ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_RENAME: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_LINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_READDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[4]); /* * We shouldn't really try to interpret the * offset cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3])); } else { ND_TCHECK(dp[1]); /* * Print the offset as signed, since -1 is * common, but offsets > 2^31 aren't. */ ND_PRINT((ndo, " %u bytes @ %d", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_READDIRPLUS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[4]); /* * We don't try to interpret the offset * cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { ND_TCHECK(dp[5]); ND_PRINT((ndo, " max %u verf %08x%08x", EXTRACT_32BITS(&dp[5]), dp[2], dp[3])); } return; } break; case NFSPROC_COMMIT: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); return; } break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12898/NFS: Fix bounds checking. Fix the bounds checking for the NFSv3 WRITE procedure to check whether the length of the opaque data being written is present in the captured data, not just whether the byte count is present in the captured data. furthest forward in the packet, not the item before it. (This also lets us eliminate the check for the "stable" argument being present in the captured data; rewrite the code to print that to make it a bit clearer.) Check that the entire ar_stat field is present in the capture. Note that parse_wcc_attr() is called after we've already checked whether the wcc_data is present. Check before fetching the "access" part of the NFSv3 ACCESS results. This fixes a buffer over-read discovered by Kamil Frankowicz. Include a test for the "check before fetching the "access" part..." fix, using the capture supplied by the reporter(s).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: midi_synth_load_patch(int dev, int format, const char __user *addr, int offs, int count, int pmgr_flag) { int orig_dev = synth_devs[dev]->midi_dev; struct sysex_info sysex; int i; unsigned long left, src_offs, eox_seen = 0; int first_byte = 1; int hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex; leave_sysex(dev); if (!prefix_cmd(orig_dev, 0xf0)) return 0; if (format != SYSEX_PATCH) { /* printk("MIDI Error: Invalid patch format (key) 0x%x\n", format);*/ return -EINVAL; } if (count < hdr_size) { /* printk("MIDI Error: Patch header too short\n");*/ return -EINVAL; } count -= hdr_size; /* * Copy the header from user space but ignore the first bytes which have * been transferred already. */ if(copy_from_user(&((char *) &sysex)[offs], &(addr)[offs], hdr_size - offs)) return -EFAULT; if (count < sysex.len) { /* printk(KERN_WARNING "MIDI Warning: Sysex record too short (%d<%d)\n", count, (int) sysex.len);*/ sysex.len = count; } left = sysex.len; src_offs = 0; for (i = 0; i < left && !signal_pending(current); i++) { unsigned char data; if (get_user(data, (unsigned char __user *)(addr + hdr_size + i))) return -EFAULT; eox_seen = (i > 0 && data & 0x80); /* End of sysex */ if (eox_seen && data != 0xf7) data = 0xf7; if (i == 0) { if (data != 0xf0) { printk(KERN_WARNING "midi_synth: Sysex start missing\n"); return -EINVAL; } } while (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) && !signal_pending(current)) schedule(); if (!first_byte && data & 0x80) return 0; first_byte = 0; } if (!eox_seen) midi_outc(orig_dev, 0xf7); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'sound/oss: remove offset from load_patch callbacks Was: [PATCH] sound/oss/midi_synth: prevent underflow, use of uninitialized value, and signedness issue The offset passed to midi_synth_load_patch() can be essentially arbitrary. If it's greater than the header length, this will result in a copy_from_user(dst, src, negative_val). While this will just return -EFAULT on x86, on other architectures this may cause memory corruption. Additionally, the length field of the sysex_info structure may not be initialized prior to its use. Finally, a signed comparison may result in an unintentionally large loop. On suggestion by Takashi Iwai, version two removes the offset argument from the load_patch callbacks entirely, which also resolves similar issues in opl3. Compile tested only. v3 adjusts comments and hopefully gets copy offsets right. Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void apply_sample_adaptive_offset_sequential(de265_image* img) { const seq_parameter_set& sps = img->get_sps(); if (sps.sample_adaptive_offset_enabled_flag==0) { return; } int lumaImageSize = img->get_image_stride(0) * img->get_height(0) * img->get_bytes_per_pixel(0); int chromaImageSize = img->get_image_stride(1) * img->get_height(1) * img->get_bytes_per_pixel(1); uint8_t* inputCopy = new uint8_t[ libde265_max(lumaImageSize, chromaImageSize) ]; if (inputCopy == NULL) { img->decctx->add_warning(DE265_WARNING_CANNOT_APPLY_SAO_OUT_OF_MEMORY,false); return; } int nChannels = 3; if (sps.ChromaArrayType == CHROMA_MONO) { nChannels=1; } for (int cIdx=0;cIdx<nChannels;cIdx++) { int stride = img->get_image_stride(cIdx); int height = img->get_height(cIdx); memcpy(inputCopy, img->get_image_plane(cIdx), stride * height * img->get_bytes_per_pixel(cIdx)); for (int yCtb=0; yCtb<sps.PicHeightInCtbsY; yCtb++) for (int xCtb=0; xCtb<sps.PicWidthInCtbsY; xCtb++) { const slice_segment_header* shdr = img->get_SliceHeaderCtb(xCtb,yCtb); if (shdr==NULL) { return; } if (cIdx==0 && shdr->slice_sao_luma_flag) { apply_sao(img, xCtb,yCtb, shdr, 0, 1<<sps.Log2CtbSizeY, 1<<sps.Log2CtbSizeY, inputCopy, stride, img->get_image_plane(0), img->get_image_stride(0)); } if (cIdx!=0 && shdr->slice_sao_chroma_flag) { int nSW = (1<<sps.Log2CtbSizeY) / sps.SubWidthC; int nSH = (1<<sps.Log2CtbSizeY) / sps.SubHeightC; apply_sao(img, xCtb,yCtb, shdr, cIdx, nSW,nSH, inputCopy, stride, img->get_image_plane(cIdx), img->get_image_stride(cIdx)); } } } delete[] inputCopy; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'fix reading invalid images where shdr references are NULL in part of the image (#302)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, Image *images,const char *filename,ExceptionInfo *exception) { #define WriteImageTag "Write/Image" ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType proceed; MagickOffsetType progress; MagickProgressMonitor progress_monitor; MagickSizeType number_images; MagickStatusType status; register Image *p; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); write_info=CloneImageInfo(image_info); *write_info->magick='\0'; images=GetFirstImageInList(images); if (filename != (const char *) NULL) for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) (void) CopyMagickString(p->filename,filename,MagickPathExtent); (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent); sans_exception=AcquireExceptionInfo(); (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); p=images; for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) if (p->scene >= GetNextImageInList(p)->scene) { register ssize_t i; /* Generate consistent scene numbers. */ i=(ssize_t) images->scene; for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) p->scene=(size_t) i++; break; } /* Write images. */ status=MagickTrue; progress_monitor=(MagickProgressMonitor) NULL; progress=0; number_images=GetImageListLength(images); for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) { if (number_images != 1) progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, p->client_data); status&=WriteImage(write_info,p,exception); if (number_images != 1) (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); if (write_info->adjoin != MagickFalse) break; if (number_images != 1) { proceed=SetImageProgress(p,WriteImageTag,progress++,number_images); if (proceed == MagickFalse) break; } } write_info=DestroyImageInfo(write_info); return(status != 0 ? MagickTrue : MagickFalse); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/pull/34'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ldb_msg_add_value(struct ldb_message *msg, const char *attr_name, const struct ldb_val *val, struct ldb_message_element **return_el) { struct ldb_message_element *el; struct ldb_val *vals; int ret; el = ldb_msg_find_element(msg, attr_name); if (!el) { ret = ldb_msg_add_empty(msg, attr_name, 0, &el); if (ret != LDB_SUCCESS) { return ret; } } vals = talloc_realloc(msg->elements, el->values, struct ldb_val, el->num_values+1); if (!vals) { return LDB_ERR_OPERATIONS_ERROR; } el->values = vals; el->values[el->num_values] = *val; el->num_values++; if (return_el) { *return_el = el; } return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Ensure shallow copy modifications do not affect original message Using the newly added ldb flag, we can now detect when a message has been shallow-copied so that its elements share their values with the original message elements. Then when adding values to the copied message, we now make a copy of the shared values array first. This should prevent a use-after-free that occurred in LDB modules when new values were added to a shallow copy of a message by calling talloc_realloc() on the original values array, invalidating the 'values' pointer in the original message element. The original values pointer can later be used in the database audit logging module which logs database requests, and potentially cause a crash. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Compute(OpKernelContext* context) override { const Tensor& input_sizes = context->input(0); const Tensor& filter = context->input(1); OP_REQUIRES( context, TensorShapeUtils::IsVector(input_sizes.shape()), errors::InvalidArgument( "Conv2DBackpropInput: input_sizes input must be 1-dim, not ", input_sizes.dims())); TensorShape input_shape; const int32* in_sizes_data = input_sizes.template flat<int32>().data(); for (int i = 0; i < input_sizes.NumElements(); ++i) { OP_REQUIRES(context, in_sizes_data[i] >= 0, errors::InvalidArgument("Dimension ", i, " of input_sizes must be >= 0")); input_shape.AddDim(in_sizes_data[i]); } const TensorShape& filter_shape = filter.shape(); EXTRACT_AND_VERIFY_DIMENSIONS("DepthwiseConv2DBackpropInput"); Tensor* in_backprop = nullptr; OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {0}, 0, input_shape, &in_backprop)); // If there is nothing to compute, return. if (input_shape.num_elements() == 0) { return; } // If in_depth==1, this operation is just a standard convolution. // Depthwise convolution is a special case of cuDNN's grouped convolution. bool use_cudnn = std::is_same<Device, GPUDevice>::value && (in_depth == 1 || (use_cudnn_grouped_conv_ && IsCudnnSupportedFilterSize(/*filter_rows=*/filter_rows, /*filter_cols=*/filter_cols, /*in_depth=*/in_depth, /*out_depth=*/out_depth))); VLOG(2) << "DepthwiseConv2dNativeBackpropInput: " << " Input: [" << batch << ", " << input_rows << ", " << input_cols << ", " << in_depth << "]; Filter: [" << filter_rows << ", " << filter_cols << ", " << in_depth << ", " << depth_multiplier << "]; Output: [" << batch << ", " << out_rows << ", " << out_cols << ", " << out_depth << "], stride = " << stride_ << ", pad_rows = " << pad_top << ", pad_cols = " << pad_left << ", Use cuDNN: " << use_cudnn; if (use_cudnn) { // Reshape from TF depthwise filter to cuDNN grouped convolution filter: // // | TensorFlow | cuDNN // -------------------------------------------------------------------- // filter_out_depth | depth_multiplier | depth_multiplier * group_count // filter_in_depth | in_depth | in_depth / group_count // // For depthwise convolution, we have group_count == in_depth. int32_t filter_in_depth = 1; TensorShape shape = TensorShape{filter_rows, filter_cols, filter_in_depth, out_depth}; Tensor reshaped_filter(/*type=*/dtype_); OP_REQUIRES( context, reshaped_filter.CopyFrom(filter, shape), errors::Internal( "Failed to reshape filter tensor for grouped convolution.")); // TODO(yangzihao): Send in arbitrary dilation rates after the dilated // conv is supported. launcher_(context, /*use_cudnn=*/true, cudnn_use_autotune_, out_backprop, reshaped_filter, /*row_dilation=*/1, /*col_dilation=*/1, stride_, stride_, padding_, explicit_paddings_, in_backprop, data_format_); return; } auto out_backprop_ptr = out_backprop.template flat<T>().data(); auto filter_ptr = filter.template flat<T>().data(); auto in_backprop_ptr = in_backprop->template flat<T>().data(); LaunchDepthwiseConvBackpropInputOp<Device, T>()( context, args, out_backprop_ptr, filter_ptr, in_backprop_ptr, data_format_); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Fix tf.raw_ops.DepthwiseConv2dNativeBackpropInput vulnerability with large input sizes. Use AddDimWithStatus rather than AddDim in order to catch and report integer overflow gracefully. PiperOrigin-RevId: 444989983'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void csync_daemon_session() { static char line[4 * 4096]; struct stat sb; address_t peername = { .sa.sa_family = AF_UNSPEC, }; socklen_t peerlen = sizeof(peername); char *peer=0, *tag[32]; int i; if (fstat(0, &sb)) csync_fatal("Can't run fstat on fd 0: %s", strerror(errno)); switch (sb.st_mode & S_IFMT) { case S_IFSOCK: if ( getpeername(0, &peername.sa, &peerlen) == -1 ) csync_fatal("Can't run getpeername on fd 0: %s", strerror(errno)); break; case S_IFIFO: set_peername_from_env(&peername, "SSH_CLIENT"); break; /* fall through */ default: csync_fatal("I'm only talking to sockets or pipes! %x\n", sb.st_mode & S_IFMT); break; } while ( conn_gets(line, sizeof(line)) ) { int cmdnr; if (!setup_tag(tag, line)) continue; for (cmdnr=0; cmdtab[cmdnr].text; cmdnr++) if ( !strcasecmp(cmdtab[cmdnr].text, tag[0]) ) break; if ( !cmdtab[cmdnr].text ) { cmd_error = conn_response(CR_ERR_UNKNOWN_COMMAND); goto abort_cmd; } cmd_error = 0; if ( cmdtab[cmdnr].need_ident && !peer ) { conn_printf("Dear %s, please identify first.\n", csync_inet_ntop(&peername) ?: "stranger"); goto next_cmd; } if ( cmdtab[cmdnr].check_perm ) on_cygwin_lowercase(tag[2]); if ( cmdtab[cmdnr].check_perm ) { if ( cmdtab[cmdnr].check_perm == 2 ) csync_compare_mode = 1; int perm = csync_perm(tag[2], tag[1], peer); if ( cmdtab[cmdnr].check_perm == 2 ) csync_compare_mode = 0; if ( perm ) { if ( perm == 2 ) { csync_mark(tag[2], peer, 0); cmd_error = conn_response(CR_ERR_PERM_DENIED_FOR_SLAVE); } else cmd_error = conn_response(CR_ERR_PERM_DENIED); goto abort_cmd; } } if ( cmdtab[cmdnr].check_dirty && csync_check_dirty(tag[2], peer, cmdtab[cmdnr].action == A_FLUSH) ) goto abort_cmd; if ( cmdtab[cmdnr].unlink ) csync_unlink(tag[2], cmdtab[cmdnr].unlink); switch ( cmdtab[cmdnr].action ) { case A_SIG: { struct stat st; if ( lstat_strict(prefixsubst(tag[2]), &st) != 0 ) { if ( errno == ENOENT ) { struct stat sb; char parent_dirname[strlen(tag[2])]; split_dirname_basename(parent_dirname, NULL, tag[2]); if ( lstat_strict(prefixsubst(parent_dirname), &sb) != 0 ) cmd_error = conn_response(CR_ERR_PARENT_DIR_MISSING); else conn_resp_zero(CR_OK_PATH_NOT_FOUND); } else cmd_error = strerror(errno); break; } else if ( csync_check_pure(tag[2]) ) { conn_resp_zero(CR_OK_NOT_FOUND); break; } conn_resp(CR_OK_DATA_FOLLOWS); conn_printf("%s\n", csync_genchecktxt(&st, tag[2], 1)); if ( S_ISREG(st.st_mode) ) csync_rs_sig(tag[2]); else conn_printf("octet-stream 0\n"); } break; case A_MARK: csync_mark(tag[2], peer, 0); break; case A_TYPE: { FILE *f = fopen(prefixsubst(tag[2]), "rb"); if (!f && errno == ENOENT) f = fopen("/dev/null", "rb"); if (f) { char buffer[512]; size_t rc; conn_resp(CR_OK_DATA_FOLLOWS); while ( (rc=fread(buffer, 1, 512, f)) > 0 ) if ( conn_write(buffer, rc) != rc ) { conn_printf("[[ %s ]]", strerror(errno)); break; } fclose(f); return; } cmd_error = strerror(errno); } break; case A_GETTM: case A_GETSZ: { struct stat sbuf; conn_resp(CR_OK_DATA_FOLLOWS); if (!lstat_strict(prefixsubst(tag[2]), &sbuf)) conn_printf("%ld\n", cmdtab[cmdnr].action == A_GETTM ? (long)sbuf.st_mtime : (long)sbuf.st_size); else conn_printf("-1\n"); goto next_cmd; } break; case A_FLUSH: SQL("Flushing dirty entry (if any) for file", "DELETE FROM dirty WHERE filename = '%s'", url_encode(tag[2])); break; case A_DEL: if (!csync_file_backup(tag[2])) csync_unlink(tag[2], 0); break; case A_PATCH: if (!csync_file_backup(tag[2])) { conn_resp(CR_OK_SEND_DATA); csync_rs_sig(tag[2]); if (csync_rs_patch(tag[2])) cmd_error = strerror(errno); } break; case A_MKDIR: /* ignore errors on creating directories if the * directory does exist already. we don't need such * a check for the other file types, because they * will simply be unlinked if already present. */ #ifdef __CYGWIN__ // This creates the file using the native windows API, bypassing // the cygwin wrappers and so making sure that we do not mess up the // permissions.. { char winfilename[MAX_PATH]; cygwin_conv_to_win32_path(prefixsubst(tag[2]), winfilename); if ( !CreateDirectory(TEXT(winfilename), NULL) ) { struct stat st; if ( lstat_strict(prefixsubst(tag[2]), &st) != 0 || !S_ISDIR(st.st_mode)) { csync_debug(1, "Win32 I/O Error %d in mkdir command: %s\n", (int)GetLastError(), winfilename); cmd_error = conn_response(CR_ERR_WIN32_EIO_CREATE_DIR); } } } #else if ( mkdir(prefixsubst(tag[2]), 0700) ) { struct stat st; if ( lstat_strict((prefixsubst(tag[2])), &st) != 0 || !S_ISDIR(st.st_mode)) cmd_error = strerror(errno); } #endif break; case A_MKCHR: if ( mknod(prefixsubst(tag[2]), 0700|S_IFCHR, atoi(tag[3])) ) cmd_error = strerror(errno); break; case A_MKBLK: if ( mknod(prefixsubst(tag[2]), 0700|S_IFBLK, atoi(tag[3])) ) cmd_error = strerror(errno); break; case A_MKFIFO: if ( mknod(prefixsubst(tag[2]), 0700|S_IFIFO, 0) ) cmd_error = strerror(errno); break; case A_MKLINK: if ( symlink(tag[3], prefixsubst(tag[2])) ) cmd_error = strerror(errno); break; case A_MKSOCK: /* just ignore socket files */ break; case A_SETOWN: if ( !csync_ignore_uid || !csync_ignore_gid ) { int uid = csync_ignore_uid ? -1 : atoi(tag[3]); int gid = csync_ignore_gid ? -1 : atoi(tag[4]); if ( lchown(prefixsubst(tag[2]), uid, gid) ) cmd_error = strerror(errno); } break; case A_SETMOD: if ( !csync_ignore_mod ) { if ( chmod(prefixsubst(tag[2]), atoi(tag[3])) ) cmd_error = strerror(errno); } break; case A_SETIME: { struct utimbuf utb; utb.actime = atoll(tag[3]); utb.modtime = atoll(tag[3]); if ( utime(prefixsubst(tag[2]), &utb) ) cmd_error = strerror(errno); } break; case A_LIST: SQL_BEGIN("DB Dump - Files for sync pair", "SELECT checktxt, filename FROM file %s%s%s ORDER BY filename", strcmp(tag[2], "-") ? "WHERE filename = '" : "", strcmp(tag[2], "-") ? url_encode(tag[2]) : "", strcmp(tag[2], "-") ? "'" : "") { if ( csync_match_file_host(url_decode(SQL_V(1)), tag[1], peer, (const char **)&tag[3]) ) conn_printf("%s\t%s\n", SQL_V(0), SQL_V(1)); } SQL_END; break; case A_DEBUG: csync_debug_out = stdout; if ( tag[1][0] ) csync_debug_level = atoi(tag[1]); break; case A_HELLO: if (peer) { free(peer); peer = NULL; } if (verify_peername(tag[1], &peername)) { peer = strdup(tag[1]); } else { peer = NULL; cmd_error = conn_response(CR_ERR_IDENTIFICATION_FAILED); break; } #ifdef HAVE_LIBGNUTLS if (!csync_conn_usessl) { struct csync_nossl *t; for (t = csync_nossl; t; t=t->next) { if ( !fnmatch(t->pattern_from, myhostname, 0) && !fnmatch(t->pattern_to, peer, 0) ) goto conn_without_ssl_ok; } cmd_error = conn_response(CR_ERR_SSL_EXPECTED); } conn_without_ssl_ok:; #endif break; case A_GROUP: if (active_grouplist) { cmd_error = conn_response(CR_ERR_GROUP_LIST_ALREADY_SET); } else { const struct csync_group *g; int i, gnamelen; active_grouplist = strdup(tag[1]); for (g=csync_group; g; g=g->next) { if (!g->myname) continue; i=0; gnamelen = strlen(csync_group->gname); while (active_grouplist[i]) { if ( !strncmp(active_grouplist+i, csync_group->gname, gnamelen) && (active_grouplist[i+gnamelen] == ',' || !active_grouplist[i+gnamelen]) ) goto found_asactive; while (active_grouplist[i]) if (active_grouplist[i++]==',') break; } csync_group->myname = 0; found_asactive: ; } } break; case A_BYE: for (i=0; i<32; i++) free(tag[i]); conn_resp(CR_OK_CU_LATER); return; } if ( cmdtab[cmdnr].update ) csync_file_update(tag[2], peer); if ( cmdtab[cmdnr].update == 1 ) { csync_debug(1, "Updated %s from %s.\n", tag[2], peer ? peer : "???"); csync_schedule_commands(tag[2], 0); } abort_cmd: if ( cmd_error ) conn_printf("%s\n", cmd_error); else conn_resp(CR_OK_CMD_FINISHED); next_cmd: destroy_tag(tag); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'fail HELLO command when SSL is required'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: State() : remote_encode_complete_(false), remote_decode_complete_(false), local_complete_(false), has_1xx_headers_(false), created_filter_chain_(false), is_head_request_(false), is_grpc_request_(false), non_100_response_headers_encoded_(false), under_on_local_reply_(false), decoder_filter_chain_aborted_(false), encoder_filter_chain_aborted_(false), saw_downstream_reset_(false) {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'internal redirect: fix a lifetime bug (#785) Signed-off-by: Alyssa Wilk <alyssar@chromium.org> Signed-off-by: Matt Klein <mklein@lyft.com> Signed-off-by: Pradeep Rao <pcrao@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEE_Result syscall_hash_final(unsigned long state, const void *chunk, size_t chunk_size, void *hash, uint64_t *hash_len) { TEE_Result res, res2; size_t hash_size; size_t hlen = 0; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = get_user_u64_as_size_t(&hlen, hash_len); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)hash, hlen); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = tee_hash_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (hlen < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = tee_mac_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (hlen < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } out: res2 = put_user_u64(hash_len, hash_size); if (res2 != TEE_SUCCESS) return res2; return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'cryp: prevent direct calls to update and final functions With inconsistent or malformed data it has been possible to call "update" and "final" crypto functions directly. Using a fuzzer tool [1] we have seen that this results in asserts, i.e., a crash that potentially could leak sensitive information. By setting the state (initialized) in the crypto context (i.e., the tee_cryp_state) at the end of all syscall_*_init functions and then add a check of the state at the beginning of all update and final functions, we prevent direct entrance to the "update" and "final" functions. [1] https://github.com/MartijnB/optee_fuzzer Fixes: OP-TEE-2019-0021 Signed-off-by: Joakim Bech <joakim.bech@linaro.org> Reported-by: Martijn Bogaard <bogaard@riscure.com> Acked-by: Jerome Forissier <jerome.forissier@linaro.org> Reviewed-by: Jens Wiklander <jens.wiklander@linaro.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int sql_auxprop_store(void *glob_context, sasl_server_params_t *sparams, struct propctx *ctx, const char *user, unsigned ulen) { char *userid = NULL; char *realm = NULL; const char *user_realm = NULL; int ret = SASL_FAIL; const struct propval *to_store, *cur; char *user_buf; char *statement = NULL; char *escap_userid = NULL; char *escap_realm = NULL; const char *cmd; sql_settings_t *settings; void *conn = NULL; settings = (sql_settings_t *) glob_context; /* just checking if we are enabled */ if (!ctx && sql_exists(settings->sql_insert) && sql_exists(settings->sql_update)) return SASL_OK; /* make sure our input is okay */ if (!glob_context || !sparams || !user) return SASL_BADPARAM; sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG, "sql plugin Parse the username %s\n", user); user_buf = sparams->utils->malloc(ulen + 1); if (!user_buf) { ret = SASL_NOMEM; goto done; } memcpy(user_buf, user, ulen); user_buf[ulen] = '\0'; if (sparams->user_realm) { user_realm = sparams->user_realm; } else { user_realm = sparams->serverFQDN; } ret = _plug_parseuser(sparams->utils, &userid, &realm, user_realm, sparams->serverFQDN, user_buf); if (ret != SASL_OK) goto done; /* just need to escape userid and realm now */ /* allocate some memory */ escap_userid = (char *) sparams->utils->malloc(strlen(userid)*2+1); escap_realm = (char *) sparams->utils->malloc(strlen(realm)*2+1); if (!escap_userid || !escap_realm) { MEMERROR(sparams->utils); goto done; } to_store = sparams->utils->prop_get(ctx); if (!to_store) { ret = SASL_BADPARAM; goto done; } conn = sql_connect(settings, sparams->utils); if (!conn) { sparams->utils->log(sparams->utils->conn, SASL_LOG_ERR, "sql plugin couldn't connect to any host\n"); goto done; } settings->sql_engine->sql_escape_str(escap_userid, userid); settings->sql_engine->sql_escape_str(escap_realm, realm); if (settings->sql_engine->sql_begin_txn(conn, sparams->utils)) { sparams->utils->log(sparams->utils->conn, SASL_LOG_ERR, "Unable to begin transaction\n"); } for (cur = to_store; ret == SASL_OK && cur->name; cur++) { if (cur->name[0] == '*') { continue; } /* determine which command we need */ /* see if we already have a row for this user */ statement = sql_create_statement(settings->sql_select, SQL_WILDCARD, escap_userid, escap_realm, NULL, sparams->utils); if (!settings->sql_engine->sql_exec(conn, statement, NULL, 0, NULL, sparams->utils)) { /* already have a row => UPDATE */ cmd = settings->sql_update; } else { /* new row => INSERT */ cmd = settings->sql_insert; } sparams->utils->free(statement); /* create a statement that we will use */ statement = sql_create_statement(cmd, cur->name, escap_userid, escap_realm, cur->values && cur->values[0] ? cur->values[0] : SQL_NULL_VALUE, sparams->utils); { char *log_statement = sql_create_statement(cmd, cur->name, escap_userid, escap_realm, cur->values && cur->values[0] ? "<omitted>" : SQL_NULL_VALUE, sparams->utils); sparams->utils->log(sparams->utils->conn, SASL_LOG_DEBUG, "sql plugin doing statement %s\n", log_statement); sparams->utils->free(log_statement); } /* run the statement */ if (settings->sql_engine->sql_exec(conn, statement, NULL, 0, NULL, sparams->utils)) { ret = SASL_FAIL; } sparams->utils->free(statement); } if (ret != SASL_OK) { sparams->utils->log(sparams->utils->conn, SASL_LOG_ERR, "Failed to store auxprop; aborting transaction\n"); if (settings->sql_engine->sql_rollback_txn(conn, sparams->utils)) { sparams->utils->log(sparams->utils->conn, SASL_LOG_ERR, "Unable to rollback transaction\n"); } } else if (settings->sql_engine->sql_commit_txn(conn, sparams->utils)) { sparams->utils->log(sparams->utils->conn, SASL_LOG_ERR, "Unable to commit transaction\n"); } done: if (escap_userid) sparams->utils->free(escap_userid); if (escap_realm) sparams->utils->free(escap_realm); if (conn) settings->sql_engine->sql_close(conn); if (userid) sparams->utils->free(userid); if (realm) sparams->utils->free(realm); if (user_buf) sparams->utils->free(user_buf); return ret; /* do a little dance */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'CVE-2022-24407 Escape password for SQL insert/update commands. Signed-off-by: Klaus Espenlaub <klaus@espenlaub.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GF_Err infe_box_read(GF_Box *s, GF_BitStream *bs) { char *buf; u32 buf_len, i, string_len, string_start; GF_ItemInfoEntryBox *ptr = (GF_ItemInfoEntryBox *)s; ISOM_DECREASE_SIZE(ptr, 4); ptr->item_ID = gf_bs_read_u16(bs); ptr->item_protection_index = gf_bs_read_u16(bs); if (ptr->version == 2) { ISOM_DECREASE_SIZE(ptr, 4); ptr->item_type = gf_bs_read_u32(bs); } buf_len = (u32) (ptr->size); buf = (char*)gf_malloc(buf_len); if (!buf) return GF_OUT_OF_MEM; if (buf_len != gf_bs_read_data(bs, buf, buf_len)) { gf_free(buf); return GF_ISOM_INVALID_FILE; } string_len = 1; string_start = 0; for (i = 0; i < buf_len; i++) { if (buf[i] == 0) { if (!ptr->item_name) { ptr->item_name = (char*)gf_malloc(sizeof(char)*string_len); if (!ptr->item_name) return GF_OUT_OF_MEM; memcpy(ptr->item_name, buf+string_start, string_len); } else if (!ptr->content_type) { ptr->content_type = (char*)gf_malloc(sizeof(char)*string_len); if (!ptr->content_type) return GF_OUT_OF_MEM; memcpy(ptr->content_type, buf+string_start, string_len); } else { ptr->content_encoding = (char*)gf_malloc(sizeof(char)*string_len); if (!ptr->content_encoding) return GF_OUT_OF_MEM; memcpy(ptr->content_encoding, buf+string_start, string_len); } string_start += string_len; string_len = 0; if (ptr->content_encoding && ptr->version == 1) { break; } } string_len++; } gf_free(buf); if (!ptr->item_name || (!ptr->content_type && ptr->version < 2)) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[isoff] Infe without name or content type !\n")); } return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401', 'CWE-787'], 'message': 'fixed #1786 (fuzz)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int xen_netbk_get_extras(struct xenvif *vif, struct xen_netif_extra_info *extras, int work_to_do) { struct xen_netif_extra_info extra; RING_IDX cons = vif->tx.req_cons; do { if (unlikely(work_to_do-- <= 0)) { netdev_dbg(vif->dev, "Missing extra info\n"); return -EBADR; } memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons), sizeof(extra)); if (unlikely(!extra.type || extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) { vif->tx.req_cons = ++cons; netdev_dbg(vif->dev, "Invalid extra type: %d\n", extra.type); return -EINVAL; } memcpy(&extras[extra.type - 1], &extra, sizeof(extra)); vif->tx.req_cons = ++cons; } while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE); return work_to_do; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'xen/netback: shutdown the ring if it contains garbage. A buggy or malicious frontend should not be able to confuse netback. If we spot anything which is not as it should be then shutdown the device and don't try to continue with the ring in a potentially hostile state. Well behaved and non-hostile frontends will not be penalised. As well as making the existing checks for such errors fatal also add a new check that ensures that there isn't an insane number of requests on the ring (i.e. more than would fit in the ring). If the ring contains garbage then previously is was possible to loop over this insane number, getting an error each time and therefore not generating any more pending requests and therefore not exiting the loop in xen_netbk_tx_build_gops for an externded period. Also turn various netdev_dbg calls which no precipitate a fatal error into netdev_err, they are rate limited because the device is shutdown afterwards. This fixes at least one known DoS/softlockup of the backend domain. Signed-off-by: Ian Campbell <ian.campbell@citrix.com> Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Acked-by: Jan Beulich <JBeulich@suse.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac) { struct cm_id_private *cm_id_priv; cm_id_priv = container_of(id, struct cm_id_private, id); if (smac != NULL) memcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac)); if (alt_smac != NULL) memcpy(cm_id_priv->alt_av.smac, alt_smac, sizeof(cm_id_priv->alt_av.smac)); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler The code that resolves the passive side source MAC within the rdma_cm connection request handler was both redundant and buggy, so remove it. It was redundant since later, when an RC QP is modified to RTR state, the resolution will take place in the ib_core module. It was buggy because this callback also deals with UD SIDR exchange, for which we incorrectly looked at the REQ member of the CM event and dereferenced a random value. Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures") Signed-off-by: Moni Shoua <monis@mellanox.com> Signed-off-by: Or Gerlitz <ogerlitz@mellanox.com> Signed-off-by: Roland Dreier <roland@purestorage.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xlate_to_uni(const unsigned char *name, int len, unsigned char *outname, int *longlen, int *outlen, int escape, int utf8, struct nls_table *nls) { const unsigned char *ip; unsigned char nc; unsigned char *op; unsigned int ec; int i, k, fill; int charlen; if (utf8) { *outlen = utf8s_to_utf16s(name, len, (wchar_t *)outname); if (*outlen < 0) return *outlen; else if (*outlen > FAT_LFN_LEN) return -ENAMETOOLONG; op = &outname[*outlen * sizeof(wchar_t)]; } else { if (nls) { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; *outlen += 1) { if (escape && (*ip == ':')) { if (i > len - 5) return -EINVAL; ec = 0; for (k = 1; k < 5; k++) { nc = ip[k]; ec <<= 4; if (nc >= '0' && nc <= '9') { ec |= nc - '0'; continue; } if (nc >= 'a' && nc <= 'f') { ec |= nc - ('a' - 10); continue; } if (nc >= 'A' && nc <= 'F') { ec |= nc - ('A' - 10); continue; } return -EINVAL; } *op++ = ec & 0xFF; *op++ = ec >> 8; ip += 5; i += 5; } else { if ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0) return -EINVAL; ip += charlen; i += charlen; op += 2; } } if (i < len) return -ENAMETOOLONG; } else { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; i++, *outlen += 1) { *op++ = *ip++; *op++ = 0; } if (i < len) return -ENAMETOOLONG; } } *longlen = *outlen; if (*outlen % 13) { *op++ = 0; *op++ = 0; *outlen += 1; if (*outlen % 13) { fill = 13 - (*outlen % 13); for (i = 0; i < fill; i++) { *op++ = 0xff; *op++ = 0xff; } *outlen += fill; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'NLS: improve UTF8 -> UTF16 string conversion routine The utf8s_to_utf16s conversion routine needs to be improved. Unlike its utf16s_to_utf8s sibling, it doesn't accept arguments specifying the maximum length of the output buffer or the endianness of its 16-bit output. This patch (as1501) adds the two missing arguments, and adjusts the only two places in the kernel where the function is called. A follow-on patch will add a third caller that does utilize the new capabilities. The two conversion routines are still annoyingly inconsistent in the way they handle invalid byte combinations. But that's a subject for a different patch. Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: Clemens Ladisch <clemens@ladisch.de> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr, __be16 sport, __be16 dport) { __u32 seq; __u32 hash[12]; struct keydata *keyptr = get_keyptr(); /* The procedure is the same as for IPv4, but addresses are longer. * Thus we must use twothirdsMD4Transform. */ memcpy(hash, saddr, 16); hash[4] = ((__force u16)sport << 16) + (__force u16)dport; memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7); seq = twothirdsMD4Transform((const __u32 *)daddr, hash) & HASH_MASK; seq += keyptr->count; seq += ktime_to_ns(ktime_get_real()); return seq; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <dan@doxpara.com> Tested-by: Willy Tarreau <w@1wt.eu> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus EvalHybridPerChannel(TfLiteContext* context, TfLiteNode* node, TfLiteDepthwiseConvParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output) { float output_activation_min, output_activation_max; CalculateActivationRange(params->activation, &output_activation_min, &output_activation_max); const int input_size = NumElements(input) / SizeOfDimension(input, 0); const int batch_size = SizeOfDimension(input, 0); TfLiteTensor* input_quantized; TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, data->input_quantized_index, &input_quantized)); int8_t* quantized_input_ptr_batch = input_quantized->data.int8; TfLiteTensor* scaling_factors_tensor; TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, data->scaling_factors_index, &scaling_factors_tensor)); float* scaling_factors_ptr = GetTensorData<float>(scaling_factors_tensor); TfLiteTensor* input_offset_tensor; TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, data->input_offset_index, &input_offset_tensor)); int32_t* input_offset_ptr = GetTensorData<int32_t>(input_offset_tensor); for (int b = 0; b < batch_size; ++b) { const int offset = b * input_size; tensor_utils::AsymmetricQuantizeFloats( GetTensorData<float>(input) + offset, input_size, quantized_input_ptr_batch + offset, &scaling_factors_ptr[b], &input_offset_ptr[b]); } DepthwiseParams op_params; op_params.padding_type = PaddingType::kSame; op_params.padding_values.width = data->padding.width; op_params.padding_values.height = data->padding.height; op_params.stride_width = params->stride_width; op_params.stride_height = params->stride_height; op_params.dilation_width_factor = params->dilation_width_factor; op_params.dilation_height_factor = params->dilation_height_factor; op_params.depth_multiplier = params->depth_multiplier; op_params.weights_offset = 0; op_params.float_activation_min = output_activation_min; op_params.float_activation_max = output_activation_max; const auto* affine_quantization = reinterpret_cast<TfLiteAffineQuantization*>(filter->quantization.params); if (kernel_type == kReference) { reference_integer_ops::DepthwiseConvHybridPerChannel( op_params, scaling_factors_ptr, GetTensorShape(input), quantized_input_ptr_batch, GetTensorShape(filter), GetTensorData<int8>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output), affine_quantization->scale->data, input_offset_ptr); } else { optimized_integer_ops::DepthwiseConvHybridPerChannel( op_params, scaling_factors_ptr, GetTensorShape(input), quantized_input_ptr_batch, GetTensorShape(filter), GetTensorData<int8>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output), affine_quantization->scale->data, input_offset_ptr, CpuBackendContext::GetFromContext(context)); } return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'Prevent divisions by 0 PiperOrigin-RevId: 371003153 Change-Id: Idef56c95b9fcaeb97f87e18c7a674dbeb5173204'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #if !defined(TIFFDefaultStripSize) #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff)) #endif const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; uint32 rows_per_strip; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type,exception); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType,exception); (void) SetImageDepth(image,1,exception); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->alpha_trait == UndefinedPixelTrait)) SetImageMonochrome(image,exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->alpha_trait != UndefinedPixelTrait) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); rows_per_strip=TIFFDefaultStripSize(tiff,0); option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; rows_per_strip+=(16-(rows_per_strip % 16)); if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor",exception); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if (image->colorspace == YCbCrColorspace) (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { rows_per_strip=(uint32) image->rows; (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ rows_per_strip=(uint32) image->rows; (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: { rows_per_strip=(uint32) image->rows; break; } #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if (rows_per_strip < 1) rows_per_strip=1; if ((image->rows/rows_per_strip) >= (1UL << 15)) rows_per_strip=(uint32) (image->rows >> 15); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "TIFF: negative image positions unsupported","%s",image->filename); if ((image->page.x > 0) && (image->resolution.x > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->resolution.x); } if ((image->page.y > 0) && (image->resolution.y > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->resolution.y); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image,exception); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image,exception); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=(unsigned char *) GetQuantumPixels(quantum_info); tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'Fix TIFF divide by zero (bug report from Donghai Zhu)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum) { size_t extent; if (CheckMemoryOverflow(count,quantum) != MagickFalse) return((void *) NULL); extent=count*quantum; return(AcquireMagickMemory(extent)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Suspend exception processing if too many exceptions'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame, const uint8_t *buf, int buf_size, int first_field) { int i, cid, ret; int old_bit_depth = ctx->bit_depth, bitdepth; uint64_t header_prefix; if (buf_size < 0x280) { av_log(ctx->avctx, AV_LOG_ERROR, "buffer too small (%d < 640).\n", buf_size); return AVERROR_INVALIDDATA; } header_prefix = ff_dnxhd_parse_header_prefix(buf); if (header_prefix == 0) { av_log(ctx->avctx, AV_LOG_ERROR, "unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n", buf[0], buf[1], buf[2], buf[3], buf[4]); return AVERROR_INVALIDDATA; } if (buf[5] & 2) { /* interlaced */ ctx->cur_field = buf[5] & 1; frame->interlaced_frame = 1; frame->top_field_first = first_field ^ ctx->cur_field; av_log(ctx->avctx, AV_LOG_DEBUG, "interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field); } else { ctx->cur_field = 0; } ctx->mbaff = (buf[0x6] >> 5) & 1; ctx->height = AV_RB16(buf + 0x18); ctx->width = AV_RB16(buf + 0x1a); switch(buf[0x21] >> 5) { case 1: bitdepth = 8; break; case 2: bitdepth = 10; break; case 3: bitdepth = 12; break; default: av_log(ctx->avctx, AV_LOG_ERROR, "Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5); return AVERROR_INVALIDDATA; } cid = AV_RB32(buf + 0x28); ctx->avctx->profile = dnxhd_get_profile(cid); if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0) return ret; if (ctx->mbaff && ctx->cid_table->cid != 1260) av_log(ctx->avctx, AV_LOG_WARNING, "Adaptive MB interlace flag in an unsupported profile.\n"); ctx->act = buf[0x2C] & 7; if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270) av_log(ctx->avctx, AV_LOG_WARNING, "Adaptive color transform in an unsupported profile.\n"); ctx->is_444 = (buf[0x2C] >> 6) & 1; if (ctx->is_444) { if (bitdepth == 8) { avpriv_request_sample(ctx->avctx, "4:4:4 8 bits"); return AVERROR_INVALIDDATA; } else if (bitdepth == 10) { ctx->decode_dct_block = dnxhd_decode_dct_block_10_444; ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10 : AV_PIX_FMT_GBRP10; } else { ctx->decode_dct_block = dnxhd_decode_dct_block_12_444; ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12 : AV_PIX_FMT_GBRP12; } } else if (bitdepth == 12) { ctx->decode_dct_block = dnxhd_decode_dct_block_12; ctx->pix_fmt = AV_PIX_FMT_YUV422P12; } else if (bitdepth == 10) { if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX) ctx->decode_dct_block = dnxhd_decode_dct_block_10_444; else ctx->decode_dct_block = dnxhd_decode_dct_block_10; ctx->pix_fmt = AV_PIX_FMT_YUV422P10; } else { ctx->decode_dct_block = dnxhd_decode_dct_block_8; ctx->pix_fmt = AV_PIX_FMT_YUV422P; } ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth; if (ctx->bit_depth != old_bit_depth) { ff_blockdsp_init(&ctx->bdsp, ctx->avctx); ff_idctdsp_init(&ctx->idsp, ctx->avctx); ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable, ff_zigzag_direct); } // make sure profile size constraints are respected // DNx100 allows 1920->1440 and 1280->960 subsampling if (ctx->width != ctx->cid_table->width && ctx->cid_table->width != DNXHD_VARIABLE) { av_reduce(&ctx->avctx->sample_aspect_ratio.num, &ctx->avctx->sample_aspect_ratio.den, ctx->width, ctx->cid_table->width, 255); ctx->width = ctx->cid_table->width; } if (buf_size < ctx->cid_table->coding_unit_size) { av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n", buf_size, ctx->cid_table->coding_unit_size); return AVERROR_INVALIDDATA; } ctx->mb_width = (ctx->width + 15)>> 4; ctx->mb_height = AV_RB16(buf + 0x16c); if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame) ctx->height <<= 1; av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n", ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2", ctx->bit_depth, ctx->mbaff, ctx->act); // Newer format supports variable mb_scan_index sizes if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) { ctx->data_offset = 0x170 + (ctx->mb_height << 2); } else { if (ctx->mb_height > 68 || (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) { av_log(ctx->avctx, AV_LOG_ERROR, "mb height too big: %d\n", ctx->mb_height); return AVERROR_INVALIDDATA; } ctx->data_offset = 0x280; } if (buf_size < ctx->data_offset) { av_log(ctx->avctx, AV_LOG_ERROR, "buffer too small (%d < %d).\n", buf_size, ctx->data_offset); return AVERROR_INVALIDDATA; } if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) { av_log(ctx->avctx, AV_LOG_ERROR, "mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index)); return AVERROR_INVALIDDATA; } for (i = 0; i < ctx->mb_height; i++) { ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2)); ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n", i, 0x170 + (i << 2), ctx->mb_scan_index[i]); if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) { av_log(ctx->avctx, AV_LOG_ERROR, "invalid mb scan index (%"PRIu32" vs %u).\n", ctx->mb_scan_index[i], buf_size - ctx->data_offset); return AVERROR_INVALIDDATA; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'avcodec/dnxhddec: Move mb height check out of non hr branch Fixes: out of array access Fixes: poc.dnxhd Found-by: Bingchang, Liu@VARAS of IIE Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void fmtutil_macbitmap_read_pixmap_only_fields(deark *c, dbuf *f, struct fmtutil_macbitmap_info *bi, i64 pos) { i64 pixmap_version; i64 pack_size; i64 plane_bytes; i64 n; de_dbg(c, "additional PixMap header fields, at %d", (int)pos); de_dbg_indent(c, 1); pixmap_version = dbuf_getu16be(f, pos+0); de_dbg(c, "pixmap version: %d", (int)pixmap_version); bi->packing_type = dbuf_getu16be(f, pos+2); de_dbg(c, "packing type: %d", (int)bi->packing_type); pack_size = dbuf_getu32be(f, pos+4); de_dbg(c, "pixel data length: %d", (int)pack_size); bi->hdpi = pict_read_fixed(f, pos+8); bi->vdpi = pict_read_fixed(f, pos+12); de_dbg(c, "dpi: %.2f"DE_CHAR_TIMES"%.2f", bi->hdpi, bi->vdpi); bi->pixeltype = dbuf_getu16be(f, pos+16); bi->pixelsize = dbuf_getu16be(f, pos+18); bi->cmpcount = dbuf_getu16be(f, pos+20); bi->cmpsize = dbuf_getu16be(f, pos+22); de_dbg(c, "pixel type=%d, bits/pixel=%d, components/pixel=%d, bits/comp=%d", (int)bi->pixeltype, (int)bi->pixelsize, (int)bi->cmpcount, (int)bi->cmpsize); bi->pdwidth = (bi->rowbytes*8)/bi->pixelsize; if(bi->pdwidth < bi->npwidth) { bi->pdwidth = bi->npwidth; } plane_bytes = dbuf_getu32be(f, pos+24); de_dbg(c, "plane bytes: %d", (int)plane_bytes); bi->pmTable = (u32)dbuf_getu32be(f, pos+28); de_dbg(c, "pmTable: 0x%08x", (unsigned int)bi->pmTable); n = dbuf_getu32be(f, pos+32); de_dbg(c, "pmReserved: 0x%08x", (unsigned int)n); de_dbg_indent(c, -1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'pict,macrsrc: Fixed a bug that could cause division by 0 Found by F. Çelik.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TfLiteStatus PopulateQuantizedLstmParams8x8_16( TfLiteContext* context, TfLiteNode* node, lstm_eval::IntegerLstmParameter* integer_lstm_param) { // Calculate quantized clip for projection and cell. const auto* params = static_cast<TfLiteUnidirectionalSequenceLSTMParams*>(node->builtin_data); const float cell_clip = params->cell_clip; const float proj_clip = params->proj_clip; const TfLiteTensor* cell_state = GetVariableInput(context, node, lstm::full::kCellStateTensor); TF_LITE_ENSURE(context, cell_state != nullptr); TfLiteTensor* output_tensor; TF_LITE_ENSURE_OK( context, GetOutputSafe(context, node, lstm::full::kOutputTensor, &output_tensor)); auto* cell_state_params = static_cast<TfLiteAffineQuantization*>(cell_state->quantization.params); auto* proj_params = static_cast<TfLiteAffineQuantization*>( output_tensor->quantization.params); if (cell_clip > 0.0) { integer_lstm_param->quantized_cell_clip = static_cast<int16_t>(std::min( std::max(cell_clip / cell_state_params->scale->data[0], -32768.0f), 32767.0f)); } else { integer_lstm_param->quantized_cell_clip = 0; } if (proj_clip > 0.0) { integer_lstm_param->quantized_proj_clip = static_cast<int8_t>(std::min( std::max(proj_clip / proj_params->scale->data[0], -128.0f), 127.0f)); } else { integer_lstm_param->quantized_proj_clip = 0; } // Calculate effective scales. OpData* op_data = static_cast<OpData*>(node->user_data); const bool use_layer_norm = op_data->use_layer_norm; const TfLiteTensor* input; TF_LITE_ENSURE_OK( context, GetInputSafe(context, node, lstm::full::kInputTensor, &input)); const TfLiteTensor* input_to_input_weights = GetOptionalInputTensor( context, node, lstm::full::kInputToInputWeightsTensor); const TfLiteTensor* input_to_forget_weights; TF_LITE_ENSURE_OK( context, GetInputSafe(context, node, lstm::full::kInputToForgetWeightsTensor, &input_to_forget_weights)); const TfLiteTensor* input_to_cell_weights; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, lstm::full::kInputToCellWeightsTensor, &input_to_cell_weights)); const TfLiteTensor* input_to_output_weights; TF_LITE_ENSURE_OK( context, GetInputSafe(context, node, lstm::full::kInputToOutputWeightsTensor, &input_to_output_weights)); const TfLiteTensor* recurrent_to_input_weights = GetOptionalInputTensor( context, node, lstm::full::kRecurrentToInputWeightsTensor); const TfLiteTensor* recurrent_to_forget_weights; TF_LITE_ENSURE_OK( context, GetInputSafe(context, node, lstm::full::kRecurrentToForgetWeightsTensor, &recurrent_to_forget_weights)); const TfLiteTensor* recurrent_to_cell_weights; TF_LITE_ENSURE_OK( context, GetInputSafe(context, node, lstm::full::kRecurrentToCellWeightsTensor, &recurrent_to_cell_weights)); const TfLiteTensor* recurrent_to_output_weights; TF_LITE_ENSURE_OK( context, GetInputSafe(context, node, lstm::full::kRecurrentToOutputWeightsTensor, &recurrent_to_output_weights)); const TfLiteTensor* cell_to_input_weights = GetOptionalInputTensor( context, node, lstm::full::kCellToInputWeightsTensor); const TfLiteTensor* cell_to_forget_weights = GetOptionalInputTensor( context, node, lstm::full::kCellToForgetWeightsTensor); const TfLiteTensor* cell_to_output_weights = GetOptionalInputTensor( context, node, lstm::full::kCellToOutputWeightsTensor); const TfLiteTensor* input_layer_norm_coefficients = GetOptionalInputTensor( context, node, lstm::full::kInputLayerNormCoefficientsTensor); const TfLiteTensor* forget_layer_norm_coefficients = GetOptionalInputTensor( context, node, lstm::full::kForgetLayerNormCoefficientsTensor); const TfLiteTensor* cell_layer_norm_coefficients = GetOptionalInputTensor( context, node, lstm::full::kCellLayerNormCoefficientsTensor); const TfLiteTensor* output_layer_norm_coefficients = GetOptionalInputTensor( context, node, lstm::full::kOutputLayerNormCoefficientsTensor); const TfLiteTensor* projection_weights = GetOptionalInputTensor( context, node, lstm::full::kProjectionWeightsTensor); TfLiteTensor* output_state = GetVariableInput(context, node, lstm::full::kOutputStateTensor); TF_LITE_ENSURE(context, output_state != nullptr); // Since we have already checked that weights are all there or none, we can // check the existence of only one to get the condition. const bool use_cifg = (input_to_input_weights == nullptr); const bool use_peephole = (cell_to_output_weights != nullptr); const bool use_projection = (projection_weights != nullptr); // Get intermediate scales and zero points. std::vector<float> intermediate_scale; std::vector<int32> intermediate_zp; for (int i = 0; i < 4; ++i) { if (use_layer_norm) { TfLiteTensor* intermediate; TF_LITE_ENSURE_OK(context, GetIntermediatesSafe(context, node, i, &intermediate)); auto* params = static_cast<TfLiteAffineQuantization*>( intermediate->quantization.params); intermediate_scale.push_back(params->scale->data[0]); intermediate_zp.push_back(params->zero_point->data[0]); } else { // Q3.12 for activation functions. intermediate_scale.push_back(std::pow(2, -12)); intermediate_zp.push_back(0); } } // In the absence of projection, hidden becomes otuput and this intermediate // is ignored. TfLiteTensor* hidden; TF_LITE_ENSURE_OK(context, GetIntermediatesSafe(context, node, 4, &hidden)); auto* hidden_params = static_cast<TfLiteAffineQuantization*>(hidden->quantization.params); intermediate_scale.push_back(hidden_params->scale->data[0]); intermediate_zp.push_back(hidden_params->zero_point->data[0]); // Scales. const float default_scale = 1.0; float input_scale = default_scale; float input_to_input_weight_scale = default_scale; float recurrent_to_input_weight_scale = default_scale; float cell_to_input_weight_scale = default_scale; float input_to_forget_weight_scale = default_scale; float recurrent_to_forget_weight_scale = default_scale; float cell_to_forget_weight_scale = default_scale; float input_to_cell_weight_scale = default_scale; float recurrent_to_cell_weight_scale = default_scale; float input_to_output_weight_scale = default_scale; float recurrent_to_output_weight_scale = default_scale; float cell_to_output_weight_scale = default_scale; float projection_weight_scale = default_scale; float layer_norm_input_scale = default_scale; float layer_norm_forget_scale = default_scale; float layer_norm_cell_scale = default_scale; float layer_norm_output_scale = default_scale; float output_state_scale = default_scale; int cell_scale = 1; // Effective scales. float effective_input_to_input_scale = default_scale; float effective_recurrent_to_input_scale = default_scale; float effective_cell_to_input_scale = default_scale; float effective_input_to_forget_scale = default_scale; float effective_recurrent_to_forget_scale = default_scale; float effective_cell_to_forget_scale = default_scale; float effective_input_to_cell_scale = default_scale; float effective_recurrent_to_cell_scale = default_scale; float effective_input_to_output_scale = default_scale; float effective_recurrent_to_output_scale = default_scale; float effective_cell_to_output_scale = default_scale; float effective_proj_scale = default_scale; float effective_hidden_scale = default_scale; // Populate scales. if (!use_cifg) { input_to_input_weight_scale = input_to_input_weights->params.scale; recurrent_to_input_weight_scale = recurrent_to_input_weights->params.scale; } if (use_peephole) { if (!use_cifg) { cell_to_input_weight_scale = cell_to_input_weights->params.scale; } cell_to_forget_weight_scale = cell_to_forget_weights->params.scale; cell_to_output_weight_scale = cell_to_output_weights->params.scale; } if (use_layer_norm) { if (!use_cifg) { layer_norm_input_scale = input_layer_norm_coefficients->params.scale; } layer_norm_forget_scale = forget_layer_norm_coefficients->params.scale; layer_norm_cell_scale = cell_layer_norm_coefficients->params.scale; layer_norm_output_scale = output_layer_norm_coefficients->params.scale; } if (use_projection) { projection_weight_scale = projection_weights->params.scale; } output_state_scale = output_state->params.scale; input_to_forget_weight_scale = input_to_forget_weights->params.scale; input_to_cell_weight_scale = input_to_cell_weights->params.scale; input_to_output_weight_scale = input_to_output_weights->params.scale; recurrent_to_forget_weight_scale = recurrent_to_forget_weights->params.scale; recurrent_to_cell_weight_scale = recurrent_to_cell_weights->params.scale; recurrent_to_output_weight_scale = recurrent_to_output_weights->params.scale; // Check cell state (already used above) TF_LITE_ENSURE(context, CheckedLog2(cell_state->params.scale, &cell_scale)); // TF_LITE_ENSURE(context, cell_scale <= -9); integer_lstm_param->cell_scale = cell_scale; input_scale = input->params.scale; // Calculate effective scales. if (!use_cifg) { effective_input_to_input_scale = input_to_input_weight_scale * input_scale / intermediate_scale[0]; effective_recurrent_to_input_scale = recurrent_to_input_weight_scale * output_state_scale / intermediate_scale[0]; } effective_input_to_forget_scale = input_to_forget_weight_scale * input_scale / intermediate_scale[1]; effective_recurrent_to_forget_scale = recurrent_to_forget_weight_scale * output_state_scale / intermediate_scale[1]; effective_input_to_cell_scale = input_to_cell_weight_scale * input_scale / intermediate_scale[2]; effective_recurrent_to_cell_scale = recurrent_to_cell_weight_scale * output_state_scale / intermediate_scale[2]; effective_input_to_output_scale = input_to_output_weight_scale * input_scale / intermediate_scale[3]; effective_recurrent_to_output_scale = recurrent_to_output_weight_scale * output_state_scale / intermediate_scale[3]; effective_hidden_scale = std::pow(2, -15) / intermediate_scale[4] * std::pow(2, -15); effective_proj_scale = projection_weight_scale * intermediate_scale[4] / output_state_scale; if (use_peephole) { if (!use_cifg) { effective_cell_to_input_scale = std::pow(2, cell_scale) * // NOLINT cell_to_input_weight_scale / intermediate_scale[0]; } effective_cell_to_forget_scale = std::pow(2, cell_scale) * // NOLINT cell_to_forget_weight_scale / intermediate_scale[1]; effective_cell_to_output_scale = std::pow(2, cell_scale) * // NOLINT cell_to_output_weight_scale / intermediate_scale[3]; } // Decompose scales. QuantizeMultiplier(effective_input_to_input_scale, &integer_lstm_param->effective_input_to_input_scale_a, &integer_lstm_param->effective_input_to_input_scale_b); QuantizeMultiplier(effective_recurrent_to_input_scale, &integer_lstm_param->effective_recurrent_to_input_scale_a, &integer_lstm_param->effective_recurrent_to_input_scale_b); QuantizeMultiplier(effective_cell_to_input_scale, &integer_lstm_param->effective_cell_to_input_scale_a, &integer_lstm_param->effective_cell_to_input_scale_b); QuantizeMultiplier(effective_input_to_forget_scale, &integer_lstm_param->effective_input_to_forget_scale_a, &integer_lstm_param->effective_input_to_forget_scale_b); QuantizeMultiplier( effective_recurrent_to_forget_scale, &integer_lstm_param->effective_recurrent_to_forget_scale_a, &integer_lstm_param->effective_recurrent_to_forget_scale_b); QuantizeMultiplier(effective_cell_to_forget_scale, &integer_lstm_param->effective_cell_to_forget_scale_a, &integer_lstm_param->effective_cell_to_forget_scale_b); QuantizeMultiplier(effective_input_to_cell_scale, &integer_lstm_param->effective_input_to_cell_scale_a, &integer_lstm_param->effective_input_to_cell_scale_b); QuantizeMultiplier(effective_recurrent_to_cell_scale, &integer_lstm_param->effective_recurrent_to_cell_scale_a, &integer_lstm_param->effective_recurrent_to_cell_scale_b); QuantizeMultiplier(effective_input_to_output_scale, &integer_lstm_param->effective_input_to_output_scale_a, &integer_lstm_param->effective_input_to_output_scale_b); QuantizeMultiplier( effective_recurrent_to_output_scale, &integer_lstm_param->effective_recurrent_to_output_scale_a, &integer_lstm_param->effective_recurrent_to_output_scale_b); QuantizeMultiplier(effective_cell_to_output_scale, &integer_lstm_param->effective_cell_to_output_scale_a, &integer_lstm_param->effective_cell_to_output_scale_b); QuantizeMultiplier(effective_proj_scale, &integer_lstm_param->effective_proj_scale_a, &integer_lstm_param->effective_proj_scale_b); QuantizeMultiplier(effective_hidden_scale, &integer_lstm_param->effective_hidden_scale_a, &integer_lstm_param->effective_hidden_scale_b); QuantizeMultiplier(layer_norm_input_scale, &integer_lstm_param->layer_norm_input_scale_a, &integer_lstm_param->layer_norm_input_scale_b); QuantizeMultiplier(layer_norm_forget_scale, &integer_lstm_param->layer_norm_forget_scale_a, &integer_lstm_param->layer_norm_forget_scale_b); QuantizeMultiplier(layer_norm_cell_scale, &integer_lstm_param->layer_norm_cell_scale_a, &integer_lstm_param->layer_norm_cell_scale_b); QuantizeMultiplier(layer_norm_output_scale, &integer_lstm_param->layer_norm_output_scale_a, &integer_lstm_param->layer_norm_output_scale_b); integer_lstm_param->hidden_zp = intermediate_zp[4]; // 10000 is used to make sure the kernel logic does not overflow. if (!use_cifg) { integer_lstm_param->input_variance_guard = std::max(1, static_cast<int32_t>(10000 * layer_norm_input_scale)); } integer_lstm_param->forget_variance_guard = std::max(1, static_cast<int32_t>(10000 * layer_norm_forget_scale)); integer_lstm_param->cell_variance_guard = std::max(1, static_cast<int32_t>(10000 * layer_norm_cell_scale)); integer_lstm_param->output_variance_guard = std::max(1, static_cast<int32_t>(10000 * layer_norm_output_scale)); return kTfLiteOk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-908'], 'message': 'Fix a null pointer exception caused by branching on uninitialized data. This is due to not checking that the params for the quantization exists. If there is no quantization, we should not access the `.params` field. PiperOrigin-RevId: 385168337 Change-Id: I28661e4f12ba1c92cfeae23d22a3fb2df2a2c6a4'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pci_lintr_release(struct pci_vdev *dev) { struct businfo *bi; struct slotinfo *si; int pin; bi = pci_businfo[dev->bus]; assert(bi != NULL); si = &bi->slotinfo[dev->slot]; for (pin = 1; pin < 4; pin++) { si->si_intpins[pin].ii_count = 0; si->si_intpins[pin].ii_pirq_pin = 0; si->si_intpins[pin].ii_ioapic_irq = 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core Tracked-On: #3252 Signed-off-by: Shuo A Liu <shuo.a.liu@intel.com> Reviewed-by: Yonghua Huang <yonghua.huang@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pci_lintr_request(struct pci_vdev *dev) { struct businfo *bi; struct slotinfo *si; int bestpin, bestcount, pin; bi = pci_businfo[dev->bus]; assert(bi != NULL); /* * Just allocate a pin from our slot. The pin will be * assigned IRQs later when interrupts are routed. */ si = &bi->slotinfo[dev->slot]; bestpin = 0; bestcount = si->si_intpins[0].ii_count; for (pin = 1; pin < 4; pin++) { if (si->si_intpins[pin].ii_count < bestcount) { bestpin = pin; bestcount = si->si_intpins[pin].ii_count; } } si->si_intpins[bestpin].ii_count++; dev->lintr.pin = bestpin + 1; pci_set_cfgdata8(dev, PCIR_INTPIN, bestpin + 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core Tracked-On: #3252 Signed-off-by: Shuo A Liu <shuo.a.liu@intel.com> Reviewed-by: Yonghua Huang <yonghua.huang@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pci_get_cfgdata16(struct pci_vdev *dev, int offset) { assert(offset <= (PCI_REGMAX - 1) && (offset & 1) == 0); return (*(uint16_t *)(dev->cfgdata + offset)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core Tracked-On: #3252 Signed-off-by: Shuo A Liu <shuo.a.liu@intel.com> Reviewed-by: Yonghua Huang <yonghua.huang@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPM2B_SYM_KEY_Marshal(TPM2B_SYM_KEY *source, BYTE **buffer, INT32 *size) { UINT16 written = 0; written += TPM2B_Marshal(&source->b, buffer, size); return written; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Add maxSize parameter to TPM2B_Marshal for sanity checks Add maxSize parameter to TPM2B_Marshal and assert on it checking the size of the data intended to be marshaled versus the maximum buffer size. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPM2B_Marshal(TPM2B *source, BYTE **buffer, INT32 *size) { UINT16 written = 0; written += UINT16_Marshal(&(source->size), buffer, size); written += Array_Marshal(source->buffer, source->size, buffer, size); return written; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Add maxSize parameter to TPM2B_Marshal for sanity checks Add maxSize parameter to TPM2B_Marshal and assert on it checking the size of the data intended to be marshaled versus the maximum buffer size. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int http_buf_read(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int len; /* read bytes from input buffer first */ len = s->buf_end - s->buf_ptr; if (len > 0) { if (len > size) len = size; memcpy(buf, s->buf_ptr, len); s->buf_ptr += len; } else { int64_t target_end = s->end_off ? s->end_off : s->filesize; if ((!s->willclose || s->chunksize < 0) && target_end >= 0 && s->off >= target_end) return AVERROR_EOF; len = ffurl_read(s->hd, buf, size); if (!len && (!s->willclose || s->chunksize < 0) && target_end >= 0 && s->off < target_end) { av_log(h, AV_LOG_ERROR, "Stream ends prematurely at %"PRId64", should be %"PRId64"\n", s->off, target_end ); return AVERROR(EIO); } } if (len > 0) { s->off += len; if (s->chunksize > 0) s->chunksize -= len; } return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.com>.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned int munlock_vma_page(struct page *page) { unsigned int nr_pages; struct zone *zone = page_zone(page); BUG_ON(!PageLocked(page)); /* * Serialize with any parallel __split_huge_page_refcount() which * might otherwise copy PageMlocked to part of the tail pages before * we clear it in the head page. It also stabilizes hpage_nr_pages(). */ spin_lock_irq(&zone->lru_lock); nr_pages = hpage_nr_pages(page); if (!TestClearPageMlocked(page)) goto unlock_out; __mod_zone_page_state(zone, NR_MLOCK, -nr_pages); if (__munlock_isolate_lru_page(page, true)) { spin_unlock_irq(&zone->lru_lock); __munlock_isolated_page(page); goto out; } __munlock_isolation_failed(page); unlock_out: spin_unlock_irq(&zone->lru_lock); out: return nr_pages - 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-264'], 'message': 'mm: try_to_unmap_cluster() should lock_page() before mlocking A BUG_ON(!PageLocked) was triggered in mlock_vma_page() by Sasha Levin fuzzing with trinity. The call site try_to_unmap_cluster() does not lock the pages other than its check_page parameter (which is already locked). The BUG_ON in mlock_vma_page() is not documented and its purpose is somewhat unclear, but apparently it serializes against page migration, which could otherwise fail to transfer the PG_mlocked flag. This would not be fatal, as the page would be eventually encountered again, but NR_MLOCK accounting would become distorted nevertheless. This patch adds a comment to the BUG_ON in mlock_vma_page() and munlock_vma_page() to that effect. The call site try_to_unmap_cluster() is fixed so that for page != check_page, trylock_page() is attempted (to avoid possible deadlocks as we already have check_page locked) and mlock_vma_page() is performed only upon success. If the page lock cannot be obtained, the page is left without PG_mlocked, which is again not a problem in the whole unevictable memory design. Signed-off-by: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Bob Liu <bob.liu@oracle.com> Reported-by: Sasha Levin <sasha.levin@oracle.com> Cc: Wanpeng Li <liwanp@linux.vnet.ibm.com> Cc: Michel Lespinasse <walken@google.com> Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: David Rientjes <rientjes@google.com> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { EXRContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; uint8_t *ptr; int i, y, ret, ymax; int planes; int out_line_size; int nb_blocks; /* nb scanline or nb tile */ uint64_t start_offset_table; uint64_t start_next_scanline; PutByteContext offset_table_writer; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_header(s, picture)) < 0) return ret; switch (s->pixel_type) { case EXR_FLOAT: case EXR_HALF: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } else { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRPF32; } else { avctx->pix_fmt = AV_PIX_FMT_GRAYF32; } } break; case EXR_UINT: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGBA64; } else { avctx->pix_fmt = AV_PIX_FMT_YA16; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGB48; } else { avctx->pix_fmt = AV_PIX_FMT_GRAY16; } } break; default: av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n"); return AVERROR_INVALIDDATA; } if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED) avctx->color_trc = s->apply_trc_type; switch (s->compression) { case EXR_RAW: case EXR_RLE: case EXR_ZIP1: s->scan_lines_per_block = 1; break; case EXR_PXR24: case EXR_ZIP16: s->scan_lines_per_block = 16; break; case EXR_PIZ: case EXR_B44: case EXR_B44A: s->scan_lines_per_block = 32; break; default: avpriv_report_missing_feature(avctx, "Compression %d", s->compression); return AVERROR_PATCHWELCOME; } /* Verify the xmin, xmax, ymin and ymax before setting the actual image size. * It's possible for the data window can larger or outside the display window */ if (s->xmin > s->xmax || s->ymin > s->ymax || s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) { av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n"); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0) return ret; s->desc = av_pix_fmt_desc_get(avctx->pix_fmt); if (!s->desc) return AVERROR_INVALIDDATA; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { planes = s->desc->nb_components; out_line_size = avctx->width * 4; } else { planes = 1; out_line_size = avctx->width * 2 * s->desc->nb_components; } if (s->is_tile) { nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) * ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize); } else { /* scanline */ nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) / s->scan_lines_per_block; } if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks) return AVERROR_INVALIDDATA; // check offset table and recreate it if need if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) { av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n"); start_offset_table = bytestream2_tell(&s->gb); start_next_scanline = start_offset_table + nb_blocks * 8; bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8); for (y = 0; y < nb_blocks; y++) { /* write offset of prev scanline in offset table */ bytestream2_put_le64(&offset_table_writer, start_next_scanline); /* get len of next scanline */ bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */ start_next_scanline += (bytestream2_get_le32(&s->gb) + 8); } bytestream2_seek(&s->gb, start_offset_table, SEEK_SET); } // save pointer we are going to use in decode_block s->buf = avpkt->data; s->buf_size = avpkt->size; // Zero out the start if ymin is not 0 for (i = 0; i < planes; i++) { ptr = picture->data[i]; for (y = 0; y < s->ymin; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } s->picture = picture; avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks); ymax = FFMAX(0, s->ymax + 1); // Zero out the end if ymax+1 is not h for (i = 0; i < planes; i++) { ptr = picture->data[i] + (ymax * picture->linesize[i]); for (y = ymax; y < avctx->height; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } picture->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/exr: Check ymin vs. h Fixes: out of array access Fixes: 26532/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_EXR_fuzzer-5613925708857344 Fixes: 27443/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_EXR_fuzzer-5631239813595136 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ssl2_read_internal(SSL *s, void *buf, int len, int peek) { int n; unsigned char mac[MAX_MAC_SIZE]; unsigned char *p; int i; unsigned int mac_size; ssl2_read_again: if (SSL_in_init(s) && !s->in_handshake) { n=s->handshake_func(s); if (n < 0) return(n); if (n == 0) { SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } } clear_sys_error(); s->rwstate=SSL_NOTHING; if (len <= 0) return(len); if (s->s2->ract_data_length != 0) /* read from buffer */ { if (len > s->s2->ract_data_length) n=s->s2->ract_data_length; else n=len; memcpy(buf,s->s2->ract_data,(unsigned int)n); if (!peek) { s->s2->ract_data_length-=n; s->s2->ract_data+=n; if (s->s2->ract_data_length == 0) s->rstate=SSL_ST_READ_HEADER; } return(n); } /* s->s2->ract_data_length == 0 * * Fill the buffer, then goto ssl2_read_again. */ if (s->rstate == SSL_ST_READ_HEADER) { if (s->first_packet) { n=read_n(s,5,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0); if (n <= 0) return(n); /* error or non-blocking */ s->first_packet=0; p=s->packet; if (!((p[0] & 0x80) && ( (p[2] == SSL2_MT_CLIENT_HELLO) || (p[2] == SSL2_MT_SERVER_HELLO)))) { SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_NON_SSLV2_INITIAL_PACKET); return(-1); } } else { n=read_n(s,2,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0); if (n <= 0) return(n); /* error or non-blocking */ } /* part read stuff */ s->rstate=SSL_ST_READ_BODY; p=s->packet; /* Do header */ /*s->s2->padding=0;*/ s->s2->escape=0; s->s2->rlength=(((unsigned int)p[0])<<8)|((unsigned int)p[1]); if ((p[0] & TWO_BYTE_BIT)) /* Two byte header? */ { s->s2->three_byte_header=0; s->s2->rlength&=TWO_BYTE_MASK; } else { s->s2->three_byte_header=1; s->s2->rlength&=THREE_BYTE_MASK; /* security >s2->escape */ s->s2->escape=((p[0] & SEC_ESC_BIT))?1:0; } } if (s->rstate == SSL_ST_READ_BODY) { n=s->s2->rlength+2+s->s2->three_byte_header; if (n > (int)s->packet_length) { n-=s->packet_length; i=read_n(s,(unsigned int)n,(unsigned int)n,1); if (i <= 0) return(i); /* ERROR */ } p= &(s->packet[2]); s->rstate=SSL_ST_READ_HEADER; if (s->s2->three_byte_header) s->s2->padding= *(p++); else s->s2->padding=0; /* Data portion */ if (s->s2->clear_text) { mac_size = 0; s->s2->mac_data=p; s->s2->ract_data=p; if (s->s2->padding) { SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_ILLEGAL_PADDING); return(-1); } } else { mac_size=EVP_MD_size(s->read_hash); OPENSSL_assert(mac_size <= MAX_MAC_SIZE); s->s2->mac_data=p; s->s2->ract_data= &p[mac_size]; if (s->s2->padding + mac_size > s->s2->rlength) { SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_ILLEGAL_PADDING); return(-1); } } s->s2->ract_data_length=s->s2->rlength; /* added a check for length > max_size in case * encryption was not turned on yet due to an error */ if ((!s->s2->clear_text) && (s->s2->rlength >= mac_size)) { ssl2_enc(s,0); s->s2->ract_data_length-=mac_size; ssl2_mac(s,mac,0); s->s2->ract_data_length-=s->s2->padding; if ( (memcmp(mac,s->s2->mac_data, (unsigned int)mac_size) != 0) || (s->s2->rlength%EVP_CIPHER_CTX_block_size(s->enc_read_ctx) != 0)) { SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_BAD_MAC_DECODE); return(-1); } } INC32(s->s2->read_sequence); /* expect next number */ /* s->s2->ract_data is now available for processing */ /* Possibly the packet that we just read had 0 actual data bytes. * (SSLeay/OpenSSL itself never sends such packets; see ssl2_write.) * In this case, returning 0 would be interpreted by the caller * as indicating EOF, so it's not a good idea. Instead, we just * continue reading; thus ssl2_read_internal may have to process * multiple packets before it can return. * * [Note that using select() for blocking sockets *never* guarantees * that the next SSL_read will not block -- the available * data may contain incomplete packets, and except for SSL 2, * renegotiation can confuse things even more.] */ goto ssl2_read_again; /* This should really be * "return ssl2_read(s,buf,len)", * but that would allow for * denial-of-service attacks if a * C compiler is used that does not * recognize end-recursion. */ } else { SSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_BAD_STATE); return(-1); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Add and use a constant-time memcmp. This change adds CRYPTO_memcmp, which compares two vectors of bytes in an amount of time that's independent of their contents. It also changes several MAC compares in the code to use this over the standard memcmp, which may leak information about the size of a matching prefix. (cherry picked from commit 2ee798880a246d648ecddadc5b91367bee4a5d98) Conflicts: crypto/crypto.h ssl/t1_lib.c (cherry picked from commit dc406b59f3169fe191e58906df08dce97edb727c) Conflicts: crypto/crypto.h ssl/d1_pkt.c ssl/s3_pkt.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int tls1_mac(SSL *ssl, unsigned char *md, int send) { SSL3_RECORD *rec; unsigned char *mac_sec,*seq; const EVP_MD *hash; unsigned int md_size; int i; EVP_MD_CTX hmac, *mac_ctx; unsigned char header[13]; int stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM)); int t; if (send) { rec= &(ssl->s3->wrec); mac_sec= &(ssl->s3->write_mac_secret[0]); seq= &(ssl->s3->write_sequence[0]); hash=ssl->write_hash; } else { rec= &(ssl->s3->rrec); mac_sec= &(ssl->s3->read_mac_secret[0]); seq= &(ssl->s3->read_sequence[0]); hash=ssl->read_hash; } md_size=EVP_MD_size(hash); /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */ HMAC_CTX_init(&hmac); HMAC_Init_ex(&hmac,mac_sec,EVP_MD_size(hash),hash,NULL); if (ssl->version == DTLS1_BAD_VER || (ssl->version == DTLS1_VERSION && ssl->client_version != DTLS1_BAD_VER)) { unsigned char dtlsseq[8],*p=dtlsseq; s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p); memcpy (p,&seq[2],6); memcpy(header, dtlsseq, 8); } else memcpy(header, seq, 8); header[8]=rec->type; header[9]=(unsigned char)(ssl->version>>8); header[10]=(unsigned char)(ssl->version); header[11]=(rec->length)>>8; header[12]=(rec->length)&0xff; if (!send && EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE && ssl3_cbc_record_digest_supported(mac_ctx)) { /* This is a CBC-encrypted record. We must avoid leaking any * timing-side channel information about how many blocks of * data we are hashing because that gives an attacker a * timing-oracle. */ ssl3_cbc_digest_record( mac_ctx, md, &md_size, header, rec->input, rec->length + md_size, rec->orig_len, ssl->s3->read_mac_secret, ssl->s3->read_mac_secret_size, 0 /* not SSLv3 */); } else { EVP_DigestSignUpdate(mac_ctx,header,sizeof(header)); EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length); t=EVP_DigestSignFinal(mac_ctx,md,&md_size); OPENSSL_assert(t > 0); } if (!stream_mac) EVP_MD_CTX_cleanup(&hmac); #ifdef TLS_DEBUG printf("sec="); {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",mac_sec[z]); printf("\n"); } printf("seq="); {int z; for (z=0; z<8; z++) printf("%02X ",seq[z]); printf("\n"); } printf("buf="); {int z; for (z=0; z<5; z++) printf("%02X ",buf[z]); printf("\n"); } printf("rec="); {unsigned int z; for (z=0; z<rec->length; z++) printf("%02X ",buf[z]); printf("\n"); } #endif if ( SSL_version(ssl) != DTLS1_VERSION && SSL_version(ssl) != DTLS1_BAD_VER) { for (i=7; i>=0; i--) { ++seq[i]; if (seq[i] != 0) break; } } #ifdef TLS_DEBUG {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",md[z]); printf("\n"); } #endif return(md_size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fixups.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int tls1_enc(SSL *s, int send) { SSL3_RECORD *rec; EVP_CIPHER_CTX *ds; unsigned long l; int bs,i,j,k,pad=0,ret,mac_size=0; const EVP_CIPHER *enc; if (send) { ds=s->enc_write_ctx; rec= &(s->s3->wrec); if (s->enc_write_ctx == NULL) enc=NULL; else enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx); } else { ds=s->enc_read_ctx; rec= &(s->s3->rrec); if (s->enc_read_ctx == NULL) enc=NULL; else enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx); } #ifdef KSSL_DEBUG printf("tls1_enc(%d)\n", send); #endif /* KSSL_DEBUG */ if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) { memmove(rec->data,rec->input,rec->length); rec->input=rec->data; ret = 1; } else { l=rec->length; bs=EVP_CIPHER_block_size(ds->cipher); if ((bs != 1) && send) { i=bs-((int)l%bs); /* Add weird padding of upto 256 bytes */ /* we need to add 'i' padding bytes of value j */ j=i-1; if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) { if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) j++; } for (k=(int)l; k<(int)(l+i); k++) rec->input[k]=j; l+=i; rec->length+=i; } #ifdef KSSL_DEBUG { unsigned long ui; printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n", ds,rec->data,rec->input,l); printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n", ds->buf_len, ds->cipher->key_len, DES_KEY_SZ, DES_SCHEDULE_SZ, ds->cipher->iv_len); printf("\t\tIV: "); for (i=0; i<ds->cipher->iv_len; i++) printf("%02X", ds->iv[i]); printf("\n"); printf("\trec->input="); for (ui=0; ui<l; ui++) printf(" %02x", rec->input[ui]); printf("\n"); } #endif /* KSSL_DEBUG */ if (!send) { if (l == 0 || l%bs != 0) { SSLerr(SSL_F_TLS1_ENC,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECRYPTION_FAILED); return 0; } } EVP_Cipher(ds,rec->data,rec->input,l); #ifdef KSSL_DEBUG { unsigned long ki; printf("\trec->data="); for (ki=0; ki<l; i++) printf(" %02x", rec->data[ki]); printf("\n"); } #endif /* KSSL_DEBUG */ rec->orig_len = rec->length; ret = 1; if (s->read_hash != NULL) mac_size = EVP_MD_size(s->read_hash); if ((bs != 1) && !send) ret = tls1_cbc_remove_padding(s, rec, bs, mac_size); if (pad && !send) rec->length -= pad; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Don't crash when processing a zero-length, TLS >= 1.1 record. The previous CBC patch was bugged in that there was a path through enc() in s3_pkt.c/d1_pkt.c which didn't set orig_len. orig_len would be left at the previous value which could suggest that the packet was a sufficient length when it wasn't. (cherry picked from commit 6cb19b7681f600b2f165e4adc57547b097b475fd) (cherry picked from commit 2c948c1bb218f4ae126e14fd3453d42c62b93235) Conflicts: ssl/s3_enc.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int tls1_mac(SSL *ssl, unsigned char *md, int send) { SSL3_RECORD *rec; unsigned char *mac_sec,*seq; const EVP_MD *hash; size_t md_size; int i; HMAC_CTX hmac; unsigned char header[13]; if (send) { rec= &(ssl->s3->wrec); mac_sec= &(ssl->s3->write_mac_secret[0]); seq= &(ssl->s3->write_sequence[0]); hash=ssl->write_hash; } else { rec= &(ssl->s3->rrec); mac_sec= &(ssl->s3->read_mac_secret[0]); seq= &(ssl->s3->read_sequence[0]); hash=ssl->read_hash; } md_size=EVP_MD_size(hash); /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */ HMAC_CTX_init(&hmac); HMAC_Init_ex(&hmac,mac_sec,EVP_MD_size(hash),hash,NULL); if (ssl->version == DTLS1_BAD_VER || (ssl->version == DTLS1_VERSION && ssl->client_version != DTLS1_BAD_VER)) { unsigned char dtlsseq[8],*p=dtlsseq; s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p); memcpy (p,&seq[2],6); memcpy(header, dtlsseq, 8); } else memcpy(header, seq, 8); header[8]=rec->type; header[9]=(unsigned char)(ssl->version>>8); header[10]=(unsigned char)(ssl->version); header[11]=(rec->length)>>8; header[12]=(rec->length)&0xff; if (!send && EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE && ssl3_cbc_record_digest_supported(hash)) { /* This is a CBC-encrypted record. We must avoid leaking any * timing-side channel information about how many blocks of * data we are hashing because that gives an attacker a * timing-oracle. */ ssl3_cbc_digest_record( hash, md, &md_size, header, rec->input, rec->length + md_size, rec->orig_len, ssl->s3->read_mac_secret, EVP_MD_size(ssl->read_hash), 0 /* not SSLv3 */); } else { unsigned mds; HMAC_Update(&hmac,header,sizeof(header)); HMAC_Update(&hmac,rec->input,rec->length); HMAC_Final(&hmac,md,&mds); md_size = mds; } HMAC_CTX_cleanup(&hmac); #ifdef TLS_DEBUG printf("sec="); {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",mac_sec[z]); printf("\n"); } printf("seq="); {int z; for (z=0; z<8; z++) printf("%02X ",seq[z]); printf("\n"); } printf("buf="); {int z; for (z=0; z<5; z++) printf("%02X ",buf[z]); printf("\n"); } printf("rec="); {unsigned int z; for (z=0; z<rec->length; z++) printf("%02X ",buf[z]); printf("\n"); } #endif if ( SSL_version(ssl) != DTLS1_VERSION && SSL_version(ssl) != DTLS1_BAD_VER) { for (i=7; i>=0; i--) { ++seq[i]; if (seq[i] != 0) break; } } #ifdef TLS_DEBUG {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",md[z]); printf("\n"); } #endif return(md_size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Timing fix mitigation for FIPS mode. We have to use EVP in FIPS mode so we can only partially mitigate timing differences. Make an extra call to HMAC_Update to hash additonal blocks to cover any timing differences caused by removal of padding.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ssl3_get_record(SSL *s) { int ssl_major,ssl_minor,al; int enc_err,n,i,ret= -1; SSL3_RECORD *rr; SSL_SESSION *sess; unsigned char *p; unsigned char md[EVP_MAX_MD_SIZE]; short version; int mac_size; int clear=0; size_t extra; int decryption_failed_or_bad_record_mac = 0; unsigned char *mac = NULL; rr= &(s->s3->rrec); sess=s->session; if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) extra=SSL3_RT_MAX_EXTRA; else extra=0; if (extra && !s->s3->init_extra) { /* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER * set after ssl3_setup_buffers() was done */ SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR); return -1; } again: /* check if we have the header */ if ( (s->rstate != SSL_ST_READ_BODY) || (s->packet_length < SSL3_RT_HEADER_LENGTH)) { n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); if (n <= 0) return(n); /* error or non-blocking */ s->rstate=SSL_ST_READ_BODY; p=s->packet; /* Pull apart the header into the SSL3_RECORD */ rr->type= *(p++); ssl_major= *(p++); ssl_minor= *(p++); version=(ssl_major<<8)|ssl_minor; n2s(p,rr->length); #if 0 fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length); #endif /* Lets check version */ if (!s->first_packet) { if (version != s->version) { SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER); if ((s->version & 0xFF00) == (version & 0xFF00)) /* Send back error using their minor version number :-) */ s->version = (unsigned short)version; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } } if ((version>>8) != SSL3_VERSION_MAJOR) { SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER); goto err; } if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG); goto f_err; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH) { /* now s->packet_length == SSL3_RT_HEADER_LENGTH */ i=rr->length; n=ssl3_read_n(s,i,i,1); if (n <= 0) return(n); /* error or non-blocking io */ /* now n == rr->length, * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */ } s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; enc_err = s->method->ssl3_enc->enc(s,0); if (enc_err <= 0) { if (enc_err == 0) /* SSLerr() and ssl3_send_alert() have been called */ goto err; /* Otherwise enc_err == -1, which indicates bad padding * (rec->length has not been changed in this case). * To minimize information leaked via timing, we will perform * the MAC computation anyway. */ decryption_failed_or_bad_record_mac = 1; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ( (sess == NULL) || (s->enc_read_ctx == NULL) || (EVP_MD_CTX_md(s->read_hash) == NULL)) clear=1; if (!clear) { /* !clear => s->read_hash != NULL => mac_size != -1 */ mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size >= 0); if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size) { #if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */ al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG); goto f_err; #else decryption_failed_or_bad_record_mac = 1; #endif } /* check the MAC for rr->input (it's in mac_size bytes at the tail) */ if (rr->length >= (unsigned int)mac_size) { rr->length -= mac_size; mac = &rr->data[rr->length]; } else { /* record (minus padding) is too short to contain a MAC */ #if 0 /* OK only for stream ciphers */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; #else decryption_failed_or_bad_record_mac = 1; rr->length = 0; #endif } i=s->method->ssl3_enc->mac(s,md,0); if (i < 0 || mac == NULL || memcmp(md, mac, (size_t)mac_size) != 0) { decryption_failed_or_bad_record_mac = 1; } } if (decryption_failed_or_bad_record_mac) { /* A separate 'decryption_failed' alert was introduced with TLS 1.0, * SSL 3.0 only has 'bad_record_mac'. But unless a decryption * failure is directly visible from the ciphertext anyway, * we should not reveal which kind of error occured -- this * might become visible to an attacker (e.g. via a logfile) */ al=SSL_AD_BAD_RECORD_MAC; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto f_err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /* So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; /* just read a 0 length packet */ if (rr->length == 0) goto again; #if 0 fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length); #endif return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Add and use a constant-time memcmp. This change adds CRYPTO_memcmp, which compares two vectors of bytes in an amount of time that's independent of their contents. It also changes several MAC compares in the code to use this over the standard memcmp, which may leak information about the size of a matching prefix. (cherry picked from commit 2ee798880a246d648ecddadc5b91367bee4a5d98) Conflicts: crypto/crypto.h ssl/t1_lib.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void OpenSSL_add_all_ciphers(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cfb()); EVP_add_cipher(EVP_des_cfb1()); EVP_add_cipher(EVP_des_cfb8()); EVP_add_cipher(EVP_des_ede_cfb()); EVP_add_cipher(EVP_des_ede3_cfb()); EVP_add_cipher(EVP_des_ede3_cfb1()); EVP_add_cipher(EVP_des_ede3_cfb8()); EVP_add_cipher(EVP_des_ofb()); EVP_add_cipher(EVP_des_ede_ofb()); EVP_add_cipher(EVP_des_ede3_ofb()); EVP_add_cipher(EVP_desx_cbc()); EVP_add_cipher_alias(SN_desx_cbc,"DESX"); EVP_add_cipher_alias(SN_desx_cbc,"desx"); EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher_alias(SN_des_cbc,"DES"); EVP_add_cipher_alias(SN_des_cbc,"des"); EVP_add_cipher(EVP_des_ede_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); EVP_add_cipher_alias(SN_des_ede3_cbc,"DES3"); EVP_add_cipher_alias(SN_des_ede3_cbc,"des3"); EVP_add_cipher(EVP_des_ecb()); EVP_add_cipher(EVP_des_ede()); EVP_add_cipher(EVP_des_ede3()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); EVP_add_cipher(EVP_rc4_40()); #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_ecb()); EVP_add_cipher(EVP_idea_cfb()); EVP_add_cipher(EVP_idea_ofb()); EVP_add_cipher(EVP_idea_cbc()); EVP_add_cipher_alias(SN_idea_cbc,"IDEA"); EVP_add_cipher_alias(SN_idea_cbc,"idea"); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_ecb()); EVP_add_cipher(EVP_seed_cfb()); EVP_add_cipher(EVP_seed_ofb()); EVP_add_cipher(EVP_seed_cbc()); EVP_add_cipher_alias(SN_seed_cbc,"SEED"); EVP_add_cipher_alias(SN_seed_cbc,"seed"); #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_ecb()); EVP_add_cipher(EVP_rc2_cfb()); EVP_add_cipher(EVP_rc2_ofb()); EVP_add_cipher(EVP_rc2_cbc()); EVP_add_cipher(EVP_rc2_40_cbc()); EVP_add_cipher(EVP_rc2_64_cbc()); EVP_add_cipher_alias(SN_rc2_cbc,"RC2"); EVP_add_cipher_alias(SN_rc2_cbc,"rc2"); #endif #ifndef OPENSSL_NO_BF EVP_add_cipher(EVP_bf_ecb()); EVP_add_cipher(EVP_bf_cfb()); EVP_add_cipher(EVP_bf_ofb()); EVP_add_cipher(EVP_bf_cbc()); EVP_add_cipher_alias(SN_bf_cbc,"BF"); EVP_add_cipher_alias(SN_bf_cbc,"bf"); EVP_add_cipher_alias(SN_bf_cbc,"blowfish"); #endif #ifndef OPENSSL_NO_CAST EVP_add_cipher(EVP_cast5_ecb()); EVP_add_cipher(EVP_cast5_cfb()); EVP_add_cipher(EVP_cast5_ofb()); EVP_add_cipher(EVP_cast5_cbc()); EVP_add_cipher_alias(SN_cast5_cbc,"CAST"); EVP_add_cipher_alias(SN_cast5_cbc,"cast"); EVP_add_cipher_alias(SN_cast5_cbc,"CAST-cbc"); EVP_add_cipher_alias(SN_cast5_cbc,"cast-cbc"); #endif #ifndef OPENSSL_NO_RC5 EVP_add_cipher(EVP_rc5_32_12_16_ecb()); EVP_add_cipher(EVP_rc5_32_12_16_cfb()); EVP_add_cipher(EVP_rc5_32_12_16_ofb()); EVP_add_cipher(EVP_rc5_32_12_16_cbc()); EVP_add_cipher_alias(SN_rc5_cbc,"rc5"); EVP_add_cipher_alias(SN_rc5_cbc,"RC5"); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_ecb()); EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_128_cfb()); EVP_add_cipher(EVP_aes_128_cfb1()); EVP_add_cipher(EVP_aes_128_cfb8()); EVP_add_cipher(EVP_aes_128_ofb()); #if 0 EVP_add_cipher(EVP_aes_128_ctr()); #endif EVP_add_cipher_alias(SN_aes_128_cbc,"AES128"); EVP_add_cipher_alias(SN_aes_128_cbc,"aes128"); EVP_add_cipher(EVP_aes_192_ecb()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_192_cfb()); EVP_add_cipher(EVP_aes_192_cfb1()); EVP_add_cipher(EVP_aes_192_cfb8()); EVP_add_cipher(EVP_aes_192_ofb()); #if 0 EVP_add_cipher(EVP_aes_192_ctr()); #endif EVP_add_cipher_alias(SN_aes_192_cbc,"AES192"); EVP_add_cipher_alias(SN_aes_192_cbc,"aes192"); EVP_add_cipher(EVP_aes_256_ecb()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_256_cfb()); EVP_add_cipher(EVP_aes_256_cfb1()); EVP_add_cipher(EVP_aes_256_cfb8()); EVP_add_cipher(EVP_aes_256_ofb()); #if 0 EVP_add_cipher(EVP_aes_256_ctr()); #endif EVP_add_cipher_alias(SN_aes_256_cbc,"AES256"); EVP_add_cipher_alias(SN_aes_256_cbc,"aes256"); #endif #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_128_cfb()); EVP_add_cipher(EVP_camellia_128_cfb1()); EVP_add_cipher(EVP_camellia_128_cfb8()); EVP_add_cipher(EVP_camellia_128_ofb()); EVP_add_cipher_alias(SN_camellia_128_cbc,"CAMELLIA128"); EVP_add_cipher_alias(SN_camellia_128_cbc,"camellia128"); EVP_add_cipher(EVP_camellia_192_ecb()); EVP_add_cipher(EVP_camellia_192_cbc()); EVP_add_cipher(EVP_camellia_192_cfb()); EVP_add_cipher(EVP_camellia_192_cfb1()); EVP_add_cipher(EVP_camellia_192_cfb8()); EVP_add_cipher(EVP_camellia_192_ofb()); EVP_add_cipher_alias(SN_camellia_192_cbc,"CAMELLIA192"); EVP_add_cipher_alias(SN_camellia_192_cbc,"camellia192"); EVP_add_cipher(EVP_camellia_256_ecb()); EVP_add_cipher(EVP_camellia_256_cbc()); EVP_add_cipher(EVP_camellia_256_cfb()); EVP_add_cipher(EVP_camellia_256_cfb1()); EVP_add_cipher(EVP_camellia_256_cfb8()); EVP_add_cipher(EVP_camellia_256_ofb()); EVP_add_cipher_alias(SN_camellia_256_cbc,"CAMELLIA256"); EVP_add_cipher_alias(SN_camellia_256_cbc,"camellia256"); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fixups from previous commit.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ssl3_get_record(SSL *s) { int ssl_major,ssl_minor,al; int enc_err,n,i,ret= -1; SSL3_RECORD *rr; SSL_SESSION *sess; unsigned char *p; unsigned char md[EVP_MAX_MD_SIZE]; short version; unsigned mac_size; int clear=0; size_t extra; rr= &(s->s3->rrec); sess=s->session; if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) extra=SSL3_RT_MAX_EXTRA; else extra=0; if (extra && !s->s3->init_extra) { /* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER * set after ssl3_setup_buffers() was done */ SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR); return -1; } again: /* check if we have the header */ if ( (s->rstate != SSL_ST_READ_BODY) || (s->packet_length < SSL3_RT_HEADER_LENGTH)) { n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); if (n <= 0) return(n); /* error or non-blocking */ s->rstate=SSL_ST_READ_BODY; p=s->packet; /* Pull apart the header into the SSL3_RECORD */ rr->type= *(p++); ssl_major= *(p++); ssl_minor= *(p++); version=(ssl_major<<8)|ssl_minor; n2s(p,rr->length); #if 0 fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length); #endif /* Lets check version */ if (!s->first_packet) { if (version != s->version) { SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER); if ((s->version & 0xFF00) == (version & 0xFF00)) /* Send back error using their minor version number :-) */ s->version = (unsigned short)version; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } } if ((version>>8) != SSL3_VERSION_MAJOR) { SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER); goto err; } if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG); goto f_err; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH) { /* now s->packet_length == SSL3_RT_HEADER_LENGTH */ i=rr->length; n=ssl3_read_n(s,i,i,1); if (n <= 0) return(n); /* error or non-blocking io */ /* now n == rr->length, * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */ } s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* SSLerr() and ssl3_send_alert() have been called */ goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ( (sess == NULL) || (s->enc_read_ctx == NULL) || (EVP_MD_CTX_md(s->read_hash) == NULL)) clear=1; if (!clear) { /* !clear => s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size) enc_err = -1; } if (enc_err < 0) { /* A separate 'decryption_failed' alert was introduced with TLS 1.0, * SSL 3.0 only has 'bad_record_mac'. But unless a decryption * failure is directly visible from the ciphertext anyway, * we should not reveal which kind of error occured -- this * might become visible to an attacker (e.g. via a logfile) */ al=SSL_AD_BAD_RECORD_MAC; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto f_err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /* So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; /* just read a 0 length packet */ if (rr->length == 0) goto again; #if 0 fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length); #endif return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Update DTLS code to match CBC decoding in TLS. This change updates the DTLS code to match the constant-time CBC behaviour in the TLS. (cherry picked from commit 9f27de170d1b7bef3d46d41382dc4dafde8b3900)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ssl3_cbc_copy_mac(unsigned char* out, const SSL3_RECORD *rec, unsigned md_size,unsigned orig_len) { #if defined(CBC_MAC_ROTATE_IN_PLACE) unsigned char rotated_mac_buf[EVP_MAX_MD_SIZE*2]; unsigned char *rotated_mac; #else unsigned char rotated_mac[EVP_MAX_MD_SIZE]; #endif /* mac_end is the index of |rec->data| just after the end of the MAC. */ unsigned mac_end = rec->length; unsigned mac_start = mac_end - md_size; /* scan_start contains the number of bytes that we can ignore because * the MAC's position can only vary by 255 bytes. */ unsigned scan_start = 0; unsigned i, j; unsigned div_spoiler; unsigned rotate_offset; OPENSSL_assert(orig_len >= md_size); OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE); #if defined(CBC_MAC_ROTATE_IN_PLACE) rotated_mac = (unsigned char*) (((intptr_t)(rotated_mac_buf + 64)) & ~63); #endif /* This information is public so it's safe to branch based on it. */ if (orig_len > md_size + 255 + 1) scan_start = orig_len - (md_size + 255 + 1); /* div_spoiler contains a multiple of md_size that is used to cause the * modulo operation to be constant time. Without this, the time varies * based on the amount of padding when running on Intel chips at least. * * The aim of right-shifting md_size is so that the compiler doesn't * figure out that it can remove div_spoiler as that would require it * to prove that md_size is always even, which I hope is beyond it. */ div_spoiler = md_size >> 1; div_spoiler <<= (sizeof(div_spoiler)-1)*8; rotate_offset = (div_spoiler + mac_start - scan_start) % md_size; memset(rotated_mac, 0, md_size); for (i = scan_start, j = 0; i < orig_len; i++) { unsigned char mac_started = constant_time_ge(i, mac_start); unsigned char mac_ended = constant_time_ge(i, mac_end); unsigned char b = rec->data[i]; rotated_mac[j++] |= b & mac_started & ~mac_ended; j &= constant_time_lt(j,md_size); } /* Now rotate the MAC */ #if defined(CBC_MAC_ROTATE_IN_PLACE) j = 0; for (i = 0; i < md_size; i++) { out[j++] = rotated_mac[rotate_offset++]; rotate_offset &= constant_time_lt(rotate_offset,md_size); } #else memset(out, 0, md_size); rotate_offset = md_size - rotate_offset; rotate_offset &= constant_time_lt(rotate_offset,md_size); for (i = 0; i < md_size; i++) { for (j = 0; j < md_size; j++) out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset); rotate_offset++; rotate_offset &= constant_time_lt(rotate_offset,md_size); } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 's3_cbc.c: make CBC_MAC_ROTATE_IN_PLACE universal. (cherry picked from commit f93a41877d8d7a287debb7c63d7b646abaaf269c)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rsvg_acquire_data_data (const char *uri, const char *base_uri, char **out_mime_type, gsize *out_len, GError **error) { const char *comma, *start, *end; char *mime_type; char *data; gsize data_len; gboolean base64 = FALSE; g_assert (out_len != NULL); g_assert (g_str_has_prefix (uri, "data:")); mime_type = NULL; start = uri + 5; comma = strchr (start, ','); if (comma && comma != start) { /* Deal with MIME type / params */ if (comma > start + BASE64_INDICATOR_LEN && !g_ascii_strncasecmp (comma - BASE64_INDICATOR_LEN, BASE64_INDICATOR, BASE64_INDICATOR_LEN)) { end = comma - BASE64_INDICATOR_LEN; base64 = TRUE; } else { end = comma; } if (end != start) { mime_type = uri_decoded_copy (start, end - start); } } if (comma) start = comma + 1; if (*start) { data = uri_decoded_copy (start, strlen (start)); if (base64) data = g_base64_decode_inplace ((char*) data, &data_len); else data_len = strlen ((const char *) data); } else { data = NULL; data_len = 0; } if (out_mime_type) *out_mime_type = mime_type; else g_free (mime_type); *out_len = data_len; return data; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'io: Implement strict load policy Allow any file to load from data:, and any resource to load from other resources. Only allow file: to load other file: URIs from below the path of the base file. Any other loads are denied. Bug #691708.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) { int al,i,j,ret; unsigned int n; SSL3_RECORD *rr; void (*cb)(const SSL *ssl,int type2,int val)=NULL; if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ if (!ssl3_setup_read_buffer(s)) return(-1); if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0)) /* (partially) satisfy request from storage */ { unsigned char *src = s->s3->handshake_fragment; unsigned char *dst = buf; unsigned int k; /* peek == 0 */ n = 0; while ((len > 0) && (s->s3->handshake_fragment_len > 0)) { *dst++ = *src++; len--; s->s3->handshake_fragment_len--; n++; } /* move any remaining fragment bytes: */ for (k = 0; k < s->s3->handshake_fragment_len; k++) s->s3->handshake_fragment[k] = *src++; return n; } /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ if (!s->in_handshake && SSL_in_init(s)) { /* type == SSL3_RT_APPLICATION_DATA */ i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } } start: s->rwstate=SSL_NOTHING; /* s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = &(s->s3->rrec); /* get new packet if necessary */ if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) { ret=ssl3_get_record(s); if (ret <= 0) return(ret); } /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (rr->type != SSL3_RT_HANDSHAKE)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED); goto f_err; } /* If the other end has shut down, throw anything we read away * (even in 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { rr->length=0; s->rwstate=SSL_NOTHING; return(0); } if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */ { /* make sure that we are not getting application data when we * are doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (len <= 0) return(len); if ((unsigned int)len > rr->length) n = rr->length; else n = (unsigned int)len; memcpy(buf,&(rr->data[rr->off]),n); if (!peek) { rr->length-=n; rr->off+=n; if (rr->length == 0) { s->rstate=SSL_ST_READ_HEADER; rr->off=0; if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0) ssl3_release_read_buffer(s); } } return(n); } /* If we get here, then type != rr->type; if we have a handshake * message, then it was unexpected (Hello Request or Client Hello). */ /* In case of record types for which we have 'fragment' storage, * fill that so that we can process the data at a fixed place. */ { unsigned int dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (rr->type == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof s->s3->handshake_fragment; dest = s->s3->handshake_fragment; dest_len = &s->s3->handshake_fragment_len; } else if (rr->type == SSL3_RT_ALERT) { dest_maxlen = sizeof s->s3->alert_fragment; dest = s->s3->alert_fragment; dest_len = &s->s3->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (rr->type == TLS1_RT_HEARTBEAT) { tls1_process_heartbeat(s); /* Exit and notify application to read again */ rr->length = 0; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return(-1); } #endif if (dest_maxlen > 0) { n = dest_maxlen - *dest_len; /* available space in 'dest' */ if (rr->length < n) n = rr->length; /* available bytes */ /* now move 'n' bytes: */ while (n-- > 0) { dest[(*dest_len)++] = rr->data[rr->off++]; rr->length--; } if (*dest_len < dest_maxlen) goto start; /* fragment was too small */ } } /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE; * s->s3->alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->s3->handshake_fragment_len >= 4) && (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->s3->handshake_fragment_len = 0; if ((s->s3->handshake_fragment[1] != 0) || (s->s3->handshake_fragment[2] != 0) || (s->s3->handshake_fragment[3] != 0)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST); goto f_err; } if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) /* no read-ahead left? */ { BIO *bio; /* In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate=SSL_READING; bio=SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } } } } /* we either finished a handshake or ignored the request, * now try again to obtain the (application) data we were asked for */ goto start; } /* If we are a server and get a client hello when renegotiation isn't * allowed send back a no renegotiation alert and carry on. * WARNING: experimental code, needs reviewing (steve) */ if (s->server && SSL_is_init_finished(s) && !s->s3->send_connection_binding && (s->version > SSL3_VERSION) && (s->s3->handshake_fragment_len >= 4) && (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) && (s->session != NULL) && (s->session->cipher != NULL) && !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { /*s->s3->handshake_fragment_len = 0;*/ rr->length = 0; ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); goto start; } if (s->s3->alert_fragment_len >= 2) { int alert_level = s->s3->alert_fragment[0]; int alert_descr = s->s3->alert_fragment[1]; s->s3->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == 1) /* warning */ { s->s3->warn_alert = alert_descr; if (alert_descr == SSL_AD_CLOSE_NOTIFY) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return(0); } /* This is a warning but we receive it if we requested * renegotiation and the peer denied it. Terminate with * a fatal alert because if application tried to * renegotiatie it presumably had a good reason and * expects it to succeed. * * In future we might have a renegotiation where we * don't care if the peer refused it where we carry on. */ else if (alert_descr == SSL_AD_NO_RENEGOTIATION) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION); goto f_err; } #ifdef SSL_AD_MISSING_SRP_USERNAME else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME) return(0); #endif } else if (alert_level == 2) /* fatal */ { char tmp[16]; s->rwstate=SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr); ERR_add_error_data(2,"SSL alert number ",tmp); s->shutdown|=SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->ctx,s->session); return(0); } else { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE); goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */ { s->rwstate=SSL_NOTHING; rr->length=0; return(0); } if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { /* 'Change Cipher Spec' is just a single byte, so we know * exactly what the record payload has to look like */ if ( (rr->length != 1) || (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC); goto f_err; } /* Check we have a cipher to change to */ if (s->s3->tmp.new_cipher == NULL) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY); goto f_err; } rr->length=0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); s->s3->change_cipher_spec=1; if (!ssl3_do_change_cipher_spec(s)) goto err; else goto start; } /* Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) { if (((s->state&SSL_ST_MASK) == SSL_ST_OK) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { #if 0 /* worked only because C operator preferences are not as expected (and * because this is not really needed for clients except for detecting * protocol violations): */ s->state=SSL_ST_BEFORE|(s->server) ?SSL_ST_ACCEPT :SSL_ST_CONNECT; #else s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #endif s->renegotiate=1; s->new_session=1; } i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) /* no read-ahead left? */ { BIO *bio; /* In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate=SSL_READING; bio=SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } } goto start; } switch (rr->type) { default: #ifndef OPENSSL_NO_TLS /* TLS up to v1.1 just ignores unknown message types: * TLS v1.2 give an unexpected message alert. */ if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) { rr->length = 0; goto start; } #endif al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* we already handled all of these, with the possible exception * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that * should not happen when type != rr->type */ al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES,ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* At this point, we were expecting handshake data, * but have application data. If the library was * running inside ssl3_read() (i.e. in_read_app_data * is set) and it makes sense to read application data * at this point (session renegotiation not yet started), * we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && (( (s->state & SSL_ST_CONNECT) && (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && (s->state <= SSL3_ST_CR_SRVR_HELLO_A) ) || ( (s->state & SSL_ST_ACCEPT) && (s->state <= SSL3_ST_SW_HELLO_REQ_A) && (s->state >= SSL3_ST_SR_CLNT_HELLO_A) ) )) { s->s3->in_read_app_data=2; return(-1); } else { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-326', 'CWE-310'], 'message': 'Fix for CVE-2014-0224 Only accept change cipher spec when it is expected instead of at any time. This prevents premature setting of session keys before the master secret is determined which an attacker could use as a MITM attack. Thanks to KIKUCHI Masashi (Lepidum Co. Ltd.) for reporting this issue and providing the initial fix this patch is based on.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long ssl2_ctrl(SSL *s, int cmd, long larg, void *parg) { int ret=0; switch(cmd) { case SSL_CTRL_GET_SESSION_REUSED: ret=s->hit; break; default: break; } return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV. Reviewed-by: Stephen Henson <steve@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,unsigned char *p,int num, STACK_OF(SSL_CIPHER) **skp) { const SSL_CIPHER *c; STACK_OF(SSL_CIPHER) *sk; int i,n; if (s->s3) s->s3->send_connection_binding = 0; n=ssl_put_cipher_by_char(s,NULL,NULL); if ((num%n) != 0) { SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST); return(NULL); } if ((skp == NULL) || (*skp == NULL)) sk=sk_SSL_CIPHER_new_null(); /* change perhaps later */ else { sk= *skp; sk_SSL_CIPHER_zero(sk); } for (i=0; i<num; i+=n) { /* Check for SCSV */ if (s->s3 && (n != 3 || !p[0]) && (p[n-2] == ((SSL3_CK_SCSV >> 8) & 0xff)) && (p[n-1] == (SSL3_CK_SCSV & 0xff))) { /* SCSV fatal if renegotiating */ if (s->renegotiate) { SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); goto err; } s->s3->send_connection_binding = 1; p += n; #ifdef OPENSSL_RI_DEBUG fprintf(stderr, "SCSV received by server\n"); #endif continue; } c=ssl_get_cipher_by_char(s,p); p+=n; if (c != NULL) { if (!sk_SSL_CIPHER_push(sk,c)) { SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,ERR_R_MALLOC_FAILURE); goto err; } } } if (skp != NULL) *skp=sk; return(sk); err: if ((skp == NULL) || (*skp == NULL)) sk_SSL_CIPHER_free(sk); return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV. Reviewed-by: Rich Salz <rsalz@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit) { int extdatalen=0; unsigned char *orig = buf; unsigned char *ret = buf; /* don't add extensions for SSLv3 unless doing secure renegotiation */ if (s->client_version == SSL3_VERSION && !s->s3->send_connection_binding) return orig; ret+=2; if (ret>=limit) return NULL; /* this really never occurs, but ... */ if (s->tlsext_hostname != NULL) { /* Add TLS extension servername to the Client Hello message */ unsigned long size_str; long lenmax; /* check for enough space. 4 for the servername type and entension length 2 for servernamelist length 1 for the hostname type 2 for hostname length + hostname length */ if ((lenmax = limit - ret - 9) < 0 || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) return NULL; /* extension type and length */ s2n(TLSEXT_TYPE_server_name,ret); s2n(size_str+5,ret); /* length of servername list */ s2n(size_str+3,ret); /* hostname type, length and hostname */ *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name; s2n(size_str,ret); memcpy(ret, s->tlsext_hostname, size_str); ret+=size_str; } /* Add RI if renegotiating */ if (s->renegotiate) { int el; if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } if((limit - ret - 4 - el) < 0) return NULL; s2n(TLSEXT_TYPE_renegotiate,ret); s2n(el,ret); if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } ret += el; } #ifndef OPENSSL_NO_SRP /* Add SRP username if there is one */ if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the Client Hello message */ int login_len = strlen(s->srp_ctx.login); if (login_len > 255 || login_len == 0) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /* check for enough space. 4 for the srp type type and entension length 1 for the srp user identity + srp user identity length */ if ((limit - ret - 5 - login_len) < 0) return NULL; /* fill in the extension */ s2n(TLSEXT_TYPE_srp,ret); s2n(login_len+1,ret); (*ret++) = (unsigned char) login_len; memcpy(ret, s->srp_ctx.login, login_len); ret+=login_len; } #endif #ifndef OPENSSL_NO_EC if (s->tlsext_ecpointformatlist != NULL) { /* Add TLS extension ECPointFormats to the ClientHello message */ long lenmax; if ((lenmax = limit - ret - 5) < 0) return NULL; if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL; if (s->tlsext_ecpointformatlist_length > 255) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } s2n(TLSEXT_TYPE_ec_point_formats,ret); s2n(s->tlsext_ecpointformatlist_length + 1,ret); *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length; memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length); ret+=s->tlsext_ecpointformatlist_length; } if (s->tlsext_ellipticcurvelist != NULL) { /* Add TLS extension EllipticCurves to the ClientHello message */ long lenmax; if ((lenmax = limit - ret - 6) < 0) return NULL; if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL; if (s->tlsext_ellipticcurvelist_length > 65532) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } s2n(TLSEXT_TYPE_elliptic_curves,ret); s2n(s->tlsext_ellipticcurvelist_length + 2, ret); /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for * elliptic_curve_list, but the examples use two bytes. * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html * resolves this to two bytes. */ s2n(s->tlsext_ellipticcurvelist_length, ret); memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length); ret+=s->tlsext_ellipticcurvelist_length; } #endif /* OPENSSL_NO_EC */ if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) { int ticklen; if (!s->new_session && s->session && s->session->tlsext_tick) ticklen = s->session->tlsext_ticklen; else if (s->session && s->tlsext_session_ticket && s->tlsext_session_ticket->data) { ticklen = s->tlsext_session_ticket->length; s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (!s->session->tlsext_tick) return NULL; memcpy(s->session->tlsext_tick, s->tlsext_session_ticket->data, ticklen); s->session->tlsext_ticklen = ticklen; } else ticklen = 0; if (ticklen == 0 && s->tlsext_session_ticket && s->tlsext_session_ticket->data == NULL) goto skip_ext; /* Check for enough room 2 for extension type, 2 for len * rest for ticket */ if ((long)(limit - ret - 4 - ticklen) < 0) return NULL; s2n(TLSEXT_TYPE_session_ticket,ret); s2n(ticklen,ret); if (ticklen) { memcpy(ret, s->session->tlsext_tick, ticklen); ret += ticklen; } } skip_ext: if (TLS1_get_client_version(s) >= TLS1_2_VERSION) { if ((size_t)(limit - ret) < sizeof(tls12_sigalgs) + 6) return NULL; s2n(TLSEXT_TYPE_signature_algorithms,ret); s2n(sizeof(tls12_sigalgs) + 2, ret); s2n(sizeof(tls12_sigalgs), ret); memcpy(ret, tls12_sigalgs, sizeof(tls12_sigalgs)); ret += sizeof(tls12_sigalgs); } #ifdef TLSEXT_TYPE_opaque_prf_input if (s->s3->client_opaque_prf_input != NULL && s->version != DTLS1_VERSION) { size_t col = s->s3->client_opaque_prf_input_len; if ((long)(limit - ret - 6 - col < 0)) return NULL; if (col > 0xFFFD) /* can't happen */ return NULL; s2n(TLSEXT_TYPE_opaque_prf_input, ret); s2n(col + 2, ret); s2n(col, ret); memcpy(ret, s->s3->client_opaque_prf_input, col); ret += col; } #endif if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp && s->version != DTLS1_VERSION) { int i; long extlen, idlen, itmp; OCSP_RESPID *id; idlen = 0; for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); itmp = i2d_OCSP_RESPID(id, NULL); if (itmp <= 0) return NULL; idlen += itmp + 2; } if (s->tlsext_ocsp_exts) { extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL); if (extlen < 0) return NULL; } else extlen = 0; if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL; s2n(TLSEXT_TYPE_status_request, ret); if (extlen + idlen > 0xFFF0) return NULL; s2n(extlen + idlen + 5, ret); *(ret++) = TLSEXT_STATUSTYPE_ocsp; s2n(idlen, ret); for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { /* save position of id len */ unsigned char *q = ret; id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); /* skip over id len */ ret += 2; itmp = i2d_OCSP_RESPID(id, &ret); /* write id len */ s2n(itmp, q); } s2n(extlen, ret); if (extlen > 0) i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret); } #ifndef OPENSSL_NO_HEARTBEATS /* Add Heartbeat extension */ if ((limit - ret - 4 - 1) < 0) return NULL; s2n(TLSEXT_TYPE_heartbeat,ret); s2n(1,ret); /* Set mode: * 1: peer may send requests * 2: peer not allowed to send requests */ if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS) *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS; else *(ret++) = SSL_TLSEXT_HB_ENABLED; #endif #ifndef OPENSSL_NO_NEXTPROTONEG if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) { /* The client advertises an emtpy extension to indicate its * support for Next Protocol Negotiation */ if (limit - ret - 4 < 0) return NULL; s2n(TLSEXT_TYPE_next_proto_neg,ret); s2n(0,ret); } #endif #ifndef OPENSSL_NO_SRTP if(SSL_get_srtp_profiles(s)) { int el; ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0); if((limit - ret - 4 - el) < 0) return NULL; s2n(TLSEXT_TYPE_use_srtp,ret); s2n(el,ret); if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } ret += el; } #endif /* Add padding to workaround bugs in F5 terminators. * See https://tools.ietf.org/html/draft-agl-tls-padding-03 * * NB: because this code works out the length of all existing * extensions it MUST always appear last. */ if (s->options & SSL_OP_TLSEXT_PADDING) { int hlen = ret - (unsigned char *)s->init_buf->data; /* The code in s23_clnt.c to build ClientHello messages * includes the 5-byte record header in the buffer, while * the code in s3_clnt.c does not. */ if (s->state == SSL23_ST_CW_CLNT_HELLO_A) hlen -= 5; if (hlen > 0xff && hlen < 0x200) { hlen = 0x200 - hlen; if (hlen >= 4) hlen -= 4; else hlen = 0; s2n(TLSEXT_TYPE_padding, ret); s2n(hlen, ret); memset(ret, 0, hlen); ret += hlen; } } if ((extdatalen = ret-orig-2)== 0) return orig; s2n(extdatalen, orig); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix for SRTP Memory Leak CVE-2014-3513 This issue was reported to OpenSSL on 26th September 2014, based on an origi issue and patch developed by the LibreSSL project. Further analysis of the i was performed by the OpenSSL team. The fix was developed by the OpenSSL team. Reviewed-by: Tim Hudson <tjh@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ssl23_get_server_hello(SSL *s) { char buf[8]; unsigned char *p; int i; int n; n=ssl23_read_bytes(s,7); if (n != 7) return(n); p=s->packet; memcpy(buf,p,n); if ((p[0] & 0x80) && (p[2] == SSL2_MT_SERVER_HELLO) && (p[5] == 0x00) && (p[6] == 0x02)) { #ifdef OPENSSL_NO_SSL2 SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; #else /* we are talking sslv2 */ /* we need to clean up the SSLv3 setup and put in the * sslv2 stuff. */ int ch_len; if (s->options & SSL_OP_NO_SSLv2) { SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; } if (s->s2 == NULL) { if (!ssl2_new(s)) goto err; } else ssl2_clear(s); if (s->options & SSL_OP_NETSCAPE_CHALLENGE_BUG) ch_len=SSL2_CHALLENGE_LENGTH; else ch_len=SSL2_MAX_CHALLENGE_LENGTH; /* write out sslv2 challenge */ /* Note that ch_len must be <= SSL3_RANDOM_SIZE (32), because it is one of SSL2_MAX_CHALLENGE_LENGTH (32) or SSL2_MAX_CHALLENGE_LENGTH (16), but leave the check in for futurproofing */ i=(SSL3_RANDOM_SIZE < ch_len) ?SSL3_RANDOM_SIZE:ch_len; s->s2->challenge_length=i; memcpy(s->s2->challenge, &(s->s3->client_random[SSL3_RANDOM_SIZE-i]),i); if (s->s3 != NULL) ssl3_free(s); if (!BUF_MEM_grow_clean(s->init_buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,ERR_R_BUF_LIB); goto err; } s->state=SSL2_ST_GET_SERVER_HELLO_A; if (!(s->client_version == SSL2_VERSION)) /* use special padding (SSL 3.0 draft/RFC 2246, App. E.2) */ s->s2->ssl2_rollback=1; /* setup the 7 bytes we have read so we get them from * the sslv2 buffer */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s2->rbuf[0]); memcpy(s->packet,buf,n); s->s2->rbuf_left=n; s->s2->rbuf_offs=0; /* we have already written one */ s->s2->write_sequence=1; s->method=SSLv2_client_method(); s->handshake_func=s->method->ssl_connect; #endif } else if (p[1] == SSL3_VERSION_MAJOR && p[2] <= TLS1_2_VERSION_MINOR && ((p[0] == SSL3_RT_HANDSHAKE && p[5] == SSL3_MT_SERVER_HELLO) || (p[0] == SSL3_RT_ALERT && p[3] == 0 && p[4] == 2))) { /* we have sslv3 or tls1 (server hello or alert) */ if ((p[2] == SSL3_VERSION_MINOR) && !(s->options & SSL_OP_NO_SSLv3)) { #ifdef OPENSSL_FIPS if(FIPS_mode()) { SSLerr(SSL_F_SSL23_GET_SERVER_HELLO, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); goto err; } #endif s->version=SSL3_VERSION; s->method=SSLv3_client_method(); } else if ((p[2] == TLS1_VERSION_MINOR) && !(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; s->method=TLSv1_client_method(); } else if ((p[2] == TLS1_1_VERSION_MINOR) && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; s->method=TLSv1_1_client_method(); } else if ((p[2] == TLS1_2_VERSION_MINOR) && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; s->method=TLSv1_2_client_method(); } else { SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; } /* ensure that TLS_MAX_VERSION is up-to-date */ OPENSSL_assert(s->version <= TLS_MAX_VERSION); if (p[0] == SSL3_RT_ALERT && p[5] != SSL3_AL_WARNING) { /* fatal alert */ void (*cb)(const SSL *ssl,int type,int val)=NULL; int j; if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; i=p[5]; if (cb != NULL) { j=(i<<8)|p[6]; cb(s,SSL_CB_READ_ALERT,j); } if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, p+5, 2, s, s->msg_callback_arg); s->rwstate=SSL_NOTHING; SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_AD_REASON_OFFSET+p[6]); goto err; } if (!ssl_init_wbio_buffer(s,1)) goto err; /* we are in this state */ s->state=SSL3_ST_CR_SRVR_HELLO_A; /* put the 7 bytes we have read into the input buffer * for SSLv3 */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; if (s->s3->rbuf.buf == NULL) if (!ssl3_setup_read_buffer(s)) goto err; s->packet= &(s->s3->rbuf.buf[0]); memcpy(s->packet,buf,n); s->s3->rbuf.left=n; s->s3->rbuf.offset=0; s->handshake_func=s->method->ssl_connect; } else { SSLerr(SSL_F_SSL23_GET_SERVER_HELLO,SSL_R_UNKNOWN_PROTOCOL); goto err; } s->init_num=0; /* Since, if we are sending a ssl23 client hello, we are not * reusing a session-id */ if (!ssl_get_new_session(s,0)) goto err; return(SSL_connect(s)); err: return(-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix no-ssl3 configuration option CVE-2014-3568 Reviewed-by: Emilia Kasper <emilia@openssl.org> Reviewed-by: Rich Salz <rsalz@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg_k,alg_a; EVP_PKEY *pkey=NULL; const EVP_MD *md = NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif EVP_MD_CTX_init(&md_ctx); /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { /* * Can't skip server key exchange if this is an ephemeral * ciphersuite. */ if (alg_k & (SSL_kDHE|SSL_kECDHE)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } #ifndef OPENSSL_NO_PSK /* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no identity hint is sent. Set session->sess_cert anyway to avoid problems later.*/ if (alg_k & SSL_kPSK) { s->session->sess_cert=ssl_sess_cert_new(); if (s->ctx->psk_identity_hint) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = NULL; } #endif s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; alg_a=s->s3->tmp.new_cipher->algorithm_auth; al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); /* Store PSK identity hint for later use, hint is used * in ssl3_send_client_key_exchange. Assume that the * maximum length of a PSK identity hint can be as * long as the maximum length of a PSK identity. */ if (i > PSK_MAX_IDENTITY_LEN) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); goto f_err; } param_len += i; /* If received PSK identity hint contains NULL * characters, the hint is truncated from the first * NULL. p may not be ending with NULL, so create a * NULL-terminated string. */ memcpy(tmp_id_hint, p, i); memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); if (s->ctx->psk_identity_hint != NULL) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); if (s->ctx->psk_identity_hint == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto f_err; } p+=i; n-=param_len; } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (1 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 1; i = (unsigned int)(p[0]); p++; if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!srp_verify_server_param(s, &al)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } /* We must check if there is a certificate */ #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif } else #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg_k & SSL_kDHE) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg_k & SSL_kECDHE) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* Check curve is one of our preferences, if not server has * sent an invalid curve. ECParameters is 3 bytes. */ if (!tls1_check_curve(s, p, 3)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE); goto f_err; } if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg_a & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg_k) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { if (SSL_USE_SIGALGS(s)) { int rv; if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) goto err; else if (rv == 0) { goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } else md = EVP_sha1(); if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { EVP_VerifyInit_ex(&md_ctx, md, NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } } else { /* aNULL, aSRP or kPSK do not need public keys */ if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK)) { /* Might be wrong key type, check it */ if (ssl3_check_cert_and_algorithm(s)) /* Otherwise this shouldn't happen */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* still data left over */ if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Only allow ephemeral RSA keys in export ciphersuites. OpenSSL clients would tolerate temporary RSA keys in non-export ciphersuites. It also had an option SSL_OP_EPHEMERAL_RSA which enabled this server side. Remove both options as they are a protocol violation. Thanks to Karthikeyan Bhargavan for reporting this issue. (CVE-2015-0204) Reviewed-by: Matt Caswell <matt@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg_k,alg_a; EVP_PKEY *pkey=NULL; const EVP_MD *md = NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { #ifndef OPENSSL_NO_PSK /* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no identity hint is sent. Set session->sess_cert anyway to avoid problems later.*/ if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK) { s->session->sess_cert=ssl_sess_cert_new(); if (s->ctx->psk_identity_hint) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = NULL; } #endif s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; alg_k=s->s3->tmp.new_cipher->algorithm_mkey; alg_a=s->s3->tmp.new_cipher->algorithm_auth; EVP_MD_CTX_init(&md_ctx); al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); /* Store PSK identity hint for later use, hint is used * in ssl3_send_client_key_exchange. Assume that the * maximum length of a PSK identity hint can be as * long as the maximum length of a PSK identity. */ if (i > PSK_MAX_IDENTITY_LEN) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); goto f_err; } param_len += i; /* If received PSK identity hint contains NULL * characters, the hint is truncated from the first * NULL. p may not be ending with NULL, so create a * NULL-terminated string. */ memcpy(tmp_id_hint, p, i); memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); if (s->ctx->psk_identity_hint != NULL) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); if (s->ctx->psk_identity_hint == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto f_err; } p+=i; n-=param_len; } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (1 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 1; i = (unsigned int)(p[0]); p++; if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!srp_verify_server_param(s, &al)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } /* We must check if there is a certificate */ #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif } else #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg_k & SSL_kEDH) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg_k & SSL_kEECDH) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if ((*p != NAMED_CURVE_TYPE) || ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0)) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg_a & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg_k) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { if (TLS1_get_version(s) >= TLS1_2_VERSION) { int sigalg; if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } sigalg = tls12_get_sigid(pkey); /* Should never happen */ if (sigalg == -1) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* Check key type is consistent with signature */ if (sigalg != (int)p[1]) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_TYPE); al=SSL_AD_DECODE_ERROR; goto f_err; } md = tls12_get_hash(p[0]); if (md == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNKNOWN_DIGEST); goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } else md = EVP_sha1(); if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && TLS1_get_version(s) < TLS1_2_VERSION) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { EVP_VerifyInit_ex(&md_ctx, md, NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } } else { /* aNULL, aSRP or kPSK do not need public keys */ if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* still data left over */ if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'ECDH downgrade bug fix. Fix bug where an OpenSSL client would accept a handshake using an ephemeral ECDH ciphersuites with the server key exchange message omitted. Thanks to Karthikeyan Bhargavan for reporting this issue. CVE-2014-3572 Reviewed-by: Matt Caswell <matt@openssl.org> (cherry picked from commit b15f8769644b00ef7283521593360b7b2135cb63)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix various certificate fingerprint issues. By using non-DER or invalid encodings outside the signed portion of a certificate the fingerprint can be changed without breaking the signature. Although no details of the signed portion of the certificate can be changed this can cause problems with some applications: e.g. those using the certificate fingerprint for blacklists. 1. Reject signatures with non zero unused bits. If the BIT STRING containing the signature has non zero unused bits reject the signature. All current signature algorithms require zero unused bits. 2. Check certificate algorithm consistency. Check the AlgorithmIdentifier inside TBS matches the one in the certificate signature. NB: this will result in signature failure errors for some broken certificates. 3. Check DSA/ECDSA signatures use DER. Reencode DSA/ECDSA signatures and compare with the original received signature. Return an error if there is a mismatch. This will reject various cases including garbage after signature (thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS program for discovering this case) and use of BER or invalid ASN.1 INTEGERs (negative or with leading zeroes). CVE-2014-8275 Reviewed-by: Emilia Käsper <emilia@openssl.org> (cherry picked from commit 684400ce192dac51df3d3e92b61830a6ef90be3e)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ssl3_get_cert_verify(SSL *s) { EVP_PKEY *pkey=NULL; unsigned char *p; int al,ok,ret=0; long n; int type=0,i,j; X509 *peer; const EVP_MD *md = NULL; EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); n=s->method->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A, SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return((int)n); if (s->session->peer != NULL) { peer=s->session->peer; pkey=X509_get_pubkey(peer); type=X509_certificate_type(peer,pkey); } else { peer=NULL; pkey=NULL; } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) { s->s3->tmp.reuse_message=1; if ((peer != NULL) && (type & EVP_PKT_SIGN)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE); goto f_err; } ret=1; goto end; } if (peer == NULL) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } if (!(type & EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE); al=SSL_AD_ILLEGAL_PARAMETER; goto f_err; } if (s->s3->change_cipher_spec) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } /* we now have a signature that we need to verify */ p=(unsigned char *)s->init_msg; /* Check for broken implementations of GOST ciphersuites */ /* If key is GOST and n is exactly 64, it is bare * signature without length field */ if (n==64 && (pkey->type==NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) ) { i=64; } else { if (SSL_USE_SIGALGS(s)) { int rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } else if (rv == 0) { al = SSL_AD_DECODE_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } n2s(p,i); n-=2; if (i > n) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH); al=SSL_AD_DECODE_ERROR; goto f_err; } } j=EVP_PKEY_size(pkey); if ((i > j) || (n > j) || (n <= 0)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE); al=SSL_AD_DECODE_ERROR; goto f_err; } if (SSL_USE_SIGALGS(s)) { long hdatalen = 0; void *hdata; hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR); al=SSL_AD_INTERNAL_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n", EVP_MD_name(md)); #endif if (!EVP_VerifyInit_ex(&mctx, md, NULL) || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB); al=SSL_AD_INTERNAL_ERROR; goto f_err; } if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE); goto f_err; } } else #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md, MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { j=DSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa); if (j <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { j=ECDSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec); if (j <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else #endif if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) { unsigned char signature[64]; int idx; EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL); EVP_PKEY_verify_init(pctx); if (i!=64) { fprintf(stderr,"GOST signature length is %d",i); } for (idx=0;idx<64;idx++) { signature[63-idx]=p[idx]; } j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32); EVP_PKEY_CTX_free(pctx); if (j<=0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR); al=SSL_AD_UNSUPPORTED_CERTIFICATE; goto f_err; } ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } end: if (s->s3->handshake_buffer) { BIO_free(s->s3->handshake_buffer); s->s3->handshake_buffer = NULL; s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE; } EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_free(pkey); return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Unauthenticated DH client certificate fix. Fix to prevent use of DH client certificates without sending certificate verify message. If we've used a client certificate to generate the premaster secret ssl3_get_client_key_exchange returns 2 and ssl3_get_cert_verify is never called. We can only skip the certificate verify message in ssl3_get_cert_verify if the client didn't send a certificate. Thanks to Karthikeyan Bhargavan for reporting this issue. CVE-2015-0205 Reviewed-by: Matt Caswell <matt@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[4],b[0],c2,c3,c1); mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); mul_add_c(a[0],b[4],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[0],b[5],c3,c1,c2); mul_add_c(a[1],b[4],c3,c1,c2); mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); mul_add_c(a[4],b[1],c3,c1,c2); mul_add_c(a[5],b[0],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[6],b[0],c1,c2,c3); mul_add_c(a[5],b[1],c1,c2,c3); mul_add_c(a[4],b[2],c1,c2,c3); mul_add_c(a[3],b[3],c1,c2,c3); mul_add_c(a[2],b[4],c1,c2,c3); mul_add_c(a[1],b[5],c1,c2,c3); mul_add_c(a[0],b[6],c1,c2,c3); r[6]=c1; c1=0; mul_add_c(a[0],b[7],c2,c3,c1); mul_add_c(a[1],b[6],c2,c3,c1); mul_add_c(a[2],b[5],c2,c3,c1); mul_add_c(a[3],b[4],c2,c3,c1); mul_add_c(a[4],b[3],c2,c3,c1); mul_add_c(a[5],b[2],c2,c3,c1); mul_add_c(a[6],b[1],c2,c3,c1); mul_add_c(a[7],b[0],c2,c3,c1); r[7]=c2; c2=0; mul_add_c(a[7],b[1],c3,c1,c2); mul_add_c(a[6],b[2],c3,c1,c2); mul_add_c(a[5],b[3],c3,c1,c2); mul_add_c(a[4],b[4],c3,c1,c2); mul_add_c(a[3],b[5],c3,c1,c2); mul_add_c(a[2],b[6],c3,c1,c2); mul_add_c(a[1],b[7],c3,c1,c2); r[8]=c3; c3=0; mul_add_c(a[2],b[7],c1,c2,c3); mul_add_c(a[3],b[6],c1,c2,c3); mul_add_c(a[4],b[5],c1,c2,c3); mul_add_c(a[5],b[4],c1,c2,c3); mul_add_c(a[6],b[3],c1,c2,c3); mul_add_c(a[7],b[2],c1,c2,c3); r[9]=c1; c1=0; mul_add_c(a[7],b[3],c2,c3,c1); mul_add_c(a[6],b[4],c2,c3,c1); mul_add_c(a[5],b[5],c2,c3,c1); mul_add_c(a[4],b[6],c2,c3,c1); mul_add_c(a[3],b[7],c2,c3,c1); r[10]=c2; c2=0; mul_add_c(a[4],b[7],c3,c1,c2); mul_add_c(a[5],b[6],c3,c1,c2); mul_add_c(a[6],b[5],c3,c1,c2); mul_add_c(a[7],b[4],c3,c1,c2); r[11]=c3; c3=0; mul_add_c(a[7],b[5],c1,c2,c3); mul_add_c(a[6],b[6],c1,c2,c3); mul_add_c(a[5],b[7],c1,c2,c3); r[12]=c1; c1=0; mul_add_c(a[6],b[7],c2,c3,c1); mul_add_c(a[7],b[6],c2,c3,c1); r[13]=c2; c2=0; mul_add_c(a[7],b[7],c3,c1,c2); r[14]=c3; r[15]=c1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <emilia@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DECLAREContigPutFunc(putcontig8bitYCbCr41tile) { (void) y; /* XXX adjust fromskew */ do { x = w>>2; do { int32 Cb = pp[4]; int32 Cr = pp[5]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); cp += 4; pp += 6; } while (--x); if( (w&3) != 0 ) { int32 Cb = pp[4]; int32 Cr = pp[5]; switch( (w&3) ) { case 3: YCbCrtoRGB(cp [2], pp[2]); case 2: YCbCrtoRGB(cp [1], pp[1]); case 1: YCbCrtoRGB(cp [0], pp[0]); case 0: break; } cp += (w&3); pp += 6; } cp += toskew; pp += fromskew; } while (--h); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': '* libtiff/tif_next.c: add new tests to check that we don't read outside of the compressed input stream buffer. * libtiff/tif_getimage.c: in OJPEG case, fix checks on strile width/height'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void do_free_upto(BIO *f, BIO *upto) { if (upto) { BIO *tbio; do { tbio = BIO_pop(f); BIO_free(f); f = tbio; } while (f != upto); } else BIO_free_all(f); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Fix infinite loop in CMS Fix loop in do_free_upto if cmsbio is NULL: this will happen when attempting to verify and a digest is not recognised. Reported by Johannes Bauer. CVE-2015-1792 Reviewed-by: Matt Caswell <matt@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, int tag, int aclass, char opt, ASN1_TLC *ctx) { const ASN1_TEMPLATE *tt, *errtt = NULL; const ASN1_COMPAT_FUNCS *cf; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; const unsigned char *p = NULL, *q; unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */ unsigned char imphack = 0, oclass; char seq_eoc, seq_nolen, cst, isopt; long tmplen; int i; int otag; int ret = 0; ASN1_VALUE **pchptr, *ptmpval; if (!pval) return 0; if (aux && aux->asn1_cb) asn1_cb = aux->asn1_cb; else asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { /* * tagging or OPTIONAL is currently illegal on an item template * because the flags can't get passed down. In practice this * isn't a problem: we include the relevant flags from the item * template in the template itself. */ if ((tag != -1) || opt) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE); goto err; } return asn1_template_ex_d2i(pval, in, len, it->templates, opt, ctx); } return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt, ctx); break; case ASN1_ITYPE_MSTRING: p = *in; /* Just read in tag and class */ ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL, &p, len, -1, 0, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Must be UNIVERSAL class */ if (oclass != V_ASN1_UNIVERSAL) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL); goto err; } /* Check tag matches bit map */ if (!(ASN1_tag2bit(otag) & it->utype)) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG); goto err; } return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx); case ASN1_ITYPE_EXTERN: /* Use new style d2i */ ef = it->funcs; return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx); case ASN1_ITYPE_COMPAT: /* we must resort to old style evil hackery */ cf = it->funcs; /* If OPTIONAL see if it is there */ if (opt) { int exptag; p = *in; if (tag == -1) exptag = it->utype; else exptag = tag; /* * Don't care about anything other than presence of expected tag */ ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL, &p, len, exptag, aclass, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (ret == -1) return -1; } /* * This is the old style evil hack IMPLICIT handling: since the * underlying code is expecting a tag and class other than the one * present we change the buffer temporarily then change it back * afterwards. This doesn't and never did work for tags > 30. Yes * this is *horrible* but it is only needed for old style d2i which * will hopefully not be around for much longer. FIXME: should copy * the buffer then modify it so the input buffer can be const: we * should *always* copy because the old style d2i might modify the * buffer. */ if (tag != -1) { wp = *(unsigned char **)in; imphack = *wp; if (p == NULL) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED) | it->utype); } ptmpval = cf->asn1_d2i(pval, in, len); if (tag != -1) *wp = imphack; if (ptmpval) return 1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; case ASN1_ITYPE_CHOICE: if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; if (*pval) { /* Free up and zero CHOICE value if initialised */ i = asn1_get_choice_selector(pval, it); if ((i >= 0) && (i < it->tcount)) { tt = it->templates + i; pchptr = asn1_get_field_ptr(pval, tt); ASN1_template_free(pchptr, tt); asn1_set_choice_selector(pval, -1, it); } } else if (!ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* CHOICE type, try each possibility in turn */ p = *in; for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { pchptr = asn1_get_field_ptr(pval, tt); /* * We mark field as OPTIONAL so its absence can be recognised. */ ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx); /* If field not present, try the next one */ if (ret == -1) continue; /* If positive return, read OK, break loop */ if (ret > 0) break; /* Otherwise must be an ASN1 parsing error */ errtt = tt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Did we fall off the end without reading anything? */ if (i == it->tcount) { /* If OPTIONAL, this is OK */ if (opt) { /* Free and zero it */ ASN1_item_ex_free(pval, it); return -1; } ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE); goto err; } asn1_set_choice_selector(pval, i, it); *in = p; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; return 1; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: p = *in; tmplen = len; /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */ if (tag == -1) { tag = V_ASN1_SEQUENCE; aclass = V_ASN1_UNIVERSAL; } /* Get SEQUENCE length and update len, p */ ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst, &p, len, tag, aclass, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } else if (ret == -1) return -1; if (aux && (aux->flags & ASN1_AFLG_BROKEN)) { len = tmplen - (p - *in); seq_nolen = 1; } /* If indefinite we don't do a length check */ else seq_nolen = seq_eoc; if (!cst) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED); goto err; } if (!*pval && !ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Free up and zero any ADB found */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { if (tt->flags & ASN1_TFLG_ADB_MASK) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 1); pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } } /* Get each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 1); if (!seqtt) goto err; pseqval = asn1_get_field_ptr(pval, seqtt); /* Have we ran out of data? */ if (!len) break; q = p; if (asn1_check_eoc(&p, len)) { if (!seq_eoc) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC); goto err; } len -= p - q; seq_eoc = 0; q = p; break; } /* * This determines the OPTIONAL flag value. The field cannot be * omitted if it is the last of a SEQUENCE and there is still * data to be read. This isn't strictly necessary but it * increases efficiency in some cases. */ if (i == (it->tcount - 1)) isopt = 0; else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL); /* * attempt to read in field, allowing each to be OPTIONAL */ ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx); if (!ret) { errtt = seqtt; goto err; } else if (ret == -1) { /* * OPTIONAL component absent. Free and zero the field. */ ASN1_template_free(pseqval, seqtt); continue; } /* Update length */ len -= p - q; } /* Check for EOC if expecting one */ if (seq_eoc && !asn1_check_eoc(&p, len)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC); goto err; } /* Check all data read */ if (!seq_nolen && len) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH); goto err; } /* * If we get here we've got no more data in the SEQUENCE, however we * may not have read all fields so check all remaining are OPTIONAL * and clear any that are. */ for (; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; seqtt = asn1_do_adb(pval, tt, 1); if (!seqtt) goto err; if (seqtt->flags & ASN1_TFLG_OPTIONAL) { ASN1_VALUE **pseqval; pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } else { errtt = seqtt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING); goto err; } } /* Save encoding */ if (!asn1_enc_save(pval, *in, p - *in, it)) goto auxerr; *in = p; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; return 1; default: return 0; } auxerr: ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR); err: ASN1_item_ex_free(pval, it); if (errtt) ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname); else ERR_add_error_data(2, "Type=", it->sname); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Fix leak with ASN.1 combine. When parsing a combined structure pass a flag to the decode routine so on error a pointer to the parent structure is not zeroed as this will leak any additional components in the parent. This can leak memory in any application parsing PKCS#7 or CMS structures. CVE-2015-3195. Thanks to Adam Langley (Google/BoringSSL) for discovering this bug using libFuzzer. PR#4131 Reviewed-by: Richard Levitte <levitte@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int www_body(int s, int stype, unsigned char *context) { char *buf = NULL; int ret = 1; int i, j, k, dot; SSL *con; const SSL_CIPHER *c; BIO *io, *ssl_bio, *sbio; #ifdef RENEG int total_bytes = 0; #endif int width; fd_set readfds; /* Set width for a select call if needed */ width = s + 1; buf = app_malloc(bufsize, "server www buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; #ifdef FIONBIO if (s_nbio) { unsigned long sl = 1; if (!s_quiet) BIO_printf(bio_err, "turning on non blocking io\n"); if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0) ERR_print_errors(bio_err); } #endif /* lets make the output buffer a reasonable size */ if (!BIO_set_write_buffer_size(io, bufsize)) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context && !SSL_set_session_id_context(con, context, strlen((char *)context))) goto err; sbio = BIO_new_socket(s, BIO_NOCLOSE); if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* SSL_set_fd(con,s); */ BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); #ifdef CHARSET_EBCDIC io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io); #endif if (s_debug) { BIO_set_callback(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } for (;;) { i = BIO_gets(io, buf, bufsize - 1); if (i < 0) { /* error */ if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); continue; } #endif #if defined(OPENSSL_SYS_NETWARE) delay(1000); #elif !defined(OPENSSL_SYS_MSDOS) sleep(1); #endif continue; } } else if (i == 0) { /* end of input */ ret = 1; goto end; } /* else we have data */ if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) || ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) { char *p; X509 *peer; STACK_OF(SSL_CIPHER) *sk; static const char *space = " "; if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) { if (strncmp("GET /renegcert", buf, 14) == 0) SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); i = SSL_renegotiate(con); BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i); /* Send the HelloRequest */ i = SSL_do_handshake(con); if (i <= 0) { BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n", SSL_get_error(con, i)); ERR_print_errors(bio_err); goto err; } /* Wait for a ClientHello to come back */ FD_ZERO(&readfds); openssl_fdset(s, &readfds); i = select(width, (void *)&readfds, NULL, NULL, NULL); if (i <= 0 || !FD_ISSET(s, &readfds)) { BIO_printf(bio_s_out, "Error waiting for client response\n"); ERR_print_errors(bio_err); goto err; } /* * We're not acutally expecting any data here and we ignore * any that is sent. This is just to force the handshake that * we're expecting to come from the client. If they haven't * sent one there's not much we can do. */ BIO_gets(io, buf, bufsize - 1); } BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n"); BIO_puts(io, "<pre>\n"); /* BIO_puts(io,OpenSSL_version(OPENSSL_VERSION));*/ BIO_puts(io, "\n"); for (i = 0; i < local_argc; i++) { const char *myp; for (myp = local_argv[i]; *myp; myp++) switch (*myp) { case '<': BIO_puts(io, "&lt;"); break; case '>': BIO_puts(io, "&gt;"); break; case '&': BIO_puts(io, "&amp;"); break; default: BIO_write(io, myp, 1); break; } BIO_write(io, " ", 1); } BIO_puts(io, "\n"); BIO_printf(io, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(con) ? "" : " NOT"); /* * The following is evil and should not really be done */ BIO_printf(io, "Ciphers supported in s_server binary\n"); sk = SSL_get_ciphers(con); j = sk_SSL_CIPHER_num(sk); for (i = 0; i < j; i++) { c = sk_SSL_CIPHER_value(sk, i); BIO_printf(io, "%-11s:%-25s ", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); if ((((i + 1) % 2) == 0) && (i + 1 != j)) BIO_puts(io, "\n"); } BIO_puts(io, "\n"); p = SSL_get_shared_ciphers(con, buf, bufsize); if (p != NULL) { BIO_printf(io, "---\nCiphers common between both SSL end points:\n"); j = i = 0; while (*p) { if (*p == ':') { BIO_write(io, space, 26 - j); i++; j = 0; BIO_write(io, ((i % 3) ? " " : "\n"), 1); } else { BIO_write(io, p, 1); j++; } p++; } BIO_puts(io, "\n"); } ssl_print_sigalgs(io, con); #ifndef OPENSSL_NO_EC ssl_print_curves(io, con, 0); #endif BIO_printf(io, (SSL_session_reused(con) ? "---\nReused, " : "---\nNew, ")); c = SSL_get_current_cipher(con); BIO_printf(io, "%s, Cipher is %s\n", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); SSL_SESSION_print(io, SSL_get_session(con)); BIO_printf(io, "---\n"); print_stats(io, SSL_get_SSL_CTX(con)); BIO_printf(io, "---\n"); peer = SSL_get_peer_certificate(con); if (peer != NULL) { BIO_printf(io, "Client certificate\n"); X509_print(io, peer); PEM_write_bio_X509(io, peer); } else BIO_puts(io, "no client certificate available\n"); BIO_puts(io, "</BODY></HTML>\r\n\r\n"); break; } else if ((www == 2 || www == 3) && (strncmp("GET /", buf, 5) == 0)) { BIO *file; char *p, *e; static const char *text = "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"; /* skip the '/' */ p = &(buf[5]); dot = 1; for (e = p; *e != '\0'; e++) { if (e[0] == ' ') break; switch (dot) { case 1: dot = (e[0] == '.') ? 2 : 0; break; case 2: dot = (e[0] == '.') ? 3 : 0; break; case 3: dot = (e[0] == '/') ? -1 : 0; break; } if (dot == 0) dot = (e[0] == '/') ? 1 : 0; } dot = (dot == 3) || (dot == -1); /* filename contains ".." * component */ if (*e == '\0') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid file name\r\n", p); break; } *e = '\0'; if (dot) { BIO_puts(io, text); BIO_printf(io, "'%s' contains '..' reference\r\n", p); break; } if (*p == '/') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid path\r\n", p); break; } /* if a directory, do the index thang */ if (app_isdir(p) > 0) { BIO_puts(io, text); BIO_printf(io, "'%s' is a directory\r\n", p); break; } if ((file = BIO_new_file(p, "r")) == NULL) { BIO_puts(io, text); BIO_printf(io, "Error opening '%s'\r\n", p); ERR_print_errors(io); break; } if (!s_quiet) BIO_printf(bio_err, "FILE:%s\n", p); if (www == 2) { i = strlen(p); if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) || ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) || ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0))) BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); else BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"); } /* send the file */ for (;;) { i = BIO_read(file, buf, bufsize); if (i <= 0) break; #ifdef RENEG total_bytes += i; BIO_printf(bio_err, "%d\n", i); if (total_bytes > 3 * 1024) { total_bytes = 0; BIO_printf(bio_err, "RENEGOTIATE\n"); SSL_renegotiate(con); } #endif for (j = 0; j < i;) { #ifdef RENEG { static count = 0; if (++count == 13) { SSL_renegotiate(con); } } #endif k = BIO_write(io, &(buf[j]), i - j); if (k <= 0) { if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) goto write_error; else { BIO_printf(bio_s_out, "rwrite W BLOCK\n"); } } else { j += k; } } } write_error: BIO_free(file); break; } } for (;;) { i = (int)BIO_flush(io); if (i <= 0) { if (!BIO_should_retry(io)) break; } else break; } end: /* make sure we re-use sessions */ SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); err: if (ret >= 0) BIO_printf(bio_s_out, "ACCEPT\n"); OPENSSL_free(buf); BIO_free_all(io); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2016-0798: avoid memory leak in SRP The SRP user database lookup method SRP_VBASE_get_by_user had confusing memory management semantics; the returned pointer was sometimes newly allocated, and sometimes owned by the callee. The calling code has no way of distinguishing these two cases. Specifically, SRP servers that configure a secret seed to hide valid login information are vulnerable to a memory leak: an attacker connecting with an invalid username can cause a memory leak of around 300 bytes per connection. Servers that do not configure SRP, or configure SRP but do not configure a seed are not vulnerable. In Apache, the seed directive is known as SSLSRPUnknownUserSeed. To mitigate the memory leak, the seed handling in SRP_VBASE_get_by_user is now disabled even if the user has configured a seed. Applications are advised to migrate to SRP_VBASE_get1_by_user. However, note that OpenSSL makes no strong guarantees about the indistinguishability of valid and invalid logins. In particular, computations are currently not carried out in constant time. Reviewed-by: Rich Salz <rsalz@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _dopr(char **sbuffer, char **buffer, size_t *maxlen, size_t *retlen, int *truncated, const char *format, va_list args) { char ch; LLONG value; LDOUBLE fvalue; char *strvalue; int min; int max; int state; int flags; int cflags; size_t currlen; state = DP_S_DEFAULT; flags = currlen = cflags = min = 0; max = -1; ch = *format++; while (state != DP_S_DONE) { if (ch == '\0' || (buffer == NULL && currlen >= *maxlen)) state = DP_S_DONE; switch (state) { case DP_S_DEFAULT: if (ch == '%') state = DP_S_FLAGS; else doapr_outch(sbuffer, buffer, &currlen, maxlen, ch); ch = *format++; break; case DP_S_FLAGS: switch (ch) { case '-': flags |= DP_F_MINUS; ch = *format++; break; case '+': flags |= DP_F_PLUS; ch = *format++; break; case ' ': flags |= DP_F_SPACE; ch = *format++; break; case '#': flags |= DP_F_NUM; ch = *format++; break; case '0': flags |= DP_F_ZERO; ch = *format++; break; default: state = DP_S_MIN; break; } break; case DP_S_MIN: if (isdigit((unsigned char)ch)) { min = 10 * min + char_to_int(ch); ch = *format++; } else if (ch == '*') { min = va_arg(args, int); ch = *format++; state = DP_S_DOT; } else state = DP_S_DOT; break; case DP_S_DOT: if (ch == '.') { state = DP_S_MAX; ch = *format++; } else state = DP_S_MOD; break; case DP_S_MAX: if (isdigit((unsigned char)ch)) { if (max < 0) max = 0; max = 10 * max + char_to_int(ch); ch = *format++; } else if (ch == '*') { max = va_arg(args, int); ch = *format++; state = DP_S_MOD; } else state = DP_S_MOD; break; case DP_S_MOD: switch (ch) { case 'h': cflags = DP_C_SHORT; ch = *format++; break; case 'l': if (*format == 'l') { cflags = DP_C_LLONG; format++; } else cflags = DP_C_LONG; ch = *format++; break; case 'q': cflags = DP_C_LLONG; ch = *format++; break; case 'L': cflags = DP_C_LDOUBLE; ch = *format++; break; default: break; } state = DP_S_CONV; break; case DP_S_CONV: switch (ch) { case 'd': case 'i': switch (cflags) { case DP_C_SHORT: value = (short int)va_arg(args, int); break; case DP_C_LONG: value = va_arg(args, long int); break; case DP_C_LLONG: value = va_arg(args, LLONG); break; default: value = va_arg(args, int); break; } fmtint(sbuffer, buffer, &currlen, maxlen, value, 10, min, max, flags); break; case 'X': flags |= DP_F_UP; /* FALLTHROUGH */ case 'x': case 'o': case 'u': flags |= DP_F_UNSIGNED; switch (cflags) { case DP_C_SHORT: value = (unsigned short int)va_arg(args, unsigned int); break; case DP_C_LONG: value = (LLONG) va_arg(args, unsigned long int); break; case DP_C_LLONG: value = va_arg(args, unsigned LLONG); break; default: value = (LLONG) va_arg(args, unsigned int); break; } fmtint(sbuffer, buffer, &currlen, maxlen, value, ch == 'o' ? 8 : (ch == 'u' ? 10 : 16), min, max, flags); break; case 'f': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); fmtfp(sbuffer, buffer, &currlen, maxlen, fvalue, min, max, flags); break; case 'E': flags |= DP_F_UP; case 'e': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); break; case 'G': flags |= DP_F_UP; case 'g': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); break; case 'c': doapr_outch(sbuffer, buffer, &currlen, maxlen, va_arg(args, int)); break; case 's': strvalue = va_arg(args, char *); if (max < 0) { if (buffer) max = INT_MAX; else max = *maxlen; } fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue, flags, min, max); break; case 'p': value = (size_t)va_arg(args, void *); fmtint(sbuffer, buffer, &currlen, maxlen, value, 16, min, max, flags | DP_F_NUM); break; case 'n': /* XXX */ if (cflags == DP_C_SHORT) { short int *num; num = va_arg(args, short int *); *num = currlen; } else if (cflags == DP_C_LONG) { /* XXX */ long int *num; num = va_arg(args, long int *); *num = (long int)currlen; } else if (cflags == DP_C_LLONG) { /* XXX */ LLONG *num; num = va_arg(args, LLONG *); *num = (LLONG) currlen; } else { int *num; num = va_arg(args, int *); *num = currlen; } break; case '%': doapr_outch(sbuffer, buffer, &currlen, maxlen, ch); break; case 'w': /* not supported yet, treat as next char */ ch = *format++; break; default: /* unknown, skip */ break; } ch = *format++; state = DP_S_DEFAULT; flags = cflags = min = 0; max = -1; break; case DP_S_DONE: break; default: break; } } *truncated = (currlen > *maxlen - 1); if (*truncated) currlen = *maxlen - 1; doapr_outch(sbuffer, buffer, &currlen, maxlen, '\0'); *retlen = currlen - 1; return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix memory issues in BIO_*printf functions The internal |fmtstr| function used in processing a "%s" format string in the BIO_*printf functions could overflow while calculating the length of a string and cause an OOB read when printing very long strings. Additionally the internal |doapr_outch| function can attempt to write to an OOB memory location (at an offset from the NULL pointer) in the event of a memory allocation failure. In 1.0.2 and below this could be caused where the size of a buffer to be allocated is greater than INT_MAX. E.g. this could be in processing a very long "%s" format string. Memory leaks can also occur. These issues will only occur on certain platforms where sizeof(size_t) > sizeof(int). E.g. many 64 bit systems. The first issue may mask the second issue dependent on compiler behaviour. These problems could enable attacks where large amounts of untrusted data is passed to the BIO_*printf functions. If applications use these functions in this way then they could be vulnerable. OpenSSL itself uses these functions when printing out human-readable dumps of ASN.1 data. Therefore applications that print this data could be vulnerable if the data is from untrusted sources. OpenSSL command line applications could also be vulnerable where they print out ASN.1 data, or if untrusted data is passed as command line arguments. Libssl is not considered directly vulnerable. Additionally certificates etc received via remote connections via libssl are also unlikely to be able to trigger these issues because of message size limits enforced within libssl. CVE-2016-0799 Issue reported by Guido Vranken. Reviewed-by: Andy Polyakov <appro@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_HMAC_SHA1 *key = data(ctx); unsigned int l; size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and * later */ sha_off = 0; # if defined(STITCHED_CALL) size_t aes_off = 0, blocks; sha_off = SHA_CBLOCK - key->md.num; # endif key->payload_length = NO_PAYLOAD_LENGTH; if (len % AES_BLOCK_SIZE) return 0; if (ctx->encrypt) { if (plen == NO_PAYLOAD_LENGTH) plen = len; else if (len != ((plen + SHA_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)) return 0; else if (key->aux.tls_ver >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; # if defined(STITCHED_CALL) if (plen > (sha_off + iv) && (blocks = (plen - (sha_off + iv)) / SHA_CBLOCK)) { SHA1_Update(&key->md, in + iv, sha_off); aesni_cbc_sha1_enc(in, out, blocks, &key->ks, ctx->iv, &key->md, in + iv + sha_off); blocks *= SHA_CBLOCK; aes_off += blocks; sha_off += blocks; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else { sha_off = 0; } # endif sha_off += iv; SHA1_Update(&key->md, in + sha_off, plen - sha_off); if (plen != len) { /* "TLS" mode of operation */ if (in != out) memcpy(out + aes_off, in + aes_off, plen - aes_off); /* calculate HMAC and append it to payload */ SHA1_Final(out + plen, &key->md); key->md = key->tail; SHA1_Update(&key->md, out + plen, SHA_DIGEST_LENGTH); SHA1_Final(out + plen, &key->md); /* pad the payload|hmac */ plen += SHA_DIGEST_LENGTH; for (l = len - plen - 1; plen < len; plen++) out[plen] = l; /* encrypt HMAC|padding at once */ aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } else { aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } } else { union { unsigned int u[SHA_DIGEST_LENGTH / sizeof(unsigned int)]; unsigned char c[32 + SHA_DIGEST_LENGTH]; } mac, *pmac; /* arrange cache line alignment */ pmac = (void *)(((size_t)mac.c + 31) & ((size_t)0 - 32)); /* decrypt HMAC|padding at once */ aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0); if (plen) { /* "TLS" mode of operation */ size_t inp_len, mask, j, i; unsigned int res, maxpad, pad, bitlen; int ret = 1; union { unsigned int u[SHA_LBLOCK]; unsigned char c[SHA_CBLOCK]; } *data = (void *)key->md.data; if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3]) >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; if (len < (iv + SHA_DIGEST_LENGTH + 1)) return 0; /* omit explicit iv */ out += iv; len -= iv; /* figure out payload length */ pad = out[len - 1]; maxpad = len - (SHA_DIGEST_LENGTH + 1); maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8); maxpad &= 255; inp_len = len - (SHA_DIGEST_LENGTH + pad + 1); mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1))); inp_len &= mask; ret &= (int)mask; key->aux.tls_aad[plen - 2] = inp_len >> 8; key->aux.tls_aad[plen - 1] = inp_len; /* calculate HMAC */ key->md = key->head; SHA1_Update(&key->md, key->aux.tls_aad, plen); # if 1 len -= SHA_DIGEST_LENGTH; /* amend mac */ if (len >= (256 + SHA_CBLOCK)) { j = (len - (256 + SHA_CBLOCK)) & (0 - SHA_CBLOCK); j += SHA_CBLOCK - key->md.num; SHA1_Update(&key->md, out, j); out += j; len -= j; inp_len -= j; } /* but pretend as if we hashed padded payload */ bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */ # ifdef BSWAP bitlen = BSWAP(bitlen); # else mac.c[0] = 0; mac.c[1] = (unsigned char)(bitlen >> 16); mac.c[2] = (unsigned char)(bitlen >> 8); mac.c[3] = (unsigned char)bitlen; bitlen = mac.u[0]; # endif pmac->u[0] = 0; pmac->u[1] = 0; pmac->u[2] = 0; pmac->u[3] = 0; pmac->u[4] = 0; for (res = key->md.num, j = 0; j < len; j++) { size_t c = out[j]; mask = (j - inp_len) >> (sizeof(j) * 8 - 8); c &= mask; c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8)); data->c[res++] = (unsigned char)c; if (res != SHA_CBLOCK) continue; /* j is not incremented yet */ mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha1_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; res = 0; } for (i = res; i < SHA_CBLOCK; i++, j++) data->c[i] = 0; if (res > SHA_CBLOCK - 8) { mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha1_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; memset(data, 0, SHA_CBLOCK); j += 64; } data->u[SHA_LBLOCK - 1] = bitlen; sha1_block_data_order(&key->md, data, 1); mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; # ifdef BSWAP pmac->u[0] = BSWAP(pmac->u[0]); pmac->u[1] = BSWAP(pmac->u[1]); pmac->u[2] = BSWAP(pmac->u[2]); pmac->u[3] = BSWAP(pmac->u[3]); pmac->u[4] = BSWAP(pmac->u[4]); # else for (i = 0; i < 5; i++) { res = pmac->u[i]; pmac->c[4 * i + 0] = (unsigned char)(res >> 24); pmac->c[4 * i + 1] = (unsigned char)(res >> 16); pmac->c[4 * i + 2] = (unsigned char)(res >> 8); pmac->c[4 * i + 3] = (unsigned char)res; } # endif len += SHA_DIGEST_LENGTH; # else SHA1_Update(&key->md, out, inp_len); res = key->md.num; SHA1_Final(pmac->c, &key->md); { unsigned int inp_blocks, pad_blocks; /* but pretend as if we hashed padded payload */ inp_blocks = 1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); res += (unsigned int)(len - inp_len); pad_blocks = res / SHA_CBLOCK; res %= SHA_CBLOCK; pad_blocks += 1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); for (; inp_blocks < pad_blocks; inp_blocks++) sha1_block_data_order(&key->md, data, 1); } # endif key->md = key->tail; SHA1_Update(&key->md, pmac->c, SHA_DIGEST_LENGTH); SHA1_Final(pmac->c, &key->md); /* verify HMAC */ out += inp_len; len -= inp_len; # if 1 { unsigned char *p = out + len - 1 - maxpad - SHA_DIGEST_LENGTH; size_t off = out - p; unsigned int c, cmask; maxpad += SHA_DIGEST_LENGTH; for (res = 0, i = 0, j = 0; j < maxpad; j++) { c = p[j]; cmask = ((int)(j - off - SHA_DIGEST_LENGTH)) >> (sizeof(int) * 8 - 1); res |= (c ^ pad) & ~cmask; /* ... and padding */ cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1); res |= (c ^ pmac->c[i]) & cmask; i += 1 & cmask; } maxpad -= SHA_DIGEST_LENGTH; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; } # else for (res = 0, i = 0; i < SHA_DIGEST_LENGTH; i++) res |= out[i] ^ pmac->c[i]; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; /* verify padding */ pad = (pad & ~res) | (maxpad & res); out = out + len - 1 - pad; for (res = 0, i = 0; i < pad; i++) res |= out[i] ^ pad; res = (0 - res) >> (sizeof(res) * 8 - 1); ret &= (int)~res; # endif return ret; } else { SHA1_Update(&key->md, out, len); } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Check that we have enough padding characters. Reviewed-by: Emilia Käsper <emilia@openssl.org> CVE-2016-2107 MR: #2572'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CAMLprim value caml_alloc_dummy_float (value size) { mlsize_t wosize = Int_val(size) * Double_wosize; if (wosize == 0) return Atom(0); return caml_alloc (wosize, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'fix PR#7003 and a few other bugs caused by misuse of Int_val git-svn-id: http://caml.inria.fr/svn/ocaml/trunk@16525 f963ae5c-01c2-4b8c-9fe0-0dff7051ff02'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) { unsigned short type, size, len; /* If resumed session or no custom extensions nothing to do */ if (s->hit || s->cert->srv_ext.meths_count == 0) return 1; if (data >= limit - 2) return 1; n2s(data, len); if (data > limit - len) return 1; while (data <= limit - 4) { n2s(data, type); n2s(data, size); if (data + size > limit) return 1; if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0) return 0; data += size; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Avoid some undefined pointer arithmetic A common idiom in the codebase is: if (p + len > limit) { return; /* Too long */ } Where "p" points to some malloc'd data of SIZE bytes and limit == p + SIZE "len" here could be from some externally supplied data (e.g. from a TLS message). The rules of C pointer arithmetic are such that "p + len" is only well defined where len <= SIZE. Therefore the above idiom is actually undefined behaviour. For example this could cause problems if some malloc implementation provides an address for "p" such that "p + len" actually overflows for values of len that are too big and therefore p + len < limit! Issue reported by Guido Vranken. CVE-2016-2177 Reviewed-by: Rich Salz <rsalz@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif )) return ((tmsize_t)(-1)); assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[strip])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu, strip %lu", (unsigned long) tif->tif_row, (unsigned long) strip); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned __int64) cc, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long long) cc, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[strip]; mb=ma+size; if (((uint64)ma!=td->td_stripoffset[strip])||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu, strip %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) strip, (unsigned __int64) n, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) strip, (unsigned long long) n, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': '* libtiff/tif_read.c: Fix out-of-bounds read on memory-mapped files in TIFFReadRawStrip1() and TIFFReadRawTile1() when stripoffset is beyond tmsize_t max value (reported by Mathias Svensson)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int dtls1_get_record(SSL *s) { int ssl_major, ssl_minor; int i, n; SSL3_RECORD *rr; unsigned char *p = NULL; unsigned short version; DTLS1_BITMAP *bitmap; unsigned int is_next_epoch; rr = &(s->s3->rrec); /* * The epoch may have changed. If so, process all the pending records. * This is a non-blocking operation. */ if (dtls1_process_buffered_records(s) < 0) return -1; /* if we're renegotiating, then there may be buffered records */ if (dtls1_get_processed_record(s)) return 1; /* get something from the wire */ again: /* check if we have the header */ if ((s->rstate != SSL_ST_READ_BODY) || (s->packet_length < DTLS1_RT_HEADER_LENGTH)) { n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); /* read timeout is handled by dtls1_read_bytes */ if (n <= 0) return (n); /* error or non-blocking */ /* this packet contained a partial record, dump it */ if (s->packet_length != DTLS1_RT_HEADER_LENGTH) { s->packet_length = 0; goto again; } s->rstate = SSL_ST_READ_BODY; p = s->packet; /* Pull apart the header into the DTLS1_RECORD */ rr->type = *(p++); ssl_major = *(p++); ssl_minor = *(p++); version = (ssl_major << 8) | ssl_minor; /* sequence number is 64 bits, with top 2 bytes = epoch */ n2s(p, rr->epoch); memcpy(&(s->s3->read_sequence[2]), p, 6); p += 6; n2s(p, rr->length); /* Lets check version */ if (!s->first_packet) { if (version != s->version) { /* unexpected version, silently discard */ rr->length = 0; s->packet_length = 0; goto again; } } if ((version & 0xff00) != (s->version & 0xff00)) { /* wrong version, silently discard record */ rr->length = 0; s->packet_length = 0; goto again; } if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { /* record too long, silently discard it */ rr->length = 0; s->packet_length = 0; goto again; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) { /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */ i = rr->length; n = ssl3_read_n(s, i, i, 1); /* this packet contained a partial record, dump it */ if (n != i) { rr->length = 0; s->packet_length = 0; goto again; } /* * now n == rr->length, and s->packet_length == * DTLS1_RT_HEADER_LENGTH + rr->length */ } s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */ /* match epochs. NULL means the packet is dropped on the floor */ bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); if (bitmap == NULL) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP /* Only do replay check if no SCTP bio */ if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) { #endif /* * Check whether this is a repeat, or aged record. Don't check if * we're listening and this message is a ClientHello. They can look * as if they're replayed, since they arrive from different * connections and would be dropped unnecessarily. */ if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE && s->packet_length > DTLS1_RT_HEADER_LENGTH && s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) && !dtls1_record_replay_check(s, bitmap)) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP } #endif /* just read a 0 length packet */ if (rr->length == 0) goto again; /* * If this record is from the next epoch (either HM or ALERT), and a * handshake is currently in progress, buffer it since it cannot be * processed at this time. However, do not buffer anything while * listening. */ if (is_next_epoch) { if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) { if (dtls1_buffer_record (s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0) return -1; /* Mark receipt of record. */ dtls1_record_bitmap_update(s, bitmap); } rr->length = 0; s->packet_length = 0; goto again; } if (!dtls1_process_record(s)) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */ return (1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix DTLS unprocessed records bug During a DTLS handshake we may get records destined for the next epoch arrive before we have processed the CCS. In that case we can't decrypt or verify the record yet, so we buffer it for later use. When we do receive the CCS we work through the queue of unprocessed records and process them. Unfortunately the act of processing wipes out any existing packet data that we were still working through. This includes any records from the new epoch that were in the same packet as the CCS. We should only process the buffered records if we've not got any data left. Reviewed-by: Richard Levitte <levitte@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ssl3_get_certificate_request(SSL *s) { int ok, ret = 0; unsigned long n, nc, l; unsigned int llen, ctype_num, i; X509_NAME *xn = NULL; const unsigned char *p, *q; unsigned char *d; STACK_OF(X509_NAME) *ca_sk = NULL; n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A, SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list, &ok); if (!ok) return ((int)n); s->s3->tmp.cert_req = 0; if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) { s->s3->tmp.reuse_message = 1; /* * If we get here we don't need any cached handshake records as we * wont be doing client auth. */ if (s->s3->handshake_buffer) { if (!ssl3_digest_cached_records(s)) goto err; } return (1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_WRONG_MESSAGE_TYPE); goto err; } /* TLS does not like anon-DH with client cert */ if (s->version > SSL3_VERSION) { if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER); goto err; } } p = d = (unsigned char *)s->init_msg; if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE); goto err; } /* get the certificate types */ ctype_num = *(p++); if (ctype_num > SSL3_CT_NUMBER) ctype_num = SSL3_CT_NUMBER; for (i = 0; i < ctype_num; i++) s->s3->tmp.ctype[i] = p[i]; p += ctype_num; if (TLS1_get_version(s) >= TLS1_2_VERSION) { n2s(p, llen); /* * Check we have enough room for signature algorithms and following * length value. */ if ((unsigned long)(p - d + llen + 2) > n) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if ((llen & 1) || !tls1_process_sigalgs(s, p, llen)) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_SIGNATURE_ALGORITHMS_ERROR); goto err; } p += llen; } /* get the CA RDNs */ n2s(p, llen); #if 0 { FILE *out; out = fopen("/tmp/vsign.der", "w"); fwrite(p, 1, llen, out); fclose(out); } #endif if ((unsigned long)(p - d + llen) != n) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH); goto err; } for (nc = 0; nc < llen;) { n2s(p, l); if ((l + nc + 2) > llen) { if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) goto cont; /* netscape bugs */ ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG); goto err; } q = p; if ((xn = d2i_X509_NAME(NULL, &q, l)) == NULL) { /* If netscape tolerance is on, ignore errors */ if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG) goto cont; else { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB); goto err; } } if (q != (p + l)) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_LENGTH_MISMATCH); goto err; } if (!sk_X509_NAME_push(ca_sk, xn)) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE); goto err; } xn = NULL; p += l; nc += l + 2; } if (0) { cont: ERR_clear_error(); } /* we should setup a certificate to return.... */ s->s3->tmp.cert_req = 1; s->s3->tmp.ctype_num = ctype_num; if (s->s3->tmp.ca_names != NULL) sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free); s->s3->tmp.ca_names = ca_sk; ca_sk = NULL; ret = 1; goto done; err: s->state = SSL_ST_ERR; done: X509_NAME_free(xn); if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk, X509_NAME_free); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix small OOB reads. In ssl3_get_client_certificate, ssl3_get_server_certificate and ssl3_get_certificate_request check we have enough room before reading a length. Thanks to Shi Lei (Gear Team, Qihoo 360 Inc.) for reporting these bugs. CVE-2016-6306 Reviewed-by: Richard Levitte <levitte@openssl.org> Reviewed-by: Matt Caswell <matt@openssl.org> (cherry picked from commit ff553f837172ecb2b5c8eca257ec3c5619a4b299)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static unsigned long dtls1_max_handshake_message_len(const SSL *s) { unsigned long max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH; if (max_len < (unsigned long)s->max_cert_list) return s->max_cert_list; return max_len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Excessive allocation of memory in dtls1_preprocess_fragment() This issue is very similar to CVE-2016-6307 described in the previous commit. The underlying defect is different but the security analysis and impacts are the same except that it impacts DTLS. A DTLS message includes 3 bytes for its length in the header for the message. This would allow for messages up to 16Mb in length. Messages of this length are excessive and OpenSSL includes a check to ensure that a peer is sending reasonably sized messages in order to avoid too much memory being consumed to service a connection. A flaw in the logic of version 1.1.0 means that memory for the message is allocated too early, prior to the excessive message length check. Due to way memory is allocated in OpenSSL this could mean an attacker could force up to 21Mb to be allocated to service a connection. This could lead to a Denial of Service through memory exhaustion. However, the excessive message length check still takes place, and this would cause the connection to immediately fail. Assuming that the application calls SSL_free() on the failed conneciton in a timely manner then the 21Mb of allocated memory will then be immediately freed again. Therefore the excessive memory allocation will be transitory in nature. This then means that there is only a security impact if: 1) The application does not call SSL_free() in a timely manner in the event that the connection fails or 2) The application is working in a constrained environment where there is very little free memory or 3) The attacker initiates multiple connection attempts such that there are multiple connections in a state where memory has been allocated for the connection; SSL_free() has not yet been called; and there is insufficient memory to service the multiple requests. Except in the instance of (1) above any Denial Of Service is likely to be transitory because as soon as the connection fails the memory is subsequently freed again in the SSL_free() call. However there is an increased risk during this period of application crashes due to the lack of memory - which would then mean a more serious Denial of Service. This issue does not affect TLS users. Issue was reported by Shi Lei (Gear Team, Qihoo 360 Inc.). CVE-2016-6308 Reviewed-by: Richard Levitte <levitte@openssl.org> (cherry picked from commit 48c054fec3506417b2598837b8062aae7114c200)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint16 bps; tsample_t s; uint8* bufp = (uint8*) buf; if (obuf == NULL) return 1; TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; for (s = 0; s < spp; s++) { if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth, tw, s, 1, spp, bps, dump) > 0) { TIFFError("writeBufferToSeparateTiles", "Unable to extract data to tile for row %lu, col %lu sample %d", (unsigned long) row, (unsigned long)col, (int)s); _TIFFfree(obuf); return 1; } if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError("writeBufferToseparateTiles", "Cannot write tile at %lu %lu sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 1; } } } } _TIFFfree(obuf); return 0; } /* end writeBufferToSeparateTiles */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '* tools/tiffcrop.c: fix multiple uint32 overflows in writeBufferToSeparateStrips(), writeBufferToContigTiles() and writeBufferToSeparateTiles() that could cause heap buffer overflows. Reported by Henri Salo from Nixu Corporation. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2592'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; unsigned char* cp = (unsigned char*) cp0; assert((cc%stride)==0); if (cc > stride) { /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; cc -= 3; cp += 3; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cc -= 3; cp += 3; } } else if (stride == 4) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; unsigned int ca = cp[3]; cc -= 4; cp += 4; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cp[3] = (unsigned char) ((ca += cp[3]) & 0xff); cc -= 4; cp += 4; } } else { cc -= stride; do { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + *cp) & 0xff); cp++) cc -= stride; } while (cc>0); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc) { uint32* wp = (uint32*) cp0; tmsize_t wc = cc / 4; TIFFSwabArrayOfLong(wp, wc); horAcc32(tif, cp0, cc); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint16 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': '* tools/tiffcp.c: fix read of undefined variable in case of missing required tags. Found on test case of MSVR 35100. * tools/tiffcrop.c: fix read of undefined buffer in readContigStripsIntoBuffer() due to uint16 overflow. Probably not a security issue but I can be wrong. Reported as MSVR 35100 by Axel Souchet from the MSRC Vulnerabilities & Mitigations team.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int EC_GROUP_copy(EC_GROUP *dest, const EC_GROUP *src) { EC_EXTRA_DATA *d; if (dest->meth->group_copy == 0) { ECerr(EC_F_EC_GROUP_COPY, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (dest->meth != src->meth) { ECerr(EC_F_EC_GROUP_COPY, EC_R_INCOMPATIBLE_OBJECTS); return 0; } if (dest == src) return 1; EC_EX_DATA_free_all_data(&dest->extra_data); for (d = src->extra_data; d != NULL; d = d->next) { void *t = d->dup_func(d->data); if (t == NULL) return 0; if (!EC_EX_DATA_set_data(&dest->extra_data, t, d->dup_func, d->free_func, d->clear_free_func)) return 0; } if (src->generator != NULL) { if (dest->generator == NULL) { dest->generator = EC_POINT_new(dest); if (dest->generator == NULL) return 0; } if (!EC_POINT_copy(dest->generator, src->generator)) return 0; } else { /* src->generator == NULL */ if (dest->generator != NULL) { EC_POINT_clear_free(dest->generator); dest->generator = NULL; } } if (!BN_copy(&dest->order, &src->order)) return 0; if (!BN_copy(&dest->cofactor, &src->cofactor)) return 0; dest->curve_name = src->curve_name; dest->asn1_flag = src->asn1_flag; dest->asn1_form = src->asn1_form; if (src->seed) { if (dest->seed) OPENSSL_free(dest->seed); dest->seed = OPENSSL_malloc(src->seed_len); if (dest->seed == NULL) return 0; if (!memcpy(dest->seed, src->seed, src->seed_len)) return 0; dest->seed_len = src->seed_len; } else { if (dest->seed) OPENSSL_free(dest->seed); dest->seed = NULL; dest->seed_len = 0; } return dest->meth->group_copy(dest, src); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-320'], 'message': 'Reserve option to use BN_mod_exp_mont_consttime in ECDSA. Submitted by Shay Gueron, Intel Corp. RT: 3149 Reviewed-by: Rich Salz <rsalz@openssl.org> (cherry picked from commit f54be179aa4cbbd944728771d7d59ed588158a12)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); switch(type) { case EVP_CTRL_INIT: if (actx == NULL) actx = ctx->cipher_data = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size()); if (actx == NULL) { EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR); return 0; } actx->len.aad = 0; actx->len.text = 0; actx->aad = 0; actx->mac_inited = 0; actx->tag_len = 0; actx->nonce_len = 12; actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; return 1; case EVP_CTRL_COPY: if (actx) { EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr; dst->cipher_data = OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size()); if (dst->cipher_data == NULL) { EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR); return 0; } } return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0 || arg > CHACHA_CTR_SIZE) return 0; actx->nonce_len = arg; return 1; case EVP_CTRL_AEAD_SET_IV_FIXED: if (arg != 12) return 0; actx->nonce[0] = actx->key.counter[1] = CHACHA_U8TOU32((unsigned char *)ptr); actx->nonce[1] = actx->key.counter[2] = CHACHA_U8TOU32((unsigned char *)ptr+4); actx->nonce[2] = actx->key.counter[3] = CHACHA_U8TOU32((unsigned char *)ptr+8); return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE) return 0; if (ptr != NULL) { memcpy(actx->tag, ptr, arg); actx->tag_len = arg; } return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt) return 0; memcpy(ptr, actx->tag, arg); return 1; case EVP_CTRL_AEAD_TLS1_AAD: if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; { unsigned int len; unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE]; len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 | aad[EVP_AEAD_TLS1_AAD_LEN - 1]; if (!ctx->encrypt) { len -= POLY1305_BLOCK_SIZE; /* discount attached tag */ memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2); aad = temp; temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8); temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len; } actx->tls_payload_length = len; /* * merge record sequence number as per * draft-ietf-tls-chacha20-poly1305-03 */ actx->key.counter[1] = actx->nonce[0]; actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad); actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4); actx->mac_inited = 0; chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN); return POLY1305_BLOCK_SIZE; /* tag length */ } case EVP_CTRL_AEAD_SET_MAC_KEY: /* no-op */ return 1; default: return -1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'crypto/evp: harden AEAD ciphers. Originally a crash in 32-bit build was reported CHACHA20-POLY1305 cipher. The crash is triggered by truncated packet and is result of excessive hashing to the edge of accessible memory. Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Other ciphers were hardened. Thanks to Robert Święcki for report. CVE-2017-3731 Reviewed-by: Rich Salz <rsalz@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al) { #ifndef OPENSSL_NO_DH DH *dh_clnt = NULL; const BIGNUM *pub_key; EVP_PKEY *ckey = NULL, *skey = NULL; skey = s->s3->peer_tmp; if (skey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); return 0; } ckey = ssl_generate_pkey(skey); dh_clnt = EVP_PKEY_get0_DH(ckey); if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); EVP_PKEY_free(ckey); return 0; } /* send off the data */ DH_get0_key(dh_clnt, &pub_key, NULL); *len = BN_num_bytes(pub_key); s2n(*len, *p); BN_bn2bin(pub_key, *p); *len += 2; EVP_PKEY_free(ckey); return 1; #else SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); *al = SSL_AD_INTERNAL_ERROR; return 0; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix missing NULL checks in CKE processing Reviewed-by: Rich Salz <rsalz@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; (void)s; if (sp->libjpeg_jpeg_query_style==0) { if (OJPEGDecodeRaw(tif,buf,cc)==0) return(0); } else { if (OJPEGDecodeScanlines(tif,buf,cc)==0) return(0); } return(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': '* libtiff/tif_ojpeg.c: make OJPEGDecode() early exit in case of failure in OJPEGPreDecode(). This will avoid a divide by zero, and potential other issues. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2611'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TIFFWriteDirectoryTagCheckedRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { static const char module[] = "TIFFWriteDirectoryTagCheckedRationalArray"; uint32* m; float* na; uint32* nb; uint32 nc; int o; assert(sizeof(uint32)==4); m=_TIFFmalloc(count*2*sizeof(uint32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=value, nb=m, nc=0; nc<count; na++, nb+=2, nc++) { if (*na<=0.0) { nb[0]=0; nb[1]=1; } else if (*na==(float)(uint32)(*na)) { nb[0]=(uint32)(*na); nb[1]=1; } else if (*na<1.0) { nb[0]=(uint32)((double)(*na)*0xFFFFFFFF); nb[1]=0xFFFFFFFF; } else { nb[0]=0xFFFFFFFF; nb[1]=(uint32)((double)0xFFFFFFFF/(*na)); } } if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(m,count*2); o=TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_RATIONAL,count,count*8,&m[0]); _TIFFfree(m); return(o); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '* libtiff/tif_dir.c, tif_dirread.c, tif_dirwrite.c: implement various clampings of double to other data types to avoid undefined behaviour if the output range isn't big enough to hold the input value. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2643 http://bugzilla.maptools.org/show_bug.cgi?id=2642 http://bugzilla.maptools.org/show_bug.cgi?id=2646 http://bugzilla.maptools.org/show_bug.cgi?id=2647'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: box_blur_line (gint box_width, gint even_offset, guchar *src, guchar *dest, gint len, gint bpp) { gint i; gint lead; /* This marks the leading edge of the kernel */ gint output; /* This marks the center of the kernel */ gint trail; /* This marks the pixel BEHIND the last 1 in the kernel; it's the pixel to remove from the accumulator. */ gint *ac; /* Accumulator for each channel */ ac = g_new0 (gint, bpp); /* The algorithm differs for even and odd-sized kernels. * With the output at the center, * If odd, the kernel might look like this: 0011100 * If even, the kernel will either be centered on the boundary between * the output and its left neighbor, or on the boundary between the * output and its right neighbor, depending on even_lr. * So it might be 0111100 or 0011110, where output is on the center * of these arrays. */ lead = 0; if (box_width % 2 != 0) { /* Odd-width kernel */ output = lead - (box_width - 1) / 2; trail = lead - box_width; } else { /* Even-width kernel. */ if (even_offset == 1) { /* Right offset */ output = lead + 1 - box_width / 2; trail = lead - box_width; } else if (even_offset == -1) { /* Left offset */ output = lead - box_width / 2; trail = lead - box_width; } else { /* If even_offset isn't 1 or -1, there's some error. */ g_assert_not_reached (); } } /* Initialize accumulator */ for (i = 0; i < bpp; i++) ac[i] = 0; /* As the kernel moves across the image, it has a leading edge and a * trailing edge, and the output is in the middle. */ while (output < len) { /* The number of pixels that are both in the image and * currently covered by the kernel. This is necessary to * handle edge cases. */ guint coverage = (lead < len ? lead : len - 1) - (trail >= 0 ? trail : -1); #ifdef READABLE_BOXBLUR_CODE /* The code here does the same as the code below, but the code below * has been optimized by moving the if statements out of the tight for * loop, and is harder to understand. * Don't use both this code and the code below. */ for (i = 0; i < bpp; i++) { /* If the leading edge of the kernel is still on the image, * add the value there to the accumulator. */ if (lead < len) ac[i] += src[bpp * lead + i]; /* If the trailing edge of the kernel is on the image, * subtract the value there from the accumulator. */ if (trail >= 0) ac[i] -= src[bpp * trail + i]; /* Take the averaged value in the accumulator and store * that value in the output. The number of pixels currently * stored in the accumulator can be less than the nominal * width of the kernel because the kernel can go "over the edge" * of the image. */ if (output >= 0) dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } #endif /* If the leading edge of the kernel is still on the image... */ if (lead < len) { if (trail >= 0) { /* If the trailing edge of the kernel is on the image. (Since * the output is in between the lead and trail, it must be on * the image. */ for (i = 0; i < bpp; i++) { ac[i] += src[bpp * lead + i]; ac[i] -= src[bpp * trail + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else if (output >= 0) { /* If the output is on the image, but the trailing edge isn't yet * on the image. */ for (i = 0; i < bpp; i++) { ac[i] += src[bpp * lead + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else { /* If leading edge is on the image, but the output and trailing * edge aren't yet on the image. */ for (i = 0; i < bpp; i++) ac[i] += src[bpp * lead + i]; } } else if (trail >= 0) { /* If the leading edge has gone off the image, but the output and * trailing edge are on the image. (The big loop exits when the * output goes off the image. */ for (i = 0; i < bpp; i++) { ac[i] -= src[bpp * trail + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else if (output >= 0) { /* Leading has gone off the image and trailing isn't yet in it * (small image) */ for (i = 0; i < bpp; i++) dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } lead++; output++; trail++; } g_free (ac); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'bgo#783835 - Don't divide by zero in box_blur_line() for gaussian blurs We were making the decision to use box blurs, instead of a true Gaussian kernel, based on the size of *both* x and y dimensions. Do them individually instead.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ECDSA_SIG *ossl_ecdsa_sign_sig(const unsigned char *dgst, int dgst_len, const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *eckey) { int ok = 0, i; BIGNUM *kinv = NULL, *s, *m = NULL, *tmp = NULL; const BIGNUM *order, *ckinv; BN_CTX *ctx = NULL; const EC_GROUP *group; ECDSA_SIG *ret; const BIGNUM *priv_key; group = EC_KEY_get0_group(eckey); priv_key = EC_KEY_get0_private_key(eckey); if (group == NULL || priv_key == NULL) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!EC_KEY_can_sign(eckey)) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING); return NULL; } ret = ECDSA_SIG_new(); if (ret == NULL) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE); return NULL; } ret->r = BN_new(); ret->s = BN_new(); if (ret->r == NULL || ret->s == NULL) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE); goto err; } s = ret->s; if ((ctx = BN_CTX_new()) == NULL || (tmp = BN_new()) == NULL || (m = BN_new()) == NULL) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE); goto err; } order = EC_GROUP_get0_order(group); if (order == NULL) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_EC_LIB); goto err; } i = BN_num_bits(order); /* * Need to truncate digest if it is too long: first truncate whole bytes. */ if (8 * dgst_len > i) dgst_len = (i + 7) / 8; if (!BN_bin2bn(dgst, dgst_len, m)) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB); goto err; } /* If still too long truncate remaining bits with a shift */ if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB); goto err; } do { if (in_kinv == NULL || in_r == NULL) { if (!ecdsa_sign_setup(eckey, ctx, &kinv, &ret->r, dgst, dgst_len)) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_ECDSA_LIB); goto err; } ckinv = kinv; } else { ckinv = in_kinv; if (BN_copy(ret->r, in_r) == NULL) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_MALLOC_FAILURE); goto err; } } if (!BN_mod_mul(tmp, priv_key, ret->r, order, ctx)) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB); goto err; } if (!BN_mod_add_quick(s, tmp, m, order)) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB); goto err; } if (!BN_mod_mul(s, s, ckinv, order, ctx)) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, ERR_R_BN_LIB); goto err; } if (BN_is_zero(s)) { /* * if kinv and r have been supplied by the caller don't to * generate new kinv and r values */ if (in_kinv != NULL && in_r != NULL) { ECerr(EC_F_OSSL_ECDSA_SIGN_SIG, EC_R_NEED_NEW_SETUP_VALUES); goto err; } } else /* s != 0 => we have a valid signature */ break; } while (1); ok = 1; err: if (!ok) { ECDSA_SIG_free(ret); ret = NULL; } BN_CTX_free(ctx); BN_clear_free(m); BN_clear_free(tmp); BN_clear_free(kinv); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-203'], 'message': 'Add blinding to an ECDSA signature Keegan Ryan (NCC Group) has demonstrated a side channel attack on an ECDSA signature operation. During signing the signer calculates: s:= k^-1 * (m + r * priv_key) mod order The addition operation above provides a sufficient signal for a flush+reload attack to derive the private key given sufficient signature operations. As a mitigation (based on a suggestion from Keegan) we add blinding to the operation so that: s := k^-1 * blind^-1 (blind * m + blind * r * priv_key) mod order Since this attack is a localhost side channel only no CVE is assigned. Reviewed-by: Rich Salz <rsalz@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { BN_CTX *ctx; BIGNUM k, kq, *K, *kinv = NULL, *r = NULL; int ret = 0; if (!dsa->p || !dsa->q || !dsa->g) { DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS); return 0; } BN_init(&k); BN_init(&kq); if (ctx_in == NULL) { if ((ctx = BN_CTX_new()) == NULL) goto err; } else ctx = ctx_in; if ((r = BN_new()) == NULL) goto err; /* Get random k */ do if (!BN_rand_range(&k, dsa->q)) goto err; while (BN_is_zero(&k)); if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) { BN_set_flags(&k, BN_FLG_CONSTTIME); } if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, CRYPTO_LOCK_DSA, dsa->p, ctx)) goto err; } /* Compute r = (g^k mod p) mod q */ if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) { if (!BN_copy(&kq, &k)) goto err; BN_set_flags(&kq, BN_FLG_CONSTTIME); /* * We do not want timing information to leak the length of k, so we * compute g^k using an equivalent exponent of fixed length. (This * is a kludge that we need because the BN_mod_exp_mont() does not * let us specify the desired timing behaviour.) */ if (!BN_add(&kq, &kq, dsa->q)) goto err; if (BN_num_bits(&kq) <= BN_num_bits(dsa->q)) { if (!BN_add(&kq, &kq, dsa->q)) goto err; } K = &kq; } else { K = &k; } DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx, dsa->method_mont_p); if (!BN_mod(r, r, dsa->q, ctx)) goto err; /* Compute part of 's = inv(k) (m + xr) mod q' */ if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL) goto err; if (*kinvp != NULL) BN_clear_free(*kinvp); *kinvp = kinv; kinv = NULL; if (*rp != NULL) BN_clear_free(*rp); *rp = r; ret = 1; err: if (!ret) { DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB); if (r != NULL) BN_clear_free(r); } if (ctx_in == NULL) BN_CTX_free(ctx); BN_clear_free(&k); BN_clear_free(&kq); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'Address a timing side channel whereby it is possible to determine some information about the length of a value used in DSA operations from a large number of signatures. This doesn't rate as a CVE because: * For the non-constant time code, there are easier ways to extract more information. * For the constant time code, it requires a significant number of signatures to leak a small amount of information. Thanks to Neals Fournaise, Eliane Jaulmes and Jean-Rene Reinhard for reporting this issue. Original commit by Paul Dale. Backported to 1.0.2 by Matt Caswell Reviewed-by: Andy Polyakov <appro@openssl.org> Reviewed-by: Matt Caswell <matt@openssl.org> (Merged from https://github.com/openssl/openssl/pull/4642)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void endElementHandler(void *userData, const char *name) { userdata_t *ud = (userdata_t *) userData; if (strcmp(name, "graph") == 0) { pop_subg(); popString(&ud->elements); ud->closedElementType = TAG_GRAPH; } else if (strcmp(name, "node") == 0) { char *ele_name = topString(ud->elements); if (ud->closedElementType == TAG_GRAPH) { Agnode_t *node = agnode(root, ele_name, 0); agdelete(root, node); } popString(&ud->elements); Current_class = TAG_GRAPH; N = 0; ud->closedElementType = TAG_NODE; } else if (strcmp(name, "edge") == 0) { Current_class = TAG_GRAPH; E = 0; ud->closedElementType = TAG_EDGE; ud->edgeinverted = FALSE; } else if (strcmp(name, "attr") == 0) { char *name; char *value; char buf[SMALLBUF] = GRAPHML_COMP; char *dynbuf = 0; ud->closedElementType = TAG_NONE; if (ud->compositeReadState) { int len = sizeof(GRAPHML_COMP) + agxblen(&ud->xml_attr_name); if (len <= SMALLBUF) { name = buf; } else { name = dynbuf = N_NEW(len, char); strcpy(name, GRAPHML_COMP); } strcpy(name + sizeof(GRAPHML_COMP) - 1, agxbuse(&ud->xml_attr_name)); value = agxbuse(&ud->composite_buffer); agxbclear(&ud->xml_attr_value); ud->compositeReadState = FALSE; } else { name = agxbuse(&ud->xml_attr_name); value = agxbuse(&ud->xml_attr_value); } switch (ud->globalAttrType) { case TAG_NONE: setAttr(name, value, ud); break; case TAG_NODE: setGlobalNodeAttr(G, name, value, ud); break; case TAG_EDGE: setGlobalEdgeAttr(G, name, value, ud); break; case TAG_GRAPH: setGraphAttr(G, name, value, ud); break; } if (dynbuf) free(dynbuf); ud->globalAttrType = TAG_NONE; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'attempted fix for null pointer deference on malformed input'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY *pkey = ktri->pkey; unsigned char *ek = NULL; size_t eklen; int ret = 0; CMS_EncryptedContentInfo *ec; ec = cms->d.envelopedData->encryptedContentInfo; if (ktri->pkey == NULL) { CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY); return 0; } ktri->pctx = EVP_PKEY_CTX_new(pkey, NULL); if (!ktri->pctx) return 0; if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0) goto err; if (!cms_env_asn1_ctrl(ri, 1)) goto err; if (EVP_PKEY_CTX_ctrl(ktri->pctx, -1, EVP_PKEY_OP_DECRYPT, EVP_PKEY_CTRL_CMS_DECRYPT, 0, ri) <= 0) { CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CTRL_ERROR); goto err; } if (EVP_PKEY_decrypt(ktri->pctx, NULL, &eklen, ktri->encryptedKey->data, ktri->encryptedKey->length) <= 0) goto err; ek = OPENSSL_malloc(eklen); if (ek == NULL) { CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, ERR_R_MALLOC_FAILURE); goto err; } if (EVP_PKEY_decrypt(ktri->pctx, ek, &eklen, ktri->encryptedKey->data, ktri->encryptedKey->length) <= 0) { CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CMS_LIB); goto err; } ret = 1; if (ec->key) { OPENSSL_cleanse(ec->key, ec->keylen); OPENSSL_free(ec->key); } ec->key = ek; ec->keylen = eklen; err: if (ktri->pctx) { EVP_PKEY_CTX_free(ktri->pctx); ktri->pctx = NULL; } if (!ret && ek) OPENSSL_free(ek); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'Fix a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey An attack is simple, if the first CMS_recipientInfo is valid but the second CMS_recipientInfo is chosen ciphertext. If the second recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct encryption key will be replaced by garbage, and the message cannot be decoded, but if the RSA decryption fails, the correct encryption key is used and the recipient will not notice the attack. As a work around for this potential attack the length of the decrypted key must be equal to the cipher default key length, in case the certifiate is not given and all recipientInfo are tried out. The old behaviour can be re-enabled in the CMS code by setting the CMS_DEBUG_DECRYPT flag. Reviewed-by: Matt Caswell <matt@openssl.org> (Merged from https://github.com/openssl/openssl/pull/9777) (cherry picked from commit 5840ed0cd1e6487d247efbc1a04136a41d7b3a37)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Context::onDone() { if (wasm_->onDone_) { wasm_->onDone_(this, id_); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '1.4 - Do not call into the VM unless the VM Context has been created. (#24) * Ensure that the in VM Context is created before onDone is called. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Update as per offline discussion. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Set in_vm_context_created_ in onNetworkNewConnection. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Add guards to other network calls. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Fix common/wasm tests. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Patch tests. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Remove unecessary file from cherry-pick. Signed-off-by: John Plevyak <jplevyak@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void Context::onLog() { if (wasm_->onLog_) { wasm_->onLog_(this, id_); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '1.4 - Do not call into the VM unless the VM Context has been created. (#24) * Ensure that the in VM Context is created before onDone is called. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Update as per offline discussion. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Set in_vm_context_created_ in onNetworkNewConnection. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Add guards to other network calls. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Fix common/wasm tests. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Patch tests. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Remove unecessary file from cherry-pick. Signed-off-by: John Plevyak <jplevyak@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rpa_read_buffer(pool_t pool, const unsigned char **data, const unsigned char *end, unsigned char **buffer) { const unsigned char *p = *data; unsigned int len; if (p > end) return 0; len = *p++; if (p + len > end) return 0; *buffer = p_malloc(pool, len); memcpy(*buffer, p, len); *data += 1 + len; return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'auth: mech-rpa - Fail on zero len buffer'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: enhanced_recursion( const char *p, TBOOLEAN brace, char *fontname, double fontsize, double base, TBOOLEAN widthflag, TBOOLEAN showflag, int overprint) { TBOOLEAN wasitalic, wasbold; /* Keep track of the style of the font passed in at this recursion level */ wasitalic = (strstr(fontname, ":Italic") != NULL); wasbold = (strstr(fontname, ":Bold") != NULL); FPRINTF((stderr, "RECURSE WITH \"%s\", %d %s %.1f %.1f %d %d %d", p, brace, fontname, fontsize, base, widthflag, showflag, overprint)); /* Start each recursion with a clean string */ (term->enhanced_flush)(); if (base + fontsize > enhanced_max_height) { enhanced_max_height = base + fontsize; ENH_DEBUG(("Setting max height to %.1f\n", enhanced_max_height)); } if (base < enhanced_min_height) { enhanced_min_height = base; ENH_DEBUG(("Setting min height to %.1f\n", enhanced_min_height)); } while (*p) { double shift; /* * EAM Jun 2009 - treating bytes one at a time does not work for multibyte * encodings, including utf-8. If we hit a byte with the high bit set, test * whether it starts a legal UTF-8 sequence and if so copy the whole thing. * Other multibyte encodings are still a problem. * Gnuplot's other defined encodings are all single-byte; for those we * really do want to treat one byte at a time. */ if ((*p & 0x80) && (encoding == S_ENC_DEFAULT || encoding == S_ENC_UTF8)) { unsigned long utf8char; const char *nextchar = p; (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); if (utf8toulong(&utf8char, &nextchar)) { /* Legal UTF8 sequence */ while (p < nextchar) (term->enhanced_writec)(*p++); p--; } else { /* Some other multibyte encoding? */ (term->enhanced_writec)(*p); } /* shige : for Shift_JIS */ } else if ((*p & 0x80) && (encoding == S_ENC_SJIS)) { (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); (term->enhanced_writec)(*(p++)); (term->enhanced_writec)(*p); } else switch (*p) { case '}' : /*{{{ deal with it*/ if (brace) return (p); int_warn(NO_CARET, "enhanced text parser - spurious }"); break; /*}}}*/ case '_' : case '^' : /*{{{ deal with super/sub script*/ shift = (*p == '^') ? 0.5 : -0.3; (term->enhanced_flush)(); p = enhanced_recursion(p + 1, FALSE, fontname, fontsize * 0.8, base + shift * fontsize, widthflag, showflag, overprint); break; /*}}}*/ case '{' : { TBOOLEAN isitalic = FALSE, isbold = FALSE, isnormal = FALSE; const char *start_of_fontname = NULL; const char *end_of_fontname = NULL; char *localfontname = NULL; char ch; double f = fontsize, ovp; /* Mar 2014 - this will hold "fontfamily{:Italic}{:Bold}" */ char *styledfontname = NULL; /*{{{ recurse (possibly with a new font) */ ENH_DEBUG(("Dealing with {\n")); /* 30 Sep 2016: Remove incorrect whitespace-eating loop going */ /* waaay back to 31-May-2000 */ /* while (*++p == ' '); */ ++p; /* get vertical offset (if present) for overprinted text */ if (overprint == 2) { char *end; ovp = strtod(p,&end); p = end; if (term->flags & TERM_IS_POSTSCRIPT) base = ovp*f; else base += ovp*f; } --p; if (*++p == '/') { /* then parse a fontname, optional fontsize */ while (*++p == ' ') ; /* do nothing */ if (*p=='-') { while (*++p == ' ') ; /* do nothing */ } start_of_fontname = p; /* Allow font name to be in quotes. * This makes it possible to handle font names containing spaces. */ if (*p == '\'' || *p == '"') { ++p; while (*p != '\0' && *p != '}' && *p != *start_of_fontname) ++p; if (*p != *start_of_fontname) { int_warn(NO_CARET, "cannot interpret font name %s", start_of_fontname); p = start_of_fontname; } start_of_fontname++; end_of_fontname = p++; ch = *p; } else { /* Normal unquoted font name */ while ((ch = *p) > ' ' && ch != '=' && ch != '*' && ch != '}' && ch != ':') ++p; end_of_fontname = p; } do { if (ch == '=') { /* get optional font size */ char *end; p++; ENH_DEBUG(("Calling strtod(\"%s\") ...", p)); f = strtod(p, &end); p = end; ENH_DEBUG(("Returned %.1f and \"%s\"\n", f, p)); if (f == 0) f = fontsize; else f *= enhanced_fontscale; /* remember the scaling */ ENH_DEBUG(("Font size %.1f\n", f)); } else if (ch == '*') { /* get optional font size scale factor */ char *end; p++; ENH_DEBUG(("Calling strtod(\"%s\") ...", p)); f = strtod(p, &end); p = end; ENH_DEBUG(("Returned %.1f and \"%s\"\n", f, p)); if (f) f *= fontsize; /* apply the scale factor */ else f = fontsize; ENH_DEBUG(("Font size %.1f\n", f)); } else if (ch == ':') { /* get optional style markup attributes */ p++; if (!strncmp(p,"Bold",4)) isbold = TRUE; if (!strncmp(p,"Italic",6)) isitalic = TRUE; if (!strncmp(p,"Normal",6)) isnormal = TRUE; while (isalpha((unsigned char)*p)) {p++;} } } while (((ch = *p) == '=') || (ch == ':') || (ch == '*')); if (ch == '}') int_warn(NO_CARET,"bad syntax in enhanced text string"); if (*p == ' ') /* Eat up a single space following a font spec */ ++p; if (!start_of_fontname || (start_of_fontname == end_of_fontname)) { /* Use the font name passed in to us */ localfontname = gp_strdup(fontname); } else { /* We found a new font name {/Font ...} */ int len = end_of_fontname - start_of_fontname; localfontname = gp_alloc(len+1,"localfontname"); strncpy(localfontname, start_of_fontname, len); localfontname[len] = '\0'; } } /*}}}*/ /* Collect cumulative style markup before passing it in the font name */ isitalic = (wasitalic || isitalic) && !isnormal; isbold = (wasbold || isbold) && !isnormal; styledfontname = stylefont(localfontname ? localfontname : fontname, isbold, isitalic); p = enhanced_recursion(p, TRUE, styledfontname, f, base, widthflag, showflag, overprint); (term->enhanced_flush)(); free(styledfontname); free(localfontname); break; } /* case '{' */ case '@' : /*{{{ phantom box - prints next 'char', then restores currentpoint */ (term->enhanced_flush)(); (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 3); p = enhanced_recursion(++p, FALSE, fontname, fontsize, base, widthflag, showflag, overprint); (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 4); break; /*}}}*/ case '&' : /*{{{ character skip - skips space equal to length of character(s) */ (term->enhanced_flush)(); p = enhanced_recursion(++p, FALSE, fontname, fontsize, base, widthflag, FALSE, overprint); break; /*}}}*/ case '~' : /*{{{ overprinted text */ /* the second string is overwritten on the first, centered * horizontally on the first and (optionally) vertically * shifted by an amount specified (as a fraction of the * current fontsize) at the beginning of the second string * Note that in this implementation neither the under- nor * overprinted string can contain syntax that would result * in additional recursions -- no subscripts, * superscripts, or anything else, with the exception of a * font definition at the beginning of the text */ (term->enhanced_flush)(); p = enhanced_recursion(++p, FALSE, fontname, fontsize, base, widthflag, showflag, 1); (term->enhanced_flush)(); if (!*p) break; p = enhanced_recursion(++p, FALSE, fontname, fontsize, base, FALSE, showflag, 2); overprint = 0; /* may not be necessary, but just in case . . . */ break; /*}}}*/ case '(' : case ')' : /*{{{ an escape and print it */ /* special cases */ (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); if (term->flags & TERM_IS_POSTSCRIPT) (term->enhanced_writec)('\\'); (term->enhanced_writec)(*p); break; /*}}}*/ case '\\' : /*{{{ various types of escape sequences, some context-dependent */ (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); /* Unicode represented as \U+hhhhh where hhhhh is hexadecimal code point. * For UTF-8 encoding we translate hhhhh to a UTF-8 byte sequence and * output the bytes one by one. */ if (p[1] == 'U' && p[2] == '+') { if (encoding == S_ENC_UTF8) { uint32_t codepoint; unsigned char utf8char[8]; int i, length; sscanf(&(p[3]), "%5x", &codepoint); length = ucs4toutf8(codepoint, utf8char); p += (codepoint > 0xFFFF) ? 7 : 6; for (i=0; i<length; i++) (term->enhanced_writec)(utf8char[i]); break; } /* FIXME: non-utf8 environments not yet supported. * Note that some terminals may have an alternative way to handle unicode * escape sequences that is not dependent on encoding. * E.g. svg and html output could convert to xml sequences &#xhhhh; * For these cases we must retain the leading backslash so that the * unicode escape sequence can be recognized by the terminal driver. */ (term->enhanced_writec)(p[0]); break; } /* Enhanced mode always uses \xyz as an octal character representation * but each terminal type must give us the actual output format wanted. * pdf.trm wants the raw character code, which is why we use strtol(); * most other terminal types want some variant of "\\%o". */ if (p[1] >= '0' && p[1] <= '7') { char *e, escape[16], octal[4] = {'\0','\0','\0','\0'}; octal[0] = *(++p); if (p[1] >= '0' && p[1] <= '7') { octal[1] = *(++p); if (p[1] >= '0' && p[1] <= '7') octal[2] = *(++p); } sprintf(escape, enhanced_escape_format, strtol(octal,NULL,8)); for (e=escape; *e; e++) { (term->enhanced_writec)(*e); } break; } /* This was the original (prior to version 4) enhanced text code specific * to the reserved characters of PostScript. */ if (term->flags & TERM_IS_POSTSCRIPT) { if (p[1]=='\\' || p[1]=='(' || p[1]==')') { (term->enhanced_writec)('\\'); } else if (strchr("^_@&~{}",p[1]) == NULL) { (term->enhanced_writec)('\\'); (term->enhanced_writec)('\\'); break; } } /* Step past the backslash character in the input stream */ ++p; /* HBB: Avoid broken output if there's a \ exactly at the end of the line */ if (*p == '\0') { int_warn(NO_CARET, "enhanced text parser -- spurious backslash"); break; } /* SVG requires an escaped '&' to be passed as something else */ /* FIXME: terminal-dependent code does not belong here */ if (*p == '&' && encoding == S_ENC_DEFAULT && !strcmp(term->name, "svg")) { (term->enhanced_writec)('\376'); break; } /* print the character following the backslash */ (term->enhanced_writec)(*p); break; /*}}}*/ default: /*{{{ print it */ (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); (term->enhanced_writec)(*p); /*}}}*/ } /* switch (*p) */ /* like TeX, we only do one character in a recursion, unless it's * in braces */ if (!brace) { (term->enhanced_flush)(); return(p); /* the ++p in the outer copy will increment us */ } if (*p) /* only not true if { not terminated, I think */ ++p; } /* while (*p) */ (term->enhanced_flush)(); return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Better error handling for faulty font syntax A missing close-quote in an enhanced text font specification could cause a segfault. Bug #2303'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int setup_tests(void) { ADD_ALL_TESTS(call_run_cert, OSSL_NELEM(name_fns)); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Add a test for GENERAL_NAME_cmp Based on a boringssl test contributed by David Benjamin Reviewed-by: Tomas Mraz <tmraz@fedoraproject.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int LibuvStreamWrap::DoWrite(WriteWrap* req_wrap, uv_buf_t* bufs, size_t count, uv_stream_t* send_handle) { LibuvWriteWrap* w = static_cast<LibuvWriteWrap*>(req_wrap); int r; if (send_handle == nullptr) { r = w->Dispatch(uv_write, stream(), bufs, count, AfterUvWrite); } else { r = w->Dispatch(uv_write2, stream(), bufs, count, send_handle, AfterUvWrite); } if (!r) { size_t bytes = 0; for (size_t i = 0; i < count; i++) bytes += bufs[i].len; if (stream()->type == UV_TCP) { NODE_COUNT_NET_BYTES_SENT(bytes); } else if (stream()->type == UV_NAMED_PIPE) { NODE_COUNT_PIPE_BYTES_SENT(bytes); } } return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'src: use unique_ptr for WriteWrap This commit attempts to avoid a use-after-free error by using unqiue_ptr and passing a reference to it. CVE-ID: CVE-2020-8265 Fixes: https://github.com/nodejs-private/node-private/issues/227 PR-URL: https://github.com/nodejs-private/node-private/pull/238 Reviewed-By: Michael Dawson <midawson@redhat.com> Reviewed-By: Tobias Nießen <tniessen@tnie.de> Reviewed-By: Richard Lau <rlau@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned long X509_issuer_and_serial_hash(X509 *a) { unsigned long ret = 0; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); unsigned char md[16]; char *f; if (ctx == NULL) goto err; f = X509_NAME_oneline(a->cert_info.issuer, NULL, 0); if (!EVP_DigestInit_ex(ctx, EVP_md5(), NULL)) goto err; if (!EVP_DigestUpdate(ctx, (unsigned char *)f, strlen(f))) goto err; OPENSSL_free(f); if (!EVP_DigestUpdate (ctx, (unsigned char *)a->cert_info.serialNumber.data, (unsigned long)a->cert_info.serialNumber.length)) goto err; if (!EVP_DigestFinal_ex(ctx, &(md[0]), NULL)) goto err; ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; err: EVP_MD_CTX_free(ctx); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix Null pointer deref in X509_issuer_and_serial_hash() The OpenSSL public API function X509_issuer_and_serial_hash() attempts to create a unique hash value based on the issuer and serial number data contained within an X509 certificate. However it fails to correctly handle any errors that may occur while parsing the issuer field (which might occur if the issuer field is maliciously constructed). This may subsequently result in a NULL pointer deref and a crash leading to a potential denial of service attack. The function X509_issuer_and_serial_hash() is never directly called by OpenSSL itself so applications are only vulnerable if they use this function directly and they use it on certificates that may have been obtained from untrusted sources. CVE-2021-23841 Reviewed-by: Richard Levitte <levitte@openssl.org> Reviewed-by: Paul Dale <pauli@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void save_key_to(const char *algo, const char *name, const char *keydata) { const char *error; struct dict_transaction_context *ctx = dict_transaction_begin(keys_dict); algo = t_str_ucase(algo); dict_set(ctx, t_strconcat(DICT_PATH_SHARED, "default/", algo, "/", name, NULL), keydata); if (dict_transaction_commit(&ctx, &error) < 0) i_error("dict_set(%s) failed: %s", name, error); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'lib-oauth2: Ensure azp is escaped too'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int am_check_url(request_rec *r, const char *url) { const char *i; for (i = url; *i; i++) { if (*i >= 0 && *i < ' ') { /* Deny all control-characters. */ AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r, "Control character detected in URL."); return HTTP_BAD_REQUEST; } if (*i == '\\') { /* Reject backslash character, as it can be used to bypass * redirect URL validation. */ AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r, "Backslash character detected in URL."); return HTTP_BAD_REQUEST; } } return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-601'], 'message': 'Prevent redirect to URLs that begin with '///' Visiting a logout URL like this: https://rp.example.co.jp/mellon/logout?ReturnTo=///fishing-site.example.com/logout.html would have redirected the user to fishing-site.example.com With the patch, this URL would be rejected. Fixes: CVE-2021-3639'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ia5ncasecmp(const char *s1, const char *s2, size_t n) { for (; n > 0; n--, s1++, s2++) { if (*s1 != *s2) { unsigned char c1 = (unsigned char)*s1, c2 = (unsigned char)*s2; /* Convert to lower case */ if (c1 >= 0x41 /* A */ && c1 <= 0x5A /* Z */) c1 += 0x20; if (c2 >= 0x41 /* A */ && c2 <= 0x5A /* Z */) c2 += 0x20; if (c1 == c2) continue; if (c1 < c2) return -1; /* c1 > c2 */ return 1; } else if (*s1 == 0) { /* If we get here we know that *s2 == 0 too */ return 0; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix the name constraints code to not assume NUL terminated strings ASN.1 strings may not be NUL terminated. Don't assume they are. CVE-2021-3712 Reviewed-by: Viktor Dukhovni <viktor@openssl.org> Reviewed-by: Paul Dale <pauli@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static llparse_state_t llhttp__internal__run( llhttp__internal_t* state, const unsigned char* p, const unsigned char* endp) { int match; switch ((llparse_state_t) (intptr_t) state->_current) { case s_n_llhttp__internal__n_closed: s_n_llhttp__internal__n_closed: { if (p == endp) { return s_n_llhttp__internal__n_closed; } p++; goto s_n_llhttp__internal__n_closed; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_llhttp__after_message_complete: s_n_llhttp__internal__n_invoke_llhttp__after_message_complete: { switch (llhttp__after_message_complete(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_invoke_update_finish_2; default: goto s_n_llhttp__internal__n_invoke_update_finish_1; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_pause_1: s_n_llhttp__internal__n_pause_1: { state->error = 0x16; state->reason = "Pause on CONNECT/Upgrade"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__after_message_complete; return s_error; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_is_equal_upgrade: s_n_llhttp__internal__n_invoke_is_equal_upgrade: { switch (llhttp__internal__c_is_equal_upgrade(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_invoke_llhttp__after_message_complete; default: goto s_n_llhttp__internal__n_pause_1; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2: s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2: { switch (llhttp__on_message_complete(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_invoke_is_equal_upgrade; case 21: goto s_n_llhttp__internal__n_pause_5; default: goto s_n_llhttp__internal__n_error_9; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_chunk_data_almost_done_skip: s_n_llhttp__internal__n_chunk_data_almost_done_skip: { if (p == endp) { return s_n_llhttp__internal__n_chunk_data_almost_done_skip; } p++; goto s_n_llhttp__internal__n_invoke_llhttp__on_chunk_complete; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_chunk_data_almost_done: s_n_llhttp__internal__n_chunk_data_almost_done: { if (p == endp) { return s_n_llhttp__internal__n_chunk_data_almost_done; } p++; goto s_n_llhttp__internal__n_chunk_data_almost_done_skip; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_consume_content_length: s_n_llhttp__internal__n_consume_content_length: { size_t avail; uint64_t need; avail = endp - p; need = state->content_length; if (avail >= need) { p += need; state->content_length = 0; goto s_n_llhttp__internal__n_span_end_llhttp__on_body; } state->content_length -= avail; return s_n_llhttp__internal__n_consume_content_length; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_body: s_n_llhttp__internal__n_span_start_llhttp__on_body: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_body; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_body; goto s_n_llhttp__internal__n_consume_content_length; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_is_equal_content_length: s_n_llhttp__internal__n_invoke_is_equal_content_length: { switch (llhttp__internal__c_is_equal_content_length(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_span_start_llhttp__on_body; default: goto s_n_llhttp__internal__n_invoke_or_flags; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_chunk_size_almost_done: s_n_llhttp__internal__n_chunk_size_almost_done: { if (p == endp) { return s_n_llhttp__internal__n_chunk_size_almost_done; } p++; goto s_n_llhttp__internal__n_invoke_llhttp__on_chunk_header; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_chunk_parameters: s_n_llhttp__internal__n_chunk_parameters: { if (p == endp) { return s_n_llhttp__internal__n_chunk_parameters; } switch (*p) { case 13: { p++; goto s_n_llhttp__internal__n_chunk_size_almost_done; } default: { p++; goto s_n_llhttp__internal__n_chunk_parameters; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_chunk_size_otherwise: s_n_llhttp__internal__n_chunk_size_otherwise: { if (p == endp) { return s_n_llhttp__internal__n_chunk_size_otherwise; } switch (*p) { case 13: { p++; goto s_n_llhttp__internal__n_chunk_size_almost_done; } case ' ': { p++; goto s_n_llhttp__internal__n_chunk_parameters; } case ';': { p++; goto s_n_llhttp__internal__n_chunk_parameters; } default: { goto s_n_llhttp__internal__n_error_6; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_chunk_size: s_n_llhttp__internal__n_chunk_size: { if (p == endp) { return s_n_llhttp__internal__n_chunk_size; } switch (*p) { case '0': { p++; match = 0; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '1': { p++; match = 1; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '2': { p++; match = 2; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '3': { p++; match = 3; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '4': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '5': { p++; match = 5; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '6': { p++; match = 6; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '7': { p++; match = 7; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '8': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '9': { p++; match = 9; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'A': { p++; match = 10; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'B': { p++; match = 11; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'C': { p++; match = 12; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'D': { p++; match = 13; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'E': { p++; match = 14; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'F': { p++; match = 15; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'a': { p++; match = 10; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'b': { p++; match = 11; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'c': { p++; match = 12; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'd': { p++; match = 13; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'e': { p++; match = 14; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'f': { p++; match = 15; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } default: { goto s_n_llhttp__internal__n_chunk_size_otherwise; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_chunk_size_digit: s_n_llhttp__internal__n_chunk_size_digit: { if (p == endp) { return s_n_llhttp__internal__n_chunk_size_digit; } switch (*p) { case '0': { p++; match = 0; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '1': { p++; match = 1; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '2': { p++; match = 2; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '3': { p++; match = 3; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '4': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '5': { p++; match = 5; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '6': { p++; match = 6; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '7': { p++; match = 7; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '8': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case '9': { p++; match = 9; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'A': { p++; match = 10; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'B': { p++; match = 11; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'C': { p++; match = 12; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'D': { p++; match = 13; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'E': { p++; match = 14; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'F': { p++; match = 15; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'a': { p++; match = 10; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'b': { p++; match = 11; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'c': { p++; match = 12; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'd': { p++; match = 13; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'e': { p++; match = 14; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } case 'f': { p++; match = 15; goto s_n_llhttp__internal__n_invoke_mul_add_content_length; } default: { goto s_n_llhttp__internal__n_error_8; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_update_content_length: s_n_llhttp__internal__n_invoke_update_content_length: { switch (llhttp__internal__c_update_content_length(state, p, endp)) { default: goto s_n_llhttp__internal__n_chunk_size_digit; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_consume_content_length_1: s_n_llhttp__internal__n_consume_content_length_1: { size_t avail; uint64_t need; avail = endp - p; need = state->content_length; if (avail >= need) { p += need; state->content_length = 0; goto s_n_llhttp__internal__n_span_end_llhttp__on_body_1; } state->content_length -= avail; return s_n_llhttp__internal__n_consume_content_length_1; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_body_1: s_n_llhttp__internal__n_span_start_llhttp__on_body_1: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_body_1; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_body; goto s_n_llhttp__internal__n_consume_content_length_1; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_eof: s_n_llhttp__internal__n_eof: { if (p == endp) { return s_n_llhttp__internal__n_eof; } p++; goto s_n_llhttp__internal__n_eof; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_body_2: s_n_llhttp__internal__n_span_start_llhttp__on_body_2: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_body_2; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_body; goto s_n_llhttp__internal__n_eof; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete: s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete: { switch (llhttp__after_headers_complete(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_1; case 2: goto s_n_llhttp__internal__n_invoke_update_content_length; case 3: goto s_n_llhttp__internal__n_span_start_llhttp__on_body_1; case 4: goto s_n_llhttp__internal__n_invoke_update_finish_3; case 5: goto s_n_llhttp__internal__n_error_10; default: goto s_n_llhttp__internal__n_invoke_llhttp__on_message_complete; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_headers_almost_done: s_n_llhttp__internal__n_headers_almost_done: { if (p == endp) { return s_n_llhttp__internal__n_headers_almost_done; } p++; goto s_n_llhttp__internal__n_invoke_test_flags; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete: s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete: { switch (llhttp__on_header_value_complete(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_field_start; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_header_value: s_n_llhttp__internal__n_span_start_llhttp__on_header_value: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_header_value; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_header_value; goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_discard_lws: s_n_llhttp__internal__n_header_value_discard_lws: { if (p == endp) { return s_n_llhttp__internal__n_header_value_discard_lws; } switch (*p) { case 9: { p++; goto s_n_llhttp__internal__n_header_value_discard_ws; } case ' ': { p++; goto s_n_llhttp__internal__n_header_value_discard_ws; } default: { goto s_n_llhttp__internal__n_invoke_load_header_state; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_discard_ws_almost_done: s_n_llhttp__internal__n_header_value_discard_ws_almost_done: { if (p == endp) { return s_n_llhttp__internal__n_header_value_discard_ws_almost_done; } p++; goto s_n_llhttp__internal__n_header_value_discard_lws; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_lws: s_n_llhttp__internal__n_header_value_lws: { if (p == endp) { return s_n_llhttp__internal__n_header_value_lws; } switch (*p) { case 9: { goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1; } case ' ': { goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1; } default: { goto s_n_llhttp__internal__n_invoke_load_header_state_3; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_almost_done: s_n_llhttp__internal__n_header_value_almost_done: { if (p == endp) { return s_n_llhttp__internal__n_header_value_almost_done; } switch (*p) { case 10: { p++; goto s_n_llhttp__internal__n_header_value_lws; } default: { goto s_n_llhttp__internal__n_error_14; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_lenient: s_n_llhttp__internal__n_header_value_lenient: { if (p == endp) { return s_n_llhttp__internal__n_header_value_lenient; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_1; } case 13: { goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_3; } default: { p++; goto s_n_llhttp__internal__n_header_value_lenient; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_otherwise: s_n_llhttp__internal__n_header_value_otherwise: { if (p == endp) { return s_n_llhttp__internal__n_header_value_otherwise; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_1; } case 13: { goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_2; } default: { goto s_n_llhttp__internal__n_invoke_test_lenient_flags_2; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_connection_token: s_n_llhttp__internal__n_header_value_connection_token: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; if (p == endp) { return s_n_llhttp__internal__n_header_value_connection_token; } switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_header_value_connection_token; } case 2: { p++; goto s_n_llhttp__internal__n_header_value_connection; } default: { goto s_n_llhttp__internal__n_header_value_otherwise; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_connection_ws: s_n_llhttp__internal__n_header_value_connection_ws: { if (p == endp) { return s_n_llhttp__internal__n_header_value_connection_ws; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_header_value_otherwise; } case 13: { goto s_n_llhttp__internal__n_header_value_otherwise; } case ' ': { p++; goto s_n_llhttp__internal__n_header_value_connection_ws; } case ',': { p++; goto s_n_llhttp__internal__n_invoke_load_header_state_4; } default: { goto s_n_llhttp__internal__n_invoke_update_header_state_4; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_connection_1: s_n_llhttp__internal__n_header_value_connection_1: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_value_connection_1; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob3, 4); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_invoke_update_header_state_2; } case kMatchPause: { return s_n_llhttp__internal__n_header_value_connection_1; } case kMatchMismatch: { goto s_n_llhttp__internal__n_header_value_connection_token; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_connection_2: s_n_llhttp__internal__n_header_value_connection_2: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_value_connection_2; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob4, 9); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_invoke_update_header_state_5; } case kMatchPause: { return s_n_llhttp__internal__n_header_value_connection_2; } case kMatchMismatch: { goto s_n_llhttp__internal__n_header_value_connection_token; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_connection_3: s_n_llhttp__internal__n_header_value_connection_3: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_value_connection_3; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob5, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_invoke_update_header_state_6; } case kMatchPause: { return s_n_llhttp__internal__n_header_value_connection_3; } case kMatchMismatch: { goto s_n_llhttp__internal__n_header_value_connection_token; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_connection: s_n_llhttp__internal__n_header_value_connection: { if (p == endp) { return s_n_llhttp__internal__n_header_value_connection; } switch (((*p) >= 'A' && (*p) <= 'Z' ? (*p | 0x20) : (*p))) { case 9: { p++; goto s_n_llhttp__internal__n_header_value_connection; } case ' ': { p++; goto s_n_llhttp__internal__n_header_value_connection; } case 'c': { p++; goto s_n_llhttp__internal__n_header_value_connection_1; } case 'k': { p++; goto s_n_llhttp__internal__n_header_value_connection_2; } case 'u': { p++; goto s_n_llhttp__internal__n_header_value_connection_3; } default: { goto s_n_llhttp__internal__n_header_value_connection_token; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_error_17: s_n_llhttp__internal__n_error_17: { state->error = 0xb; state->reason = "Content-Length overflow"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_error_18: s_n_llhttp__internal__n_error_18: { state->error = 0xb; state->reason = "Invalid character in Content-Length"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_content_length_ws: s_n_llhttp__internal__n_header_value_content_length_ws: { if (p == endp) { return s_n_llhttp__internal__n_header_value_content_length_ws; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_invoke_or_flags_15; } case 13: { goto s_n_llhttp__internal__n_invoke_or_flags_15; } case ' ': { p++; goto s_n_llhttp__internal__n_header_value_content_length_ws; } default: { goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_5; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_content_length: s_n_llhttp__internal__n_header_value_content_length: { if (p == endp) { return s_n_llhttp__internal__n_header_value_content_length; } switch (*p) { case '0': { p++; match = 0; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '1': { p++; match = 1; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '2': { p++; match = 2; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '3': { p++; match = 3; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '4': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '5': { p++; match = 5; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '6': { p++; match = 6; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '7': { p++; match = 7; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '8': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } case '9': { p++; match = 9; goto s_n_llhttp__internal__n_invoke_mul_add_content_length_1; } default: { goto s_n_llhttp__internal__n_header_value_content_length_ws; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_te_chunked_last: s_n_llhttp__internal__n_header_value_te_chunked_last: { if (p == endp) { return s_n_llhttp__internal__n_header_value_te_chunked_last; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_invoke_update_header_state_7; } case 13: { goto s_n_llhttp__internal__n_invoke_update_header_state_7; } case ' ': { p++; goto s_n_llhttp__internal__n_header_value_te_chunked_last; } default: { goto s_n_llhttp__internal__n_header_value_te_chunked; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_te_token_ows: s_n_llhttp__internal__n_header_value_te_token_ows: { if (p == endp) { return s_n_llhttp__internal__n_header_value_te_token_ows; } switch (*p) { case 9: { p++; goto s_n_llhttp__internal__n_header_value_te_token_ows; } case ' ': { p++; goto s_n_llhttp__internal__n_header_value_te_token_ows; } default: { goto s_n_llhttp__internal__n_header_value_te_chunked; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value: s_n_llhttp__internal__n_header_value: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; if (p == endp) { return s_n_llhttp__internal__n_header_value; } #ifdef __SSE4_2__ if (endp - p >= 16) { __m128i ranges; __m128i input; int avail; int match_len; /* Load input */ input = _mm_loadu_si128((__m128i const*) p); ranges = _mm_loadu_si128((__m128i const*) llparse_blob7); /* Find first character that does not match `ranges` */ match_len = _mm_cmpestri(ranges, 6, input, 16, _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES | _SIDD_NEGATIVE_POLARITY); if (match_len != 0) { p += match_len; goto s_n_llhttp__internal__n_header_value; } goto s_n_llhttp__internal__n_header_value_otherwise; } #endif /* __SSE4_2__ */ switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_header_value; } default: { goto s_n_llhttp__internal__n_header_value_otherwise; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_te_token: s_n_llhttp__internal__n_header_value_te_token: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; if (p == endp) { return s_n_llhttp__internal__n_header_value_te_token; } switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_header_value_te_token; } case 2: { p++; goto s_n_llhttp__internal__n_header_value_te_token_ows; } default: { goto s_n_llhttp__internal__n_invoke_update_header_state_8; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_te_chunked: s_n_llhttp__internal__n_header_value_te_chunked: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_value_te_chunked; } match_seq = llparse__match_sequence_to_lower_unsafe(state, p, endp, llparse_blob6, 7); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_header_value_te_chunked_last; } case kMatchPause: { return s_n_llhttp__internal__n_header_value_te_chunked; } case kMatchMismatch: { goto s_n_llhttp__internal__n_header_value_te_token; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1: s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_header_value; goto s_n_llhttp__internal__n_invoke_load_header_state_2; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_value_discard_ws: s_n_llhttp__internal__n_header_value_discard_ws: { if (p == endp) { return s_n_llhttp__internal__n_header_value_discard_ws; } switch (*p) { case 9: { p++; goto s_n_llhttp__internal__n_header_value_discard_ws; } case 10: { p++; goto s_n_llhttp__internal__n_header_value_discard_lws; } case 13: { p++; goto s_n_llhttp__internal__n_header_value_discard_ws_almost_done; } case ' ': { p++; goto s_n_llhttp__internal__n_header_value_discard_ws; } default: { goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value_1; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete: s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete: { switch (llhttp__on_header_field_complete(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_discard_ws; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_general_otherwise: s_n_llhttp__internal__n_header_field_general_otherwise: { if (p == endp) { return s_n_llhttp__internal__n_header_field_general_otherwise; } switch (*p) { case ':': { goto s_n_llhttp__internal__n_span_end_llhttp__on_header_field_1; } default: { goto s_n_llhttp__internal__n_error_19; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_general: s_n_llhttp__internal__n_header_field_general: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; if (p == endp) { return s_n_llhttp__internal__n_header_field_general; } #ifdef __SSE4_2__ if (endp - p >= 16) { __m128i ranges; __m128i input; int avail; int match_len; /* Load input */ input = _mm_loadu_si128((__m128i const*) p); ranges = _mm_loadu_si128((__m128i const*) llparse_blob8); /* Find first character that does not match `ranges` */ match_len = _mm_cmpestri(ranges, 16, input, 16, _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES | _SIDD_NEGATIVE_POLARITY); if (match_len != 0) { p += match_len; goto s_n_llhttp__internal__n_header_field_general; } ranges = _mm_loadu_si128((__m128i const*) llparse_blob9); /* Find first character that does not match `ranges` */ match_len = _mm_cmpestri(ranges, 2, input, 16, _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES | _SIDD_NEGATIVE_POLARITY); if (match_len != 0) { p += match_len; goto s_n_llhttp__internal__n_header_field_general; } goto s_n_llhttp__internal__n_header_field_general_otherwise; } #endif /* __SSE4_2__ */ switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_header_field_general; } default: { goto s_n_llhttp__internal__n_header_field_general_otherwise; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_colon: s_n_llhttp__internal__n_header_field_colon: { if (p == endp) { return s_n_llhttp__internal__n_header_field_colon; } switch (*p) { case ' ': { p++; goto s_n_llhttp__internal__n_header_field_colon; } case ':': { goto s_n_llhttp__internal__n_span_end_llhttp__on_header_field; } default: { goto s_n_llhttp__internal__n_invoke_update_header_state_9; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_3: s_n_llhttp__internal__n_header_field_3: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_field_3; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob2, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 1; goto s_n_llhttp__internal__n_invoke_store_header_state; } case kMatchPause: { return s_n_llhttp__internal__n_header_field_3; } case kMatchMismatch: { goto s_n_llhttp__internal__n_invoke_update_header_state_10; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_4: s_n_llhttp__internal__n_header_field_4: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_field_4; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob10, 10); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 2; goto s_n_llhttp__internal__n_invoke_store_header_state; } case kMatchPause: { return s_n_llhttp__internal__n_header_field_4; } case kMatchMismatch: { goto s_n_llhttp__internal__n_invoke_update_header_state_10; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_2: s_n_llhttp__internal__n_header_field_2: { if (p == endp) { return s_n_llhttp__internal__n_header_field_2; } switch (((*p) >= 'A' && (*p) <= 'Z' ? (*p | 0x20) : (*p))) { case 'n': { p++; goto s_n_llhttp__internal__n_header_field_3; } case 't': { p++; goto s_n_llhttp__internal__n_header_field_4; } default: { goto s_n_llhttp__internal__n_invoke_update_header_state_10; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_1: s_n_llhttp__internal__n_header_field_1: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_field_1; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob1, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_header_field_2; } case kMatchPause: { return s_n_llhttp__internal__n_header_field_1; } case kMatchMismatch: { goto s_n_llhttp__internal__n_invoke_update_header_state_10; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_5: s_n_llhttp__internal__n_header_field_5: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_field_5; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob11, 15); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 1; goto s_n_llhttp__internal__n_invoke_store_header_state; } case kMatchPause: { return s_n_llhttp__internal__n_header_field_5; } case kMatchMismatch: { goto s_n_llhttp__internal__n_invoke_update_header_state_10; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_6: s_n_llhttp__internal__n_header_field_6: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_field_6; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob12, 16); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 3; goto s_n_llhttp__internal__n_invoke_store_header_state; } case kMatchPause: { return s_n_llhttp__internal__n_header_field_6; } case kMatchMismatch: { goto s_n_llhttp__internal__n_invoke_update_header_state_10; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_7: s_n_llhttp__internal__n_header_field_7: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_header_field_7; } match_seq = llparse__match_sequence_to_lower(state, p, endp, llparse_blob13, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 4; goto s_n_llhttp__internal__n_invoke_store_header_state; } case kMatchPause: { return s_n_llhttp__internal__n_header_field_7; } case kMatchMismatch: { goto s_n_llhttp__internal__n_invoke_update_header_state_10; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field: s_n_llhttp__internal__n_header_field: { if (p == endp) { return s_n_llhttp__internal__n_header_field; } switch (((*p) >= 'A' && (*p) <= 'Z' ? (*p | 0x20) : (*p))) { case 'c': { p++; goto s_n_llhttp__internal__n_header_field_1; } case 'p': { p++; goto s_n_llhttp__internal__n_header_field_5; } case 't': { p++; goto s_n_llhttp__internal__n_header_field_6; } case 'u': { p++; goto s_n_llhttp__internal__n_header_field_7; } default: { goto s_n_llhttp__internal__n_invoke_update_header_state_10; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_header_field: s_n_llhttp__internal__n_span_start_llhttp__on_header_field: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_header_field; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_header_field; goto s_n_llhttp__internal__n_header_field; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_header_field_start: s_n_llhttp__internal__n_header_field_start: { if (p == endp) { return s_n_llhttp__internal__n_header_field_start; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_headers_almost_done; } case 13: { p++; goto s_n_llhttp__internal__n_headers_almost_done; } default: { goto s_n_llhttp__internal__n_span_start_llhttp__on_header_field; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_skip_to_http09: s_n_llhttp__internal__n_url_skip_to_http09: { if (p == endp) { return s_n_llhttp__internal__n_url_skip_to_http09; } p++; goto s_n_llhttp__internal__n_invoke_update_http_major; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_skip_lf_to_http09: s_n_llhttp__internal__n_url_skip_lf_to_http09: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_url_skip_lf_to_http09; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob14, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_invoke_update_http_major; } case kMatchPause: { return s_n_llhttp__internal__n_url_skip_lf_to_http09; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_20; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_pri_upgrade: s_n_llhttp__internal__n_req_pri_upgrade: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_req_pri_upgrade; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob16, 10); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_error_23; } case kMatchPause: { return s_n_llhttp__internal__n_req_pri_upgrade; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_24; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_complete_1: s_n_llhttp__internal__n_req_http_complete_1: { if (p == endp) { return s_n_llhttp__internal__n_req_http_complete_1; } switch (*p) { case 10: { p++; goto s_n_llhttp__internal__n_header_field_start; } default: { goto s_n_llhttp__internal__n_error_22; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_complete: s_n_llhttp__internal__n_req_http_complete: { if (p == endp) { return s_n_llhttp__internal__n_req_http_complete; } switch (*p) { case 10: { p++; goto s_n_llhttp__internal__n_header_field_start; } case 13: { p++; goto s_n_llhttp__internal__n_req_http_complete_1; } default: { goto s_n_llhttp__internal__n_error_22; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_minor: s_n_llhttp__internal__n_req_http_minor: { if (p == endp) { return s_n_llhttp__internal__n_req_http_minor; } switch (*p) { case '0': { p++; match = 0; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '1': { p++; match = 1; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '2': { p++; match = 2; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '3': { p++; match = 3; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '4': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '5': { p++; match = 5; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '6': { p++; match = 6; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '7': { p++; match = 7; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '8': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_store_http_minor; } case '9': { p++; match = 9; goto s_n_llhttp__internal__n_invoke_store_http_minor; } default: { goto s_n_llhttp__internal__n_error_25; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_dot: s_n_llhttp__internal__n_req_http_dot: { if (p == endp) { return s_n_llhttp__internal__n_req_http_dot; } switch (*p) { case '.': { p++; goto s_n_llhttp__internal__n_req_http_minor; } default: { goto s_n_llhttp__internal__n_error_26; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_major: s_n_llhttp__internal__n_req_http_major: { if (p == endp) { return s_n_llhttp__internal__n_req_http_major; } switch (*p) { case '0': { p++; match = 0; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '1': { p++; match = 1; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '2': { p++; match = 2; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '3': { p++; match = 3; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '4': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '5': { p++; match = 5; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '6': { p++; match = 6; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '7': { p++; match = 7; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '8': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_store_http_major; } case '9': { p++; match = 9; goto s_n_llhttp__internal__n_invoke_store_http_major; } default: { goto s_n_llhttp__internal__n_error_27; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_start_1: s_n_llhttp__internal__n_req_http_start_1: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_req_http_start_1; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob15, 4); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_invoke_load_method; } case kMatchPause: { return s_n_llhttp__internal__n_req_http_start_1; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_30; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_start_2: s_n_llhttp__internal__n_req_http_start_2: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_req_http_start_2; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob17, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_invoke_load_method_2; } case kMatchPause: { return s_n_llhttp__internal__n_req_http_start_2; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_30; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_start_3: s_n_llhttp__internal__n_req_http_start_3: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_req_http_start_3; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob18, 4); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_invoke_load_method_3; } case kMatchPause: { return s_n_llhttp__internal__n_req_http_start_3; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_30; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_http_start: s_n_llhttp__internal__n_req_http_start: { if (p == endp) { return s_n_llhttp__internal__n_req_http_start; } switch (*p) { case ' ': { p++; goto s_n_llhttp__internal__n_req_http_start; } case 'H': { p++; goto s_n_llhttp__internal__n_req_http_start_1; } case 'I': { p++; goto s_n_llhttp__internal__n_req_http_start_2; } case 'R': { p++; goto s_n_llhttp__internal__n_req_http_start_3; } default: { goto s_n_llhttp__internal__n_error_30; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_skip_to_http: s_n_llhttp__internal__n_url_skip_to_http: { if (p == endp) { return s_n_llhttp__internal__n_url_skip_to_http; } p++; goto s_n_llhttp__internal__n_invoke_llhttp__on_url_complete_1; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_fragment: s_n_llhttp__internal__n_url_fragment: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; if (p == endp) { return s_n_llhttp__internal__n_url_fragment; } switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_url_fragment; } case 2: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_6; } case 3: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_7; } case 4: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_8; } default: { goto s_n_llhttp__internal__n_error_31; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_end_stub_query_3: s_n_llhttp__internal__n_span_end_stub_query_3: { if (p == endp) { return s_n_llhttp__internal__n_span_end_stub_query_3; } p++; goto s_n_llhttp__internal__n_url_fragment; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_query: s_n_llhttp__internal__n_url_query: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; if (p == endp) { return s_n_llhttp__internal__n_url_query; } switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_url_query; } case 2: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_9; } case 3: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_10; } case 4: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_11; } case 5: { goto s_n_llhttp__internal__n_span_end_stub_query_3; } default: { goto s_n_llhttp__internal__n_error_32; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_query_or_fragment: s_n_llhttp__internal__n_url_query_or_fragment: { if (p == endp) { return s_n_llhttp__internal__n_url_query_or_fragment; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_3; } case 13: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_4; } case ' ': { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_5; } case '#': { p++; goto s_n_llhttp__internal__n_url_fragment; } case '?': { p++; goto s_n_llhttp__internal__n_url_query; } default: { goto s_n_llhttp__internal__n_error_33; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_path: s_n_llhttp__internal__n_url_path: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; if (p == endp) { return s_n_llhttp__internal__n_url_path; } #ifdef __SSE4_2__ if (endp - p >= 16) { __m128i ranges; __m128i input; int avail; int match_len; /* Load input */ input = _mm_loadu_si128((__m128i const*) p); ranges = _mm_loadu_si128((__m128i const*) llparse_blob0); /* Find first character that does not match `ranges` */ match_len = _mm_cmpestri(ranges, 12, input, 16, _SIDD_UBYTE_OPS | _SIDD_CMP_RANGES | _SIDD_NEGATIVE_POLARITY); if (match_len != 0) { p += match_len; goto s_n_llhttp__internal__n_url_path; } goto s_n_llhttp__internal__n_url_query_or_fragment; } #endif /* __SSE4_2__ */ switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_url_path; } default: { goto s_n_llhttp__internal__n_url_query_or_fragment; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_stub_path_2: s_n_llhttp__internal__n_span_start_stub_path_2: { if (p == endp) { return s_n_llhttp__internal__n_span_start_stub_path_2; } p++; goto s_n_llhttp__internal__n_url_path; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_stub_path: s_n_llhttp__internal__n_span_start_stub_path: { if (p == endp) { return s_n_llhttp__internal__n_span_start_stub_path; } p++; goto s_n_llhttp__internal__n_url_path; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_stub_path_1: s_n_llhttp__internal__n_span_start_stub_path_1: { if (p == endp) { return s_n_llhttp__internal__n_span_start_stub_path_1; } p++; goto s_n_llhttp__internal__n_url_path; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_server_with_at: s_n_llhttp__internal__n_url_server_with_at: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 0, 6, 7, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 0, 4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; if (p == endp) { return s_n_llhttp__internal__n_url_server_with_at; } switch (lookup_table[(uint8_t) *p]) { case 1: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_12; } case 2: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_13; } case 3: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_14; } case 4: { p++; goto s_n_llhttp__internal__n_url_server; } case 5: { goto s_n_llhttp__internal__n_span_start_stub_path_1; } case 6: { p++; goto s_n_llhttp__internal__n_url_query; } case 7: { p++; goto s_n_llhttp__internal__n_error_34; } default: { goto s_n_llhttp__internal__n_error_35; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_server: s_n_llhttp__internal__n_url_server: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 0, 6, 7, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 0, 4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; if (p == endp) { return s_n_llhttp__internal__n_url_server; } switch (lookup_table[(uint8_t) *p]) { case 1: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url; } case 2: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_1; } case 3: { goto s_n_llhttp__internal__n_span_end_llhttp__on_url_2; } case 4: { p++; goto s_n_llhttp__internal__n_url_server; } case 5: { goto s_n_llhttp__internal__n_span_start_stub_path; } case 6: { p++; goto s_n_llhttp__internal__n_url_query; } case 7: { p++; goto s_n_llhttp__internal__n_url_server_with_at; } default: { goto s_n_llhttp__internal__n_error_36; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_schema_delim_1: s_n_llhttp__internal__n_url_schema_delim_1: { if (p == endp) { return s_n_llhttp__internal__n_url_schema_delim_1; } switch (*p) { case '/': { p++; goto s_n_llhttp__internal__n_url_server; } default: { goto s_n_llhttp__internal__n_error_38; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_schema_delim: s_n_llhttp__internal__n_url_schema_delim: { if (p == endp) { return s_n_llhttp__internal__n_url_schema_delim; } switch (*p) { case 10: { p++; goto s_n_llhttp__internal__n_error_37; } case 13: { p++; goto s_n_llhttp__internal__n_error_37; } case ' ': { p++; goto s_n_llhttp__internal__n_error_37; } case '/': { p++; goto s_n_llhttp__internal__n_url_schema_delim_1; } default: { goto s_n_llhttp__internal__n_error_38; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_end_stub_schema: s_n_llhttp__internal__n_span_end_stub_schema: { if (p == endp) { return s_n_llhttp__internal__n_span_end_stub_schema; } p++; goto s_n_llhttp__internal__n_url_schema_delim; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_schema: s_n_llhttp__internal__n_url_schema: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; if (p == endp) { return s_n_llhttp__internal__n_url_schema; } switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_error_37; } case 2: { goto s_n_llhttp__internal__n_span_end_stub_schema; } case 3: { p++; goto s_n_llhttp__internal__n_url_schema; } default: { goto s_n_llhttp__internal__n_error_39; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_url_start: s_n_llhttp__internal__n_url_start: { static uint8_t lookup_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; if (p == endp) { return s_n_llhttp__internal__n_url_start; } switch (lookup_table[(uint8_t) *p]) { case 1: { p++; goto s_n_llhttp__internal__n_error_37; } case 2: { goto s_n_llhttp__internal__n_span_start_stub_path_2; } case 3: { goto s_n_llhttp__internal__n_url_schema; } default: { goto s_n_llhttp__internal__n_error_40; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_url_1: s_n_llhttp__internal__n_span_start_llhttp__on_url_1: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_url_1; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_url; goto s_n_llhttp__internal__n_url_start; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_url: s_n_llhttp__internal__n_span_start_llhttp__on_url: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_url; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_url; goto s_n_llhttp__internal__n_url_server; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_spaces_before_url: s_n_llhttp__internal__n_req_spaces_before_url: { if (p == endp) { return s_n_llhttp__internal__n_req_spaces_before_url; } switch (*p) { case ' ': { p++; goto s_n_llhttp__internal__n_req_spaces_before_url; } default: { goto s_n_llhttp__internal__n_invoke_is_equal_method; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_first_space_before_url: s_n_llhttp__internal__n_req_first_space_before_url: { if (p == endp) { return s_n_llhttp__internal__n_req_first_space_before_url; } switch (*p) { case ' ': { p++; goto s_n_llhttp__internal__n_req_spaces_before_url; } default: { goto s_n_llhttp__internal__n_error_41; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_2: s_n_llhttp__internal__n_start_req_2: { if (p == endp) { return s_n_llhttp__internal__n_start_req_2; } switch (*p) { case 'L': { p++; match = 19; goto s_n_llhttp__internal__n_invoke_store_method_1; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_3: s_n_llhttp__internal__n_start_req_3: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_3; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob19, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 36; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_3; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_1: s_n_llhttp__internal__n_start_req_1: { if (p == endp) { return s_n_llhttp__internal__n_start_req_1; } switch (*p) { case 'C': { p++; goto s_n_llhttp__internal__n_start_req_2; } case 'N': { p++; goto s_n_llhttp__internal__n_start_req_3; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_4: s_n_llhttp__internal__n_start_req_4: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_4; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob20, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 16; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_4; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_6: s_n_llhttp__internal__n_start_req_6: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_6; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob21, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 22; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_6; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_8: s_n_llhttp__internal__n_start_req_8: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_8; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob22, 4); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 5; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_8; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_9: s_n_llhttp__internal__n_start_req_9: { if (p == endp) { return s_n_llhttp__internal__n_start_req_9; } switch (*p) { case 'Y': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_store_method_1; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_7: s_n_llhttp__internal__n_start_req_7: { if (p == endp) { return s_n_llhttp__internal__n_start_req_7; } switch (*p) { case 'N': { p++; goto s_n_llhttp__internal__n_start_req_8; } case 'P': { p++; goto s_n_llhttp__internal__n_start_req_9; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_5: s_n_llhttp__internal__n_start_req_5: { if (p == endp) { return s_n_llhttp__internal__n_start_req_5; } switch (*p) { case 'H': { p++; goto s_n_llhttp__internal__n_start_req_6; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_7; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_12: s_n_llhttp__internal__n_start_req_12: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_12; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob23, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 0; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_12; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_13: s_n_llhttp__internal__n_start_req_13: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_13; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob24, 5); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 35; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_13; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_11: s_n_llhttp__internal__n_start_req_11: { if (p == endp) { return s_n_llhttp__internal__n_start_req_11; } switch (*p) { case 'L': { p++; goto s_n_llhttp__internal__n_start_req_12; } case 'S': { p++; goto s_n_llhttp__internal__n_start_req_13; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_10: s_n_llhttp__internal__n_start_req_10: { if (p == endp) { return s_n_llhttp__internal__n_start_req_10; } switch (*p) { case 'E': { p++; goto s_n_llhttp__internal__n_start_req_11; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_14: s_n_llhttp__internal__n_start_req_14: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_14; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob25, 4); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 45; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_14; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_17: s_n_llhttp__internal__n_start_req_17: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_17; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob27, 9); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 41; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_17; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_16: s_n_llhttp__internal__n_start_req_16: { if (p == endp) { return s_n_llhttp__internal__n_start_req_16; } switch (*p) { case '_': { p++; goto s_n_llhttp__internal__n_start_req_17; } default: { match = 1; goto s_n_llhttp__internal__n_invoke_store_method_1; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_15: s_n_llhttp__internal__n_start_req_15: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_15; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob26, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_start_req_16; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_15; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_18: s_n_llhttp__internal__n_start_req_18: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_18; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob28, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 2; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_18; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_20: s_n_llhttp__internal__n_start_req_20: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_20; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob29, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 31; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_20; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_21: s_n_llhttp__internal__n_start_req_21: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_21; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob30, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 9; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_21; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_19: s_n_llhttp__internal__n_start_req_19: { if (p == endp) { return s_n_llhttp__internal__n_start_req_19; } switch (*p) { case 'I': { p++; goto s_n_llhttp__internal__n_start_req_20; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_21; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_23: s_n_llhttp__internal__n_start_req_23: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_23; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob31, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 24; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_23; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_24: s_n_llhttp__internal__n_start_req_24: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_24; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob32, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 23; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_24; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_26: s_n_llhttp__internal__n_start_req_26: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_26; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob33, 7); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 21; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_26; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_28: s_n_llhttp__internal__n_start_req_28: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_28; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob34, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 30; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_28; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_29: s_n_llhttp__internal__n_start_req_29: { if (p == endp) { return s_n_llhttp__internal__n_start_req_29; } switch (*p) { case 'L': { p++; match = 10; goto s_n_llhttp__internal__n_invoke_store_method_1; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_27: s_n_llhttp__internal__n_start_req_27: { if (p == endp) { return s_n_llhttp__internal__n_start_req_27; } switch (*p) { case 'A': { p++; goto s_n_llhttp__internal__n_start_req_28; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_29; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_25: s_n_llhttp__internal__n_start_req_25: { if (p == endp) { return s_n_llhttp__internal__n_start_req_25; } switch (*p) { case 'A': { p++; goto s_n_llhttp__internal__n_start_req_26; } case 'C': { p++; goto s_n_llhttp__internal__n_start_req_27; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_30: s_n_llhttp__internal__n_start_req_30: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_30; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob35, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 11; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_30; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_22: s_n_llhttp__internal__n_start_req_22: { if (p == endp) { return s_n_llhttp__internal__n_start_req_22; } switch (*p) { case '-': { p++; goto s_n_llhttp__internal__n_start_req_23; } case 'E': { p++; goto s_n_llhttp__internal__n_start_req_24; } case 'K': { p++; goto s_n_llhttp__internal__n_start_req_25; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_30; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_31: s_n_llhttp__internal__n_start_req_31: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_31; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob36, 5); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 25; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_31; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_32: s_n_llhttp__internal__n_start_req_32: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_32; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob37, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 6; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_32; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_35: s_n_llhttp__internal__n_start_req_35: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_35; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob38, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 28; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_35; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_36: s_n_llhttp__internal__n_start_req_36: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_36; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob39, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 39; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_36; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_34: s_n_llhttp__internal__n_start_req_34: { if (p == endp) { return s_n_llhttp__internal__n_start_req_34; } switch (*p) { case 'T': { p++; goto s_n_llhttp__internal__n_start_req_35; } case 'U': { p++; goto s_n_llhttp__internal__n_start_req_36; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_37: s_n_llhttp__internal__n_start_req_37: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_37; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob40, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 38; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_37; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_38: s_n_llhttp__internal__n_start_req_38: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_38; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob41, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 3; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_38; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_42: s_n_llhttp__internal__n_start_req_42: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_42; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob42, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 12; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_42; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_43: s_n_llhttp__internal__n_start_req_43: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_43; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob43, 4); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 13; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_43; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_41: s_n_llhttp__internal__n_start_req_41: { if (p == endp) { return s_n_llhttp__internal__n_start_req_41; } switch (*p) { case 'F': { p++; goto s_n_llhttp__internal__n_start_req_42; } case 'P': { p++; goto s_n_llhttp__internal__n_start_req_43; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_40: s_n_llhttp__internal__n_start_req_40: { if (p == endp) { return s_n_llhttp__internal__n_start_req_40; } switch (*p) { case 'P': { p++; goto s_n_llhttp__internal__n_start_req_41; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_39: s_n_llhttp__internal__n_start_req_39: { if (p == endp) { return s_n_llhttp__internal__n_start_req_39; } switch (*p) { case 'I': { p++; match = 34; goto s_n_llhttp__internal__n_invoke_store_method_1; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_40; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_45: s_n_llhttp__internal__n_start_req_45: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_45; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob44, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 29; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_45; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_44: s_n_llhttp__internal__n_start_req_44: { if (p == endp) { return s_n_llhttp__internal__n_start_req_44; } switch (*p) { case 'R': { p++; goto s_n_llhttp__internal__n_start_req_45; } case 'T': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_store_method_1; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_33: s_n_llhttp__internal__n_start_req_33: { if (p == endp) { return s_n_llhttp__internal__n_start_req_33; } switch (*p) { case 'A': { p++; goto s_n_llhttp__internal__n_start_req_34; } case 'L': { p++; goto s_n_llhttp__internal__n_start_req_37; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_38; } case 'R': { p++; goto s_n_llhttp__internal__n_start_req_39; } case 'U': { p++; goto s_n_llhttp__internal__n_start_req_44; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_48: s_n_llhttp__internal__n_start_req_48: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_48; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob45, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 17; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_48; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_49: s_n_llhttp__internal__n_start_req_49: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_49; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob46, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 44; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_49; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_50: s_n_llhttp__internal__n_start_req_50: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_50; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob47, 5); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 43; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_50; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_51: s_n_llhttp__internal__n_start_req_51: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_51; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob48, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 20; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_51; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_47: s_n_llhttp__internal__n_start_req_47: { if (p == endp) { return s_n_llhttp__internal__n_start_req_47; } switch (*p) { case 'B': { p++; goto s_n_llhttp__internal__n_start_req_48; } case 'C': { p++; goto s_n_llhttp__internal__n_start_req_49; } case 'D': { p++; goto s_n_llhttp__internal__n_start_req_50; } case 'P': { p++; goto s_n_llhttp__internal__n_start_req_51; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_46: s_n_llhttp__internal__n_start_req_46: { if (p == endp) { return s_n_llhttp__internal__n_start_req_46; } switch (*p) { case 'E': { p++; goto s_n_llhttp__internal__n_start_req_47; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_54: s_n_llhttp__internal__n_start_req_54: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_54; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob49, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 14; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_54; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_56: s_n_llhttp__internal__n_start_req_56: { if (p == endp) { return s_n_llhttp__internal__n_start_req_56; } switch (*p) { case 'P': { p++; match = 37; goto s_n_llhttp__internal__n_invoke_store_method_1; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_57: s_n_llhttp__internal__n_start_req_57: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_57; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob50, 9); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 42; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_57; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_55: s_n_llhttp__internal__n_start_req_55: { if (p == endp) { return s_n_llhttp__internal__n_start_req_55; } switch (*p) { case 'U': { p++; goto s_n_llhttp__internal__n_start_req_56; } case '_': { p++; goto s_n_llhttp__internal__n_start_req_57; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_53: s_n_llhttp__internal__n_start_req_53: { if (p == endp) { return s_n_llhttp__internal__n_start_req_53; } switch (*p) { case 'A': { p++; goto s_n_llhttp__internal__n_start_req_54; } case 'T': { p++; goto s_n_llhttp__internal__n_start_req_55; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_58: s_n_llhttp__internal__n_start_req_58: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_58; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob51, 4); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 33; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_58; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_59: s_n_llhttp__internal__n_start_req_59: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_59; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob52, 7); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 26; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_59; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_52: s_n_llhttp__internal__n_start_req_52: { if (p == endp) { return s_n_llhttp__internal__n_start_req_52; } switch (*p) { case 'E': { p++; goto s_n_llhttp__internal__n_start_req_53; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_58; } case 'U': { p++; goto s_n_llhttp__internal__n_start_req_59; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_61: s_n_llhttp__internal__n_start_req_61: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_61; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob53, 6); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 40; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_61; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_62: s_n_llhttp__internal__n_start_req_62: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_62; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob54, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 7; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_62; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_60: s_n_llhttp__internal__n_start_req_60: { if (p == endp) { return s_n_llhttp__internal__n_start_req_60; } switch (*p) { case 'E': { p++; goto s_n_llhttp__internal__n_start_req_61; } case 'R': { p++; goto s_n_llhttp__internal__n_start_req_62; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_65: s_n_llhttp__internal__n_start_req_65: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_65; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob55, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 18; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_65; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_67: s_n_llhttp__internal__n_start_req_67: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_67; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob56, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 32; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_67; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_68: s_n_llhttp__internal__n_start_req_68: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_68; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob57, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 15; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_68; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_66: s_n_llhttp__internal__n_start_req_66: { if (p == endp) { return s_n_llhttp__internal__n_start_req_66; } switch (*p) { case 'I': { p++; goto s_n_llhttp__internal__n_start_req_67; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_68; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_69: s_n_llhttp__internal__n_start_req_69: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_req_69; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob58, 8); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 27; goto s_n_llhttp__internal__n_invoke_store_method_1; } case kMatchPause: { return s_n_llhttp__internal__n_start_req_69; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_64: s_n_llhttp__internal__n_start_req_64: { if (p == endp) { return s_n_llhttp__internal__n_start_req_64; } switch (*p) { case 'B': { p++; goto s_n_llhttp__internal__n_start_req_65; } case 'L': { p++; goto s_n_llhttp__internal__n_start_req_66; } case 'S': { p++; goto s_n_llhttp__internal__n_start_req_69; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_63: s_n_llhttp__internal__n_start_req_63: { if (p == endp) { return s_n_llhttp__internal__n_start_req_63; } switch (*p) { case 'N': { p++; goto s_n_llhttp__internal__n_start_req_64; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req: s_n_llhttp__internal__n_start_req: { if (p == endp) { return s_n_llhttp__internal__n_start_req; } switch (*p) { case 'A': { p++; goto s_n_llhttp__internal__n_start_req_1; } case 'B': { p++; goto s_n_llhttp__internal__n_start_req_4; } case 'C': { p++; goto s_n_llhttp__internal__n_start_req_5; } case 'D': { p++; goto s_n_llhttp__internal__n_start_req_10; } case 'F': { p++; goto s_n_llhttp__internal__n_start_req_14; } case 'G': { p++; goto s_n_llhttp__internal__n_start_req_15; } case 'H': { p++; goto s_n_llhttp__internal__n_start_req_18; } case 'L': { p++; goto s_n_llhttp__internal__n_start_req_19; } case 'M': { p++; goto s_n_llhttp__internal__n_start_req_22; } case 'N': { p++; goto s_n_llhttp__internal__n_start_req_31; } case 'O': { p++; goto s_n_llhttp__internal__n_start_req_32; } case 'P': { p++; goto s_n_llhttp__internal__n_start_req_33; } case 'R': { p++; goto s_n_llhttp__internal__n_start_req_46; } case 'S': { p++; goto s_n_llhttp__internal__n_start_req_52; } case 'T': { p++; goto s_n_llhttp__internal__n_start_req_60; } case 'U': { p++; goto s_n_llhttp__internal__n_start_req_63; } default: { goto s_n_llhttp__internal__n_error_49; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_llhttp__on_status_complete: s_n_llhttp__internal__n_invoke_llhttp__on_status_complete: { switch (llhttp__on_status_complete(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_field_start; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_line_almost_done: s_n_llhttp__internal__n_res_line_almost_done: { if (p == endp) { return s_n_llhttp__internal__n_res_line_almost_done; } p++; goto s_n_llhttp__internal__n_invoke_llhttp__on_status_complete; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_status: s_n_llhttp__internal__n_res_status: { if (p == endp) { return s_n_llhttp__internal__n_res_status; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_span_end_llhttp__on_status; } case 13: { goto s_n_llhttp__internal__n_span_end_llhttp__on_status_1; } default: { p++; goto s_n_llhttp__internal__n_res_status; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_span_start_llhttp__on_status: s_n_llhttp__internal__n_span_start_llhttp__on_status: { if (p == endp) { return s_n_llhttp__internal__n_span_start_llhttp__on_status; } state->_span_pos0 = (void*) p; state->_span_cb0 = llhttp__on_status; goto s_n_llhttp__internal__n_res_status; /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_status_start: s_n_llhttp__internal__n_res_status_start: { if (p == endp) { return s_n_llhttp__internal__n_res_status_start; } switch (*p) { case 10: { p++; goto s_n_llhttp__internal__n_invoke_llhttp__on_status_complete; } case 13: { p++; goto s_n_llhttp__internal__n_res_line_almost_done; } default: { goto s_n_llhttp__internal__n_span_start_llhttp__on_status; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_status_code_otherwise: s_n_llhttp__internal__n_res_status_code_otherwise: { if (p == endp) { return s_n_llhttp__internal__n_res_status_code_otherwise; } switch (*p) { case 10: { goto s_n_llhttp__internal__n_res_status_start; } case 13: { goto s_n_llhttp__internal__n_res_status_start; } case ' ': { p++; goto s_n_llhttp__internal__n_res_status_start; } default: { goto s_n_llhttp__internal__n_error_43; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_status_code: s_n_llhttp__internal__n_res_status_code: { if (p == endp) { return s_n_llhttp__internal__n_res_status_code; } switch (*p) { case '0': { p++; match = 0; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '1': { p++; match = 1; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '2': { p++; match = 2; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '3': { p++; match = 3; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '4': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '5': { p++; match = 5; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '6': { p++; match = 6; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '7': { p++; match = 7; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '8': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } case '9': { p++; match = 9; goto s_n_llhttp__internal__n_invoke_mul_add_status_code; } default: { goto s_n_llhttp__internal__n_res_status_code_otherwise; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_http_end: s_n_llhttp__internal__n_res_http_end: { if (p == endp) { return s_n_llhttp__internal__n_res_http_end; } switch (*p) { case ' ': { p++; goto s_n_llhttp__internal__n_invoke_update_status_code; } default: { goto s_n_llhttp__internal__n_error_44; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_http_minor: s_n_llhttp__internal__n_res_http_minor: { if (p == endp) { return s_n_llhttp__internal__n_res_http_minor; } switch (*p) { case '0': { p++; match = 0; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '1': { p++; match = 1; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '2': { p++; match = 2; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '3': { p++; match = 3; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '4': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '5': { p++; match = 5; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '6': { p++; match = 6; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '7': { p++; match = 7; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '8': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } case '9': { p++; match = 9; goto s_n_llhttp__internal__n_invoke_store_http_minor_1; } default: { goto s_n_llhttp__internal__n_error_45; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_http_dot: s_n_llhttp__internal__n_res_http_dot: { if (p == endp) { return s_n_llhttp__internal__n_res_http_dot; } switch (*p) { case '.': { p++; goto s_n_llhttp__internal__n_res_http_minor; } default: { goto s_n_llhttp__internal__n_error_46; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_res_http_major: s_n_llhttp__internal__n_res_http_major: { if (p == endp) { return s_n_llhttp__internal__n_res_http_major; } switch (*p) { case '0': { p++; match = 0; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '1': { p++; match = 1; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '2': { p++; match = 2; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '3': { p++; match = 3; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '4': { p++; match = 4; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '5': { p++; match = 5; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '6': { p++; match = 6; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '7': { p++; match = 7; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '8': { p++; match = 8; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } case '9': { p++; match = 9; goto s_n_llhttp__internal__n_invoke_store_http_major_1; } default: { goto s_n_llhttp__internal__n_error_47; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_res: s_n_llhttp__internal__n_start_res: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_start_res; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob59, 5); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_res_http_major; } case kMatchPause: { return s_n_llhttp__internal__n_start_res; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_50; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_or_res_method_2: s_n_llhttp__internal__n_req_or_res_method_2: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_req_or_res_method_2; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob60, 2); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; match = 2; goto s_n_llhttp__internal__n_invoke_store_method; } case kMatchPause: { return s_n_llhttp__internal__n_req_or_res_method_2; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_48; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_or_res_method_3: s_n_llhttp__internal__n_req_or_res_method_3: { llparse_match_t match_seq; if (p == endp) { return s_n_llhttp__internal__n_req_or_res_method_3; } match_seq = llparse__match_sequence_id(state, p, endp, llparse_blob61, 3); p = match_seq.current; switch (match_seq.status) { case kMatchComplete: { p++; goto s_n_llhttp__internal__n_invoke_update_type_1; } case kMatchPause: { return s_n_llhttp__internal__n_req_or_res_method_3; } case kMatchMismatch: { goto s_n_llhttp__internal__n_error_48; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_or_res_method_1: s_n_llhttp__internal__n_req_or_res_method_1: { if (p == endp) { return s_n_llhttp__internal__n_req_or_res_method_1; } switch (*p) { case 'E': { p++; goto s_n_llhttp__internal__n_req_or_res_method_2; } case 'T': { p++; goto s_n_llhttp__internal__n_req_or_res_method_3; } default: { goto s_n_llhttp__internal__n_error_48; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_req_or_res_method: s_n_llhttp__internal__n_req_or_res_method: { if (p == endp) { return s_n_llhttp__internal__n_req_or_res_method; } switch (*p) { case 'H': { p++; goto s_n_llhttp__internal__n_req_or_res_method_1; } default: { goto s_n_llhttp__internal__n_error_48; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start_req_or_res: s_n_llhttp__internal__n_start_req_or_res: { if (p == endp) { return s_n_llhttp__internal__n_start_req_or_res; } switch (*p) { case 'H': { goto s_n_llhttp__internal__n_req_or_res_method; } default: { goto s_n_llhttp__internal__n_invoke_update_type_2; } } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_invoke_load_type: s_n_llhttp__internal__n_invoke_load_type: { switch (llhttp__internal__c_load_type(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_start_req; case 2: goto s_n_llhttp__internal__n_start_res; default: goto s_n_llhttp__internal__n_start_req_or_res; } /* UNREACHABLE */; abort(); } case s_n_llhttp__internal__n_start: s_n_llhttp__internal__n_start: { if (p == endp) { return s_n_llhttp__internal__n_start; } switch (*p) { case 10: { p++; goto s_n_llhttp__internal__n_start; } case 13: { p++; goto s_n_llhttp__internal__n_start; } default: { goto s_n_llhttp__internal__n_invoke_update_finish; } } /* UNREACHABLE */; abort(); } default: /* UNREACHABLE */ abort(); } s_n_llhttp__internal__n_error_37: { state->error = 0x7; state->reason = "Invalid characters in url"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_finish_2: { switch (llhttp__internal__c_update_finish_1(state, p, endp)) { default: goto s_n_llhttp__internal__n_start; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_test_lenient_flags: { switch (llhttp__internal__c_test_lenient_flags(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_invoke_update_finish_2; default: goto s_n_llhttp__internal__n_closed; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_finish_1: { switch (llhttp__internal__c_update_finish_1(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_test_lenient_flags; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_pause_5: { state->error = 0x15; state->reason = "on_message_complete pause"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_is_equal_upgrade; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_9: { state->error = 0x12; state->reason = "`on_message_complete` callback error"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_pause_7: { state->error = 0x15; state->reason = "on_chunk_complete pause"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_12: { state->error = 0x14; state->reason = "`on_chunk_complete` callback error"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_chunk_complete_1: { switch (llhttp__on_chunk_complete(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2; case 21: goto s_n_llhttp__internal__n_pause_7; default: goto s_n_llhttp__internal__n_error_12; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_11: { state->error = 0x4; state->reason = "Content-Length can't be present with Transfer-Encoding"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_pause_2: { state->error = 0x15; state->reason = "on_message_complete pause"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_pause_1; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_3: { state->error = 0x12; state->reason = "`on_message_complete` callback error"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_1: { switch (llhttp__on_message_complete(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_pause_1; case 21: goto s_n_llhttp__internal__n_pause_2; default: goto s_n_llhttp__internal__n_error_3; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_7: { state->error = 0xc; state->reason = "Chunk size overflow"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_pause_3: { state->error = 0x15; state->reason = "on_chunk_complete pause"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_update_content_length; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_5: { state->error = 0x14; state->reason = "`on_chunk_complete` callback error"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_chunk_complete: { switch (llhttp__on_chunk_complete(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_invoke_update_content_length; case 21: goto s_n_llhttp__internal__n_pause_3; default: goto s_n_llhttp__internal__n_error_5; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_body: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_body(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_chunk_data_almost_done; return s_error; } goto s_n_llhttp__internal__n_chunk_data_almost_done; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags: { switch (llhttp__internal__c_or_flags(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_field_start; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_pause_4: { state->error = 0x15; state->reason = "on_chunk_header pause"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_is_equal_content_length; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_4: { state->error = 0x13; state->reason = "`on_chunk_header` callback error"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_chunk_header: { switch (llhttp__on_chunk_header(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_invoke_is_equal_content_length; case 21: goto s_n_llhttp__internal__n_pause_4; default: goto s_n_llhttp__internal__n_error_4; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_6: { state->error = 0xc; state->reason = "Invalid character in chunk size"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_mul_add_content_length: { switch (llhttp__internal__c_mul_add_content_length(state, p, endp, match)) { case 1: goto s_n_llhttp__internal__n_error_7; default: goto s_n_llhttp__internal__n_chunk_size; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_8: { state->error = 0xc; state->reason = "Invalid character in chunk size"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_body_1: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_body(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2; return s_error; } goto s_n_llhttp__internal__n_invoke_llhttp__on_message_complete_2; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_finish_3: { switch (llhttp__internal__c_update_finish_3(state, p, endp)) { default: goto s_n_llhttp__internal__n_span_start_llhttp__on_body_2; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_10: { state->error = 0xf; state->reason = "Request has invalid `Transfer-Encoding`"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_pause: { state->error = 0x15; state->reason = "on_message_complete pause"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__after_message_complete; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_2: { state->error = 0x12; state->reason = "`on_message_complete` callback error"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_message_complete: { switch (llhttp__on_message_complete(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_invoke_llhttp__after_message_complete; case 21: goto s_n_llhttp__internal__n_pause; default: goto s_n_llhttp__internal__n_error_2; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_1: { switch (llhttp__internal__c_or_flags_1(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_2: { switch (llhttp__internal__c_or_flags_1(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_upgrade: { switch (llhttp__internal__c_update_upgrade(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_or_flags_2; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_pause_6: { state->error = 0x15; state->reason = "Paused by on_headers_complete"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_1: { state->error = 0x11; state->reason = "User callback error"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_headers_complete: { switch (llhttp__on_headers_complete(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_invoke_llhttp__after_headers_complete; case 1: goto s_n_llhttp__internal__n_invoke_or_flags_1; case 2: goto s_n_llhttp__internal__n_invoke_update_upgrade; case 21: goto s_n_llhttp__internal__n_pause_6; default: goto s_n_llhttp__internal__n_error_1; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__before_headers_complete: { switch (llhttp__before_headers_complete(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_llhttp__on_headers_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_test_lenient_flags_1: { switch (llhttp__internal__c_test_lenient_flags_1(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_error_11; default: goto s_n_llhttp__internal__n_invoke_llhttp__before_headers_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_test_flags_1: { switch (llhttp__internal__c_test_flags_1(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_invoke_test_lenient_flags_1; default: goto s_n_llhttp__internal__n_invoke_llhttp__before_headers_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_test_flags: { switch (llhttp__internal__c_test_flags(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_invoke_llhttp__on_chunk_complete_1; default: goto s_n_llhttp__internal__n_invoke_test_flags_1; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_13: { state->error = 0xb; state->reason = "Empty Content-Length"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_header_value: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_header_value(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete; return s_error; } goto s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state: { switch (llhttp__internal__c_update_header_state(state, p, endp)) { default: goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_3: { switch (llhttp__internal__c_or_flags_3(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_4: { switch (llhttp__internal__c_or_flags_4(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_5: { switch (llhttp__internal__c_or_flags_5(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_6: { switch (llhttp__internal__c_or_flags_6(state, p, endp)) { default: goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_header_state_1: { switch (llhttp__internal__c_load_header_state(state, p, endp)) { case 5: goto s_n_llhttp__internal__n_invoke_or_flags_3; case 6: goto s_n_llhttp__internal__n_invoke_or_flags_4; case 7: goto s_n_llhttp__internal__n_invoke_or_flags_5; case 8: goto s_n_llhttp__internal__n_invoke_or_flags_6; default: goto s_n_llhttp__internal__n_span_start_llhttp__on_header_value; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_header_state: { switch (llhttp__internal__c_load_header_state(state, p, endp)) { case 2: goto s_n_llhttp__internal__n_error_13; default: goto s_n_llhttp__internal__n_invoke_load_header_state_1; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_1: { switch (llhttp__internal__c_update_header_state(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_7: { switch (llhttp__internal__c_or_flags_3(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state_1; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_8: { switch (llhttp__internal__c_or_flags_4(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state_1; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_9: { switch (llhttp__internal__c_or_flags_5(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state_1; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_10: { switch (llhttp__internal__c_or_flags_6(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_header_state_3: { switch (llhttp__internal__c_load_header_state(state, p, endp)) { case 5: goto s_n_llhttp__internal__n_invoke_or_flags_7; case 6: goto s_n_llhttp__internal__n_invoke_or_flags_8; case 7: goto s_n_llhttp__internal__n_invoke_or_flags_9; case 8: goto s_n_llhttp__internal__n_invoke_or_flags_10; default: goto s_n_llhttp__internal__n_invoke_llhttp__on_header_value_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_14: { state->error = 0x3; state->reason = "Missing expected LF after header value"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_header_value_1: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_header_value(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_header_value_almost_done; return s_error; } goto s_n_llhttp__internal__n_header_value_almost_done; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_header_value_2: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_header_value(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) (p + 1); state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_header_value_almost_done; return s_error; } p++; goto s_n_llhttp__internal__n_header_value_almost_done; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_header_value_3: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_header_value(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) (p + 1); state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_header_value_almost_done; return s_error; } p++; goto s_n_llhttp__internal__n_header_value_almost_done; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_15: { state->error = 0xa; state->reason = "Invalid header value char"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_test_lenient_flags_2: { switch (llhttp__internal__c_test_lenient_flags_2(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_header_value_lenient; default: goto s_n_llhttp__internal__n_error_15; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_3: { switch (llhttp__internal__c_update_header_state(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_connection; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_11: { switch (llhttp__internal__c_or_flags_3(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state_3; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_12: { switch (llhttp__internal__c_or_flags_4(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state_3; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_13: { switch (llhttp__internal__c_or_flags_5(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state_3; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_14: { switch (llhttp__internal__c_or_flags_6(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_connection; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_header_state_4: { switch (llhttp__internal__c_load_header_state(state, p, endp)) { case 5: goto s_n_llhttp__internal__n_invoke_or_flags_11; case 6: goto s_n_llhttp__internal__n_invoke_or_flags_12; case 7: goto s_n_llhttp__internal__n_invoke_or_flags_13; case 8: goto s_n_llhttp__internal__n_invoke_or_flags_14; default: goto s_n_llhttp__internal__n_header_value_connection; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_4: { switch (llhttp__internal__c_update_header_state_4(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_connection_token; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_2: { switch (llhttp__internal__c_update_header_state_2(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_connection_ws; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_5: { switch (llhttp__internal__c_update_header_state_5(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_connection_ws; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_6: { switch (llhttp__internal__c_update_header_state_6(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_connection_ws; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_header_value_4: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_header_value(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_error_17; return s_error; } goto s_n_llhttp__internal__n_error_17; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_mul_add_content_length_1: { switch (llhttp__internal__c_mul_add_content_length_1(state, p, endp, match)) { case 1: goto s_n_llhttp__internal__n_span_end_llhttp__on_header_value_4; default: goto s_n_llhttp__internal__n_header_value_content_length; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_15: { switch (llhttp__internal__c_or_flags_15(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_otherwise; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_header_value_5: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_header_value(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_error_18; return s_error; } goto s_n_llhttp__internal__n_error_18; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_16: { state->error = 0x4; state->reason = "Duplicate Content-Length"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_test_flags_2: { switch (llhttp__internal__c_test_flags_2(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_header_value_content_length; default: goto s_n_llhttp__internal__n_error_16; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_7: { switch (llhttp__internal__c_update_header_state_7(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_otherwise; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_8: { switch (llhttp__internal__c_update_header_state_4(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_and_flags: { switch (llhttp__internal__c_and_flags(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_value_te_chunked; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_16: { switch (llhttp__internal__c_or_flags_16(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_and_flags; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_or_flags_17: { switch (llhttp__internal__c_or_flags_17(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_header_state_8; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_header_state_2: { switch (llhttp__internal__c_load_header_state(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_header_value_connection; case 2: goto s_n_llhttp__internal__n_invoke_test_flags_2; case 3: goto s_n_llhttp__internal__n_invoke_or_flags_16; case 4: goto s_n_llhttp__internal__n_invoke_or_flags_17; default: goto s_n_llhttp__internal__n_header_value; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_header_field: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_header_field(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) (p + 1); state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete; return s_error; } p++; goto s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_header_field_1: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_header_field(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) (p + 1); state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete; return s_error; } p++; goto s_n_llhttp__internal__n_invoke_llhttp__on_header_field_complete; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_19: { state->error = 0xa; state->reason = "Invalid header token"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_9: { switch (llhttp__internal__c_update_header_state_4(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_field_general; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_store_header_state: { switch (llhttp__internal__c_store_header_state(state, p, endp, match)) { default: goto s_n_llhttp__internal__n_header_field_colon; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_header_state_10: { switch (llhttp__internal__c_update_header_state_4(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_field_general; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_url_complete: { switch (llhttp__on_url_complete(state, p, endp)) { default: goto s_n_llhttp__internal__n_header_field_start; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_http_minor: { switch (llhttp__internal__c_update_http_minor(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_llhttp__on_url_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_http_major: { switch (llhttp__internal__c_update_http_major(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_update_http_minor; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_3: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_20: { state->error = 0x7; state->reason = "Expected CRLF"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_4: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_lf_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_23: { state->error = 0x17; state->reason = "Pause on PRI/Upgrade"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_24: { state->error = 0x9; state->reason = "Expected HTTP/2 Connection Preface"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_22: { state->error = 0x9; state->reason = "Expected CRLF after version"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_method_1: { switch (llhttp__internal__c_load_method(state, p, endp)) { case 34: goto s_n_llhttp__internal__n_req_pri_upgrade; default: goto s_n_llhttp__internal__n_req_http_complete; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_store_http_minor: { switch (llhttp__internal__c_store_http_minor(state, p, endp, match)) { default: goto s_n_llhttp__internal__n_invoke_load_method_1; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_25: { state->error = 0x9; state->reason = "Invalid minor version"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_26: { state->error = 0x9; state->reason = "Expected dot"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_store_http_major: { switch (llhttp__internal__c_store_http_major(state, p, endp, match)) { default: goto s_n_llhttp__internal__n_req_http_dot; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_27: { state->error = 0x9; state->reason = "Invalid major version"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_21: { state->error = 0x8; state->reason = "Invalid method for HTTP/x.x request"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_method: { switch (llhttp__internal__c_load_method(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_req_http_major; case 1: goto s_n_llhttp__internal__n_req_http_major; case 2: goto s_n_llhttp__internal__n_req_http_major; case 3: goto s_n_llhttp__internal__n_req_http_major; case 4: goto s_n_llhttp__internal__n_req_http_major; case 5: goto s_n_llhttp__internal__n_req_http_major; case 6: goto s_n_llhttp__internal__n_req_http_major; case 7: goto s_n_llhttp__internal__n_req_http_major; case 8: goto s_n_llhttp__internal__n_req_http_major; case 9: goto s_n_llhttp__internal__n_req_http_major; case 10: goto s_n_llhttp__internal__n_req_http_major; case 11: goto s_n_llhttp__internal__n_req_http_major; case 12: goto s_n_llhttp__internal__n_req_http_major; case 13: goto s_n_llhttp__internal__n_req_http_major; case 14: goto s_n_llhttp__internal__n_req_http_major; case 15: goto s_n_llhttp__internal__n_req_http_major; case 16: goto s_n_llhttp__internal__n_req_http_major; case 17: goto s_n_llhttp__internal__n_req_http_major; case 18: goto s_n_llhttp__internal__n_req_http_major; case 19: goto s_n_llhttp__internal__n_req_http_major; case 20: goto s_n_llhttp__internal__n_req_http_major; case 21: goto s_n_llhttp__internal__n_req_http_major; case 22: goto s_n_llhttp__internal__n_req_http_major; case 23: goto s_n_llhttp__internal__n_req_http_major; case 24: goto s_n_llhttp__internal__n_req_http_major; case 25: goto s_n_llhttp__internal__n_req_http_major; case 26: goto s_n_llhttp__internal__n_req_http_major; case 27: goto s_n_llhttp__internal__n_req_http_major; case 28: goto s_n_llhttp__internal__n_req_http_major; case 29: goto s_n_llhttp__internal__n_req_http_major; case 30: goto s_n_llhttp__internal__n_req_http_major; case 31: goto s_n_llhttp__internal__n_req_http_major; case 32: goto s_n_llhttp__internal__n_req_http_major; case 33: goto s_n_llhttp__internal__n_req_http_major; case 34: goto s_n_llhttp__internal__n_req_http_major; default: goto s_n_llhttp__internal__n_error_21; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_30: { state->error = 0x8; state->reason = "Expected HTTP/"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_28: { state->error = 0x8; state->reason = "Expected SOURCE method for ICE/x.x request"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_method_2: { switch (llhttp__internal__c_load_method(state, p, endp)) { case 33: goto s_n_llhttp__internal__n_req_http_major; default: goto s_n_llhttp__internal__n_error_28; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_29: { state->error = 0x8; state->reason = "Invalid method for RTSP/x.x request"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_load_method_3: { switch (llhttp__internal__c_load_method(state, p, endp)) { case 1: goto s_n_llhttp__internal__n_req_http_major; case 3: goto s_n_llhttp__internal__n_req_http_major; case 6: goto s_n_llhttp__internal__n_req_http_major; case 35: goto s_n_llhttp__internal__n_req_http_major; case 36: goto s_n_llhttp__internal__n_req_http_major; case 37: goto s_n_llhttp__internal__n_req_http_major; case 38: goto s_n_llhttp__internal__n_req_http_major; case 39: goto s_n_llhttp__internal__n_req_http_major; case 40: goto s_n_llhttp__internal__n_req_http_major; case 41: goto s_n_llhttp__internal__n_req_http_major; case 42: goto s_n_llhttp__internal__n_req_http_major; case 43: goto s_n_llhttp__internal__n_req_http_major; case 44: goto s_n_llhttp__internal__n_req_http_major; case 45: goto s_n_llhttp__internal__n_req_http_major; default: goto s_n_llhttp__internal__n_error_29; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_url_complete_1: { switch (llhttp__on_url_complete(state, p, endp)) { default: goto s_n_llhttp__internal__n_req_http_start; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_5: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_6: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_7: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_lf_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_8: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_31: { state->error = 0x7; state->reason = "Invalid char in url fragment start"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_9: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_10: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_lf_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_11: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_32: { state->error = 0x7; state->reason = "Invalid char in url query"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_33: { state->error = 0x7; state->reason = "Invalid char in url path"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_1: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_lf_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_2: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_12: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_13: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_lf_to_http09; return s_error; } goto s_n_llhttp__internal__n_url_skip_lf_to_http09; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_url_14: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_url(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_url_skip_to_http; return s_error; } goto s_n_llhttp__internal__n_url_skip_to_http; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_34: { state->error = 0x7; state->reason = "Double @ in url"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_35: { state->error = 0x7; state->reason = "Unexpected char in url server"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_36: { state->error = 0x7; state->reason = "Unexpected char in url server"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_38: { state->error = 0x7; state->reason = "Unexpected char in url schema"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_39: { state->error = 0x7; state->reason = "Unexpected char in url schema"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_40: { state->error = 0x7; state->reason = "Unexpected start char in url"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_is_equal_method: { switch (llhttp__internal__c_is_equal_method(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_span_start_llhttp__on_url_1; default: goto s_n_llhttp__internal__n_span_start_llhttp__on_url; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_41: { state->error = 0x6; state->reason = "Expected space after method"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_store_method_1: { switch (llhttp__internal__c_store_method(state, p, endp, match)) { default: goto s_n_llhttp__internal__n_req_first_space_before_url; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_49: { state->error = 0x6; state->reason = "Invalid method encountered"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_42: { state->error = 0xd; state->reason = "Response overflow"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_mul_add_status_code: { switch (llhttp__internal__c_mul_add_status_code(state, p, endp, match)) { case 1: goto s_n_llhttp__internal__n_error_42; default: goto s_n_llhttp__internal__n_res_status_code; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_status: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_status(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) (p + 1); state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_llhttp__on_status_complete; return s_error; } p++; goto s_n_llhttp__internal__n_invoke_llhttp__on_status_complete; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_span_end_llhttp__on_status_1: { const unsigned char* start; int err; start = state->_span_pos0; state->_span_pos0 = NULL; err = llhttp__on_status(state, start, p); if (err != 0) { state->error = err; state->error_pos = (const char*) (p + 1); state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_res_line_almost_done; return s_error; } p++; goto s_n_llhttp__internal__n_res_line_almost_done; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_43: { state->error = 0xd; state->reason = "Invalid response status"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_status_code: { switch (llhttp__internal__c_update_status_code(state, p, endp)) { default: goto s_n_llhttp__internal__n_res_status_code; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_44: { state->error = 0x9; state->reason = "Expected space after version"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_store_http_minor_1: { switch (llhttp__internal__c_store_http_minor(state, p, endp, match)) { default: goto s_n_llhttp__internal__n_res_http_end; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_45: { state->error = 0x9; state->reason = "Invalid minor version"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_46: { state->error = 0x9; state->reason = "Expected dot"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_store_http_major_1: { switch (llhttp__internal__c_store_http_major(state, p, endp, match)) { default: goto s_n_llhttp__internal__n_res_http_dot; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_47: { state->error = 0x9; state->reason = "Invalid major version"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_50: { state->error = 0x8; state->reason = "Expected HTTP/"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_type: { switch (llhttp__internal__c_update_type(state, p, endp)) { default: goto s_n_llhttp__internal__n_req_first_space_before_url; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_store_method: { switch (llhttp__internal__c_store_method(state, p, endp, match)) { default: goto s_n_llhttp__internal__n_invoke_update_type; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error_48: { state->error = 0x8; state->reason = "Invalid word encountered"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_type_1: { switch (llhttp__internal__c_update_type_1(state, p, endp)) { default: goto s_n_llhttp__internal__n_res_http_major; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_type_2: { switch (llhttp__internal__c_update_type(state, p, endp)) { default: goto s_n_llhttp__internal__n_start_req; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_pause_8: { state->error = 0x15; state->reason = "on_message_begin pause"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_n_llhttp__internal__n_invoke_load_type; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_error: { state->error = 0x10; state->reason = "`on_message_begin` callback error"; state->error_pos = (const char*) p; state->_current = (void*) (intptr_t) s_error; return s_error; /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_llhttp__on_message_begin: { switch (llhttp__on_message_begin(state, p, endp)) { case 0: goto s_n_llhttp__internal__n_invoke_load_type; case 21: goto s_n_llhttp__internal__n_pause_8; default: goto s_n_llhttp__internal__n_error; } /* UNREACHABLE */; abort(); } s_n_llhttp__internal__n_invoke_update_finish: { switch (llhttp__internal__c_update_finish(state, p, endp)) { default: goto s_n_llhttp__internal__n_invoke_llhttp__on_message_begin; } /* UNREACHABLE */; abort(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-444'], 'message': 'deps: update llhttp to 6.0.4 Refs: https://hackerone.com/reports/1238099 Refs: https://hackerone.com/reports/1238709 Refs: https://github.com/nodejs-private/llhttp-private/pull/6 Refs: https://github.com/nodejs-private/llhttp-private/pull/5 CVE-ID: CVE-2021-22959 CVE-ID: CVE-2021-22960 PR-URL: https://github.com/nodejs-private/node-private/pull/284 Reviewed-By: Akshay K <iit.akshay@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: v8::MaybeLocal<v8::Value> GetInfoString( Environment* env, const BIOPointer& bio, X509* cert) { int index = X509_get_ext_by_NID(cert, nid, -1); if (index < 0) return Undefined(env->isolate()); X509_EXTENSION* ext = X509_get_ext(cert, index); CHECK_NOT_NULL(ext); if (!SafeX509ExtPrint(bio, ext) && X509V3_EXT_print(bio.get(), ext, 0, 0) != 1) { USE(BIO_reset(bio.get())); return v8::Null(env->isolate()); } return ToV8Value(env, bio); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'crypto,tls: implement safe x509 GeneralName format This change introduces JSON-compatible escaping rules for strings that include X.509 GeneralName components (see RFC 5280). This non-standard format avoids ambiguities and prevents injection attacks that could previously lead to X.509 certificates being accepted even though they were not valid for the target hostname. These changes affect the format of subject alternative names and the format of authority information access. The checkServerIdentity function has been modified to safely handle the new format, eliminating the possibility of injecting subject alternative names into the verification logic. Because each subject alternative name is only encoded as a JSON string literal if necessary for security purposes, this change will only be visible in rare cases. This addresses CVE-2021-44532. CVE-ID: CVE-2021-44532 PR-URL: https://github.com/nodejs-private/node-private/pull/300 Reviewed-By: Michael Dawson <midawson@redhat.com> Reviewed-By: Rich Trott <rtrott@gmail.com>'</s>