instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data, krb5_kvno mkvno) { struct berval **ret = NULL; int currkvno; int num_versions = 1; int i, j, last; krb5_error_code err = 0; krb5_key_data *key_data; if (n_key_data <= 0) return NULL; /* Make a shallow copy of the key data so we can alter it. */ key_data = k5calloc(n_key_data, sizeof(*key_data), &err); if (key_data_in == NULL) goto cleanup; memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data)); /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt * field. For compatibility, always encode a salt field. */ for (i = 0; i < n_key_data; i++) { if (key_data[i].key_data_ver == 1) { key_data[i].key_data_ver = 2; key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } } /* Find the number of key versions */ for (i = 0; i < n_key_data - 1; i++) if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno) num_versions++; ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *)); if (ret == NULL) { err = ENOMEM; goto cleanup; } for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) { krb5_data *code; if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) { ret[j] = k5alloc(sizeof(struct berval), &err); if (ret[j] == NULL) goto cleanup; err = asn1_encode_sequence_of_keys(key_data + last, (krb5_int16)i - last + 1, mkvno, &code); if (err) goto cleanup; /*CHECK_NULL(ret[j]); */ ret[j]->bv_len = code->length; ret[j]->bv_val = code->data; free(code); j++; last = i + 1; if (i < n_key_data - 1) currkvno = key_data[i + 1].key_data_kvno; } } ret[num_versions] = NULL; cleanup: free(key_data); if (err != 0) { if (ret != NULL) { for (i = 0; i <= num_versions; i++) if (ret[i] != NULL) free (ret[i]); free (ret); ret = NULL; } } return ret; } Commit Message: Support keyless principals in LDAP [CVE-2014-5354] Operations like "kadmin -q 'addprinc -nokey foo'" or "kadmin -q 'purgekeys -all foo'" result in principal entries with no keys present, so krb5_encode_krbsecretkey() would just return NULL, which then got unconditionally dereferenced in krb5_add_ber_mem_ldap_mod(). Apply some fixes to krb5_encode_krbsecretkey() to handle zero-key principals better, correct the test for an allocation failure, and slightly restructure the cleanup handler to be shorter and more appropriate for the usage. Once it no longer short-circuits when n_key_data is zero, it will produce an array of length two with both entries NULL, which is treated as an empty list by the LDAP library, the correct behavior for a keyless principal. However, attributes with empty values are only handled by the LDAP library for Modify operations, not Add operations (which only get a sequence of Attribute, with no operation field). Therefore, only add an empty krbprincipalkey to the modlist when we will be performing a Modify, and not when we will be performing an Add, which is conditional on the (misspelled) create_standalone_prinicipal boolean. CVE-2014-5354: In MIT krb5, when kadmind is configured to use LDAP for the KDC database, an authenticated remote attacker can cause a NULL dereference by inserting into the database a principal entry which contains no long-term keys. In order for the LDAP KDC backend to translate a principal entry from the database abstraction layer into the form expected by the LDAP schema, the principal's keys are encoded into a NULL-terminated array of length-value entries to be stored in the LDAP database. However, the subroutine which produced this array did not correctly handle the case where no keys were present, returning NULL instead of an empty array, and the array was unconditionally dereferenced while adding to the list of LDAP operations to perform. Versions of MIT krb5 prior to 1.12 did not expose a way for principal entries to have no long-term key material, and therefore are not vulnerable. CVSSv2 Vector: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:OF/RC:C ticket: 8041 (new) tags: pullup target_version: 1.13.1 subject: kadmind with ldap backend crashes when putting keyless entries CWE ID:
krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data, krb5_kvno mkvno) { struct berval **ret = NULL; int currkvno; int num_versions = 1; int i, j, last; krb5_error_code err = 0; krb5_key_data *key_data = NULL; if (n_key_data < 0) return NULL; /* Make a shallow copy of the key data so we can alter it. */ key_data = k5calloc(n_key_data, sizeof(*key_data), &err); if (key_data == NULL) goto cleanup; memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data)); /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt * field. For compatibility, always encode a salt field. */ for (i = 0; i < n_key_data; i++) { if (key_data[i].key_data_ver == 1) { key_data[i].key_data_ver = 2; key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } } /* Find the number of key versions */ for (i = 0; i < n_key_data - 1; i++) if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno) num_versions++; ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *)); if (ret == NULL) { err = ENOMEM; goto cleanup; } for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) { krb5_data *code; if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) { ret[j] = k5alloc(sizeof(struct berval), &err); if (ret[j] == NULL) goto cleanup; err = asn1_encode_sequence_of_keys(key_data + last, (krb5_int16)i - last + 1, mkvno, &code); if (err) goto cleanup; /*CHECK_NULL(ret[j]); */ ret[j]->bv_len = code->length; ret[j]->bv_val = code->data; free(code); j++; last = i + 1; if (i < n_key_data - 1) currkvno = key_data[i + 1].key_data_kvno; } } ret[num_versions] = NULL; cleanup: free(key_data); if (err != 0) { if (ret != NULL) { for (i = 0; ret[i] != NULL; i++) free (ret[i]); free (ret); ret = NULL; } } return ret; }
166,272
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SerializerMarkupAccumulator::appendText(StringBuilder& result, Text* text) { Element* parent = text->parentElement(); if (parent && !shouldIgnoreElement(parent)) MarkupAccumulator::appendText(result, text); } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void SerializerMarkupAccumulator::appendText(StringBuilder& result, Text* text) void SerializerMarkupAccumulator::appendText(StringBuilder& out, Text* text) { Element* parent = text->parentElement(); if (parent && !shouldIgnoreElement(parent)) MarkupAccumulator::appendText(out, text); }
171,569
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LocalFileSystem::requestFileSystem(ExecutionContext* context, FileSystemType type, long long size, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::fileSystemAllowedInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::requestFileSystem(ExecutionContext* context, FileSystemType type, long long size, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); CallbackWrapper* wrapper = new CallbackWrapper(callbacks); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::fileSystemAllowedInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); }
171,429
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ctdb_tcp_listen_automatic(struct ctdb_context *ctdb) { struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data, struct ctdb_tcp); ctdb_sock_addr sock; int lock_fd, i; const char *lock_path = "/tmp/.ctdb_socket_lock"; struct flock lock; int one = 1; int sock_size; struct tevent_fd *fde; /* If there are no nodes, then it won't be possible to find * the first one. Log a failure and short circuit the whole * process. */ if (ctdb->num_nodes == 0) { DEBUG(DEBUG_CRIT,("No nodes available to attempt bind to - is the nodes file empty?\n")); return -1; } /* in order to ensure that we don't get two nodes with the same adddress, we must make the bind() and listen() calls atomic. The SO_REUSEADDR setsockopt only prevents double binds if the first socket is in LISTEN state */ lock_fd = open(lock_path, O_RDWR|O_CREAT, 0666); if (lock_fd == -1) { DEBUG(DEBUG_CRIT,("Unable to open %s\n", lock_path)); return -1; } lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 1; lock.l_pid = 0; if (fcntl(lock_fd, F_SETLKW, &lock) != 0) { DEBUG(DEBUG_CRIT,("Unable to lock %s\n", lock_path)); close(lock_fd); return -1; } for (i=0; i < ctdb->num_nodes; i++) { if (ctdb->nodes[i]->flags & NODE_FLAGS_DELETED) { continue; } ZERO_STRUCT(sock); if (ctdb_tcp_get_address(ctdb, ctdb->nodes[i]->address.address, &sock) != 0) { continue; } switch (sock.sa.sa_family) { case AF_INET: sock.ip.sin_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip); break; case AF_INET6: sock.ip6.sin6_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip6); break; default: DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n", sock.sa.sa_family)); continue; } #ifdef HAVE_SOCK_SIN_LEN sock.ip.sin_len = sock_size; #endif ctcp->listen_fd = socket(sock.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); if (ctcp->listen_fd == -1) { ctdb_set_error(ctdb, "socket failed\n"); continue; } set_close_on_exec(ctcp->listen_fd); setsockopt(ctcp->listen_fd,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one)); if (bind(ctcp->listen_fd, (struct sockaddr * )&sock, sock_size) == 0) { break; } if (errno == EADDRNOTAVAIL) { DEBUG(DEBUG_DEBUG,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } else { DEBUG(DEBUG_ERR,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } } if (i == ctdb->num_nodes) { DEBUG(DEBUG_CRIT,("Unable to bind to any of the node addresses - giving up\n")); goto failed; } ctdb->address.address = talloc_strdup(ctdb, ctdb->nodes[i]->address.address); ctdb->address.port = ctdb->nodes[i]->address.port; ctdb->name = talloc_asprintf(ctdb, "%s:%u", ctdb->address.address, ctdb->address.port); ctdb->pnn = ctdb->nodes[i]->pnn; DEBUG(DEBUG_INFO,("ctdb chose network address %s:%u pnn %u\n", ctdb->address.address, ctdb->address.port, ctdb->pnn)); if (listen(ctcp->listen_fd, 10) == -1) { goto failed; } fde = event_add_fd(ctdb->ev, ctcp, ctcp->listen_fd, EVENT_FD_READ, ctdb_listen_event, ctdb); tevent_fd_set_auto_close(fde); close(lock_fd); return 0; failed: close(lock_fd); close(ctcp->listen_fd); ctcp->listen_fd = -1; return -1; } Commit Message: CWE ID: CWE-264
static int ctdb_tcp_listen_automatic(struct ctdb_context *ctdb) { struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data, struct ctdb_tcp); ctdb_sock_addr sock; int lock_fd, i; const char *lock_path = VARDIR "/run/ctdb/.socket_lock"; struct flock lock; int one = 1; int sock_size; struct tevent_fd *fde; /* If there are no nodes, then it won't be possible to find * the first one. Log a failure and short circuit the whole * process. */ if (ctdb->num_nodes == 0) { DEBUG(DEBUG_CRIT,("No nodes available to attempt bind to - is the nodes file empty?\n")); return -1; } /* in order to ensure that we don't get two nodes with the same adddress, we must make the bind() and listen() calls atomic. The SO_REUSEADDR setsockopt only prevents double binds if the first socket is in LISTEN state */ lock_fd = open(lock_path, O_RDWR|O_CREAT, 0666); if (lock_fd == -1) { DEBUG(DEBUG_CRIT,("Unable to open %s\n", lock_path)); return -1; } lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 1; lock.l_pid = 0; if (fcntl(lock_fd, F_SETLKW, &lock) != 0) { DEBUG(DEBUG_CRIT,("Unable to lock %s\n", lock_path)); close(lock_fd); return -1; } for (i=0; i < ctdb->num_nodes; i++) { if (ctdb->nodes[i]->flags & NODE_FLAGS_DELETED) { continue; } ZERO_STRUCT(sock); if (ctdb_tcp_get_address(ctdb, ctdb->nodes[i]->address.address, &sock) != 0) { continue; } switch (sock.sa.sa_family) { case AF_INET: sock.ip.sin_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip); break; case AF_INET6: sock.ip6.sin6_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip6); break; default: DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n", sock.sa.sa_family)); continue; } #ifdef HAVE_SOCK_SIN_LEN sock.ip.sin_len = sock_size; #endif ctcp->listen_fd = socket(sock.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); if (ctcp->listen_fd == -1) { ctdb_set_error(ctdb, "socket failed\n"); continue; } set_close_on_exec(ctcp->listen_fd); setsockopt(ctcp->listen_fd,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one)); if (bind(ctcp->listen_fd, (struct sockaddr * )&sock, sock_size) == 0) { break; } if (errno == EADDRNOTAVAIL) { DEBUG(DEBUG_DEBUG,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } else { DEBUG(DEBUG_ERR,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } } if (i == ctdb->num_nodes) { DEBUG(DEBUG_CRIT,("Unable to bind to any of the node addresses - giving up\n")); goto failed; } ctdb->address.address = talloc_strdup(ctdb, ctdb->nodes[i]->address.address); ctdb->address.port = ctdb->nodes[i]->address.port; ctdb->name = talloc_asprintf(ctdb, "%s:%u", ctdb->address.address, ctdb->address.port); ctdb->pnn = ctdb->nodes[i]->pnn; DEBUG(DEBUG_INFO,("ctdb chose network address %s:%u pnn %u\n", ctdb->address.address, ctdb->address.port, ctdb->pnn)); if (listen(ctcp->listen_fd, 10) == -1) { goto failed; } fde = event_add_fd(ctdb->ev, ctcp, ctcp->listen_fd, EVENT_FD_READ, ctdb_listen_event, ctdb); tevent_fd_set_auto_close(fde); close(lock_fd); return 0; failed: close(lock_fd); close(ctcp->listen_fd); ctcp->listen_fd = -1; return -1; }
165,361
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Performance::PassesTimingAllowCheck( const ResourceResponse& response, const SecurityOrigin& initiator_security_origin, const AtomicString& original_timing_allow_origin, ExecutionContext* context) { scoped_refptr<const SecurityOrigin> resource_origin = SecurityOrigin::Create(response.Url()); if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin)) return true; const AtomicString& timing_allow_origin_string = original_timing_allow_origin.IsEmpty() ? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin) : original_timing_allow_origin; if (timing_allow_origin_string.IsEmpty() || EqualIgnoringASCIICase(timing_allow_origin_string, "null")) return false; if (timing_allow_origin_string == "*") { UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin); return true; } const String& security_origin = initiator_security_origin.ToString(); Vector<String> timing_allow_origins; timing_allow_origin_string.GetString().Split(',', timing_allow_origins); if (timing_allow_origins.size() > 1) { UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin); } else if (timing_allow_origins.size() == 1 && timing_allow_origin_string != "*") { UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin); } for (const String& allow_origin : timing_allow_origins) { const String allow_origin_stripped = allow_origin.StripWhiteSpace(); if (allow_origin_stripped == security_origin || allow_origin_stripped == "*") { return true; } } return false; } Commit Message: Fix timing allow check algorithm for service workers This CL uses the OriginalURLViaServiceWorker() in the timing allow check algorithm if the response WasFetchedViaServiceWorker(). This way, if a service worker changes a same origin request to become cross origin, then the timing allow check algorithm will still fail. resource-timing-worker.js is changed so it avoids an empty Response, which is an odd case in terms of same origin checks. Bug: 837275 Change-Id: I7e497a6fcc2ee14244121b915ca5f5cceded417a Reviewed-on: https://chromium-review.googlesource.com/1038229 Commit-Queue: Nicolás Peña Moreno <[email protected]> Reviewed-by: Yoav Weiss <[email protected]> Reviewed-by: Timothy Dresser <[email protected]> Cr-Commit-Position: refs/heads/master@{#555476} CWE ID: CWE-200
bool Performance::PassesTimingAllowCheck( const ResourceResponse& response, const SecurityOrigin& initiator_security_origin, const AtomicString& original_timing_allow_origin, ExecutionContext* context) { const KURL& response_url = response.WasFetchedViaServiceWorker() ? response.OriginalURLViaServiceWorker() : response.Url(); scoped_refptr<const SecurityOrigin> resource_origin = SecurityOrigin::Create(response_url); if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin)) return true; const AtomicString& timing_allow_origin_string = original_timing_allow_origin.IsEmpty() ? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin) : original_timing_allow_origin; if (timing_allow_origin_string.IsEmpty() || EqualIgnoringASCIICase(timing_allow_origin_string, "null")) return false; if (timing_allow_origin_string == "*") { UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin); return true; } const String& security_origin = initiator_security_origin.ToString(); Vector<String> timing_allow_origins; timing_allow_origin_string.GetString().Split(',', timing_allow_origins); if (timing_allow_origins.size() > 1) { UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin); } else if (timing_allow_origins.size() == 1 && timing_allow_origin_string != "*") { UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin); } for (const String& allow_origin : timing_allow_origins) { const String allow_origin_stripped = allow_origin.StripWhiteSpace(); if (allow_origin_stripped == security_origin || allow_origin_stripped == "*") { return true; } } return false; }
173,143
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; }
167,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionsGuestViewMessageFilter::ExtensionsGuestViewMessageFilter( int render_process_id, BrowserContext* context) : GuestViewMessageFilter(kFilteredMessageClasses, base::size(kFilteredMessageClasses), render_process_id, context), content::BrowserAssociatedInterface<mojom::GuestView>(this, this) { GetProcessIdToFilterMap()->insert_or_assign(render_process_id_, this); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362
ExtensionsGuestViewMessageFilter::ExtensionsGuestViewMessageFilter( int render_process_id, BrowserContext* context) : GuestViewMessageFilter(kFilteredMessageClasses, base::size(kFilteredMessageClasses), render_process_id, context), content::BrowserAssociatedInterface<mojom::GuestView>(this, this) { }
173,039
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages) { unsigned long i; for (i = 0; i < npages; ++i) kvm_release_pfn_clean(pfn + i); } Commit Message: kvm: iommu: fix the third parameter of kvm_iommu_put_pages (CVE-2014-3601) The third parameter of kvm_iommu_put_pages is wrong, It should be 'gfn - slot->base_gfn'. By making gfn very large, malicious guest or userspace can cause kvm to go to this error path, and subsequently to pass a huge value as size. Alternatively if gfn is small, then pages would be pinned but never unpinned, causing host memory leak and local DOS. Passing a reasonable but large value could be the most dangerous case, because it would unpin a page that should have stayed pinned, and thus allow the device to DMA into arbitrary memory. However, this cannot happen because of the condition that can trigger the error: - out of memory (where you can't allocate even a single page) should not be possible for the attacker to trigger - when exceeding the iommu's address space, guest pages after gfn will also exceed the iommu's address space, and inside kvm_iommu_put_pages() the iommu_iova_to_phys() will fail. The page thus would not be unpinned at all. Reported-by: Jack Morgenstein <[email protected]> Cc: [email protected] Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-189
static void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages)
166,352
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BufferQueueConsumer::dump(String8& result, const char* prefix) const { const IPCThreadState* ipc = IPCThreadState::self(); const pid_t pid = ipc->getCallingPid(); const uid_t uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(String16( "android.permission.DUMP"), pid, uid)) { result.appendFormat("Permission Denial: can't dump BufferQueueConsumer " "from pid=%d, uid=%d\n", pid, uid); } else { mCore->dump(result, prefix); } } Commit Message: Add SN logging Bug 27046057 Change-Id: Iede7c92e59e60795df1ec7768ebafd6b090f1c27 CWE ID: CWE-264
void BufferQueueConsumer::dump(String8& result, const char* prefix) const { const IPCThreadState* ipc = IPCThreadState::self(); const pid_t pid = ipc->getCallingPid(); const uid_t uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(String16( "android.permission.DUMP"), pid, uid)) { result.appendFormat("Permission Denial: can't dump BufferQueueConsumer " "from pid=%d, uid=%d\n", pid, uid); android_errorWriteWithInfoLog(0x534e4554, "27046057", uid, NULL, 0); } else { mCore->dump(result, prefix); } }
173,894
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AppCacheBackendImpl::SelectCacheForSharedWorker( int host_id, int64 appcache_id) { AppCacheHost* host = GetHost(host_id); if (!host || host->was_select_cache_called()) return false; host->SelectCacheForSharedWorker(appcache_id); return true; } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
bool AppCacheBackendImpl::SelectCacheForSharedWorker( int host_id, int64 appcache_id) { AppCacheHost* host = GetHost(host_id); if (!host) return false; return host->SelectCacheForSharedWorker(appcache_id); }
171,737
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */
167,077
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking) { int k, at_head; Sg_device *sdp = sfp->parentdp; sg_io_hdr_t *hp = &srp->header; srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */ hp->status = 0; hp->masked_status = 0; hp->msg_status = 0; hp->info = 0; hp->host_status = 0; hp->driver_status = 0; hp->resid = 0; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) cmnd[0], (int) hp->cmd_len)); k = sg_start_req(srp, cmnd); if (k) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: start_req err=%d\n", k)); sg_finish_rem_req(srp); return k; /* probably out of space --> ENOMEM */ } if (atomic_read(&sdp->detaching)) { if (srp->bio) blk_end_request_all(srp->rq, -EIO); sg_finish_rem_req(srp); return -ENODEV; } hp->duration = jiffies_to_msecs(jiffies); if (hp->interface_id != '\0' && /* v3 (or later) interface */ (SG_FLAG_Q_AT_TAIL & hp->flags)) at_head = 0; else at_head = 1; srp->rq->timeout = timeout; kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk, srp->rq, at_head, sg_rq_end_io); return 0; } Commit Message: sg: Fix double-free when drives detach during SG_IO In sg_common_write(), we free the block request and return -ENODEV if the device is detached in the middle of the SG_IO ioctl(). Unfortunately, sg_finish_rem_req() also tries to free srp->rq, so we end up freeing rq->cmd in the already free rq object, and then free the object itself out from under the current user. This ends up corrupting random memory via the list_head on the rq object. The most common crash trace I saw is this: ------------[ cut here ]------------ kernel BUG at block/blk-core.c:1420! Call Trace: [<ffffffff81281eab>] blk_put_request+0x5b/0x80 [<ffffffffa0069e5b>] sg_finish_rem_req+0x6b/0x120 [sg] [<ffffffffa006bcb9>] sg_common_write.isra.14+0x459/0x5a0 [sg] [<ffffffff8125b328>] ? selinux_file_alloc_security+0x48/0x70 [<ffffffffa006bf95>] sg_new_write.isra.17+0x195/0x2d0 [sg] [<ffffffffa006cef4>] sg_ioctl+0x644/0xdb0 [sg] [<ffffffff81170f80>] do_vfs_ioctl+0x90/0x520 [<ffffffff81258967>] ? file_has_perm+0x97/0xb0 [<ffffffff811714a1>] SyS_ioctl+0x91/0xb0 [<ffffffff81602afb>] tracesys+0xdd/0xe2 RIP [<ffffffff81281e04>] __blk_put_request+0x154/0x1a0 The solution is straightforward: just set srp->rq to NULL in the failure branch so that sg_finish_rem_req() doesn't attempt to re-free it. Additionally, since sg_rq_end_io() will never be called on the object when this happens, we need to free memory backing ->cmd if it isn't embedded in the object itself. KASAN was extremely helpful in finding the root cause of this bug. Signed-off-by: Calvin Owens <[email protected]> Acked-by: Douglas Gilbert <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-415
sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking) { int k, at_head; Sg_device *sdp = sfp->parentdp; sg_io_hdr_t *hp = &srp->header; srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */ hp->status = 0; hp->masked_status = 0; hp->msg_status = 0; hp->info = 0; hp->host_status = 0; hp->driver_status = 0; hp->resid = 0; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) cmnd[0], (int) hp->cmd_len)); k = sg_start_req(srp, cmnd); if (k) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: start_req err=%d\n", k)); sg_finish_rem_req(srp); return k; /* probably out of space --> ENOMEM */ } if (atomic_read(&sdp->detaching)) { if (srp->bio) { if (srp->rq->cmd != srp->rq->__cmd) kfree(srp->rq->cmd); blk_end_request_all(srp->rq, -EIO); srp->rq = NULL; } sg_finish_rem_req(srp); return -ENODEV; } hp->duration = jiffies_to_msecs(jiffies); if (hp->interface_id != '\0' && /* v3 (or later) interface */ (SG_FLAG_Q_AT_TAIL & hp->flags)) at_head = 0; else at_head = 1; srp->rq->timeout = timeout; kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk, srp->rq, at_head, sg_rq_end_io); return 0; }
167,464
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int crypto_rng_init_tfm(struct crypto_tfm *tfm) { struct crypto_rng *rng = __crypto_rng_cast(tfm); struct rng_alg *alg = crypto_rng_alg(rng); struct old_rng_alg *oalg = crypto_old_rng_alg(rng); if (oalg->rng_make_random) { rng->generate = generate; rng->seed = rngapi_reset; rng->seedsize = oalg->seedsize; return 0; } rng->generate = alg->generate; rng->seed = alg->seed; rng->seedsize = alg->seedsize; return 0; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476
static int crypto_rng_init_tfm(struct crypto_tfm *tfm) { return 0; }
167,731
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AudioTrack::AudioTrack( Segment* pSegment, long long element_start, long long element_size) : Track(pSegment, element_start, element_size) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
AudioTrack::AudioTrack(
174,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DoTouchScroll(const gfx::Point& point, const gfx::Vector2d& distance, bool wait_until_scrolled) { EXPECT_EQ(0, GetScrollTop()); int scrollHeight = ExecuteScriptAndExtractInt( "document.documentElement.scrollHeight"); EXPECT_EQ(1200, scrollHeight); scoped_refptr<FrameWatcher> frame_watcher(new FrameWatcher()); frame_watcher->AttachTo(shell()->web_contents()); SyntheticSmoothScrollGestureParams params; params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; params.anchor = gfx::PointF(point); params.distances.push_back(-distance); runner_ = new MessageLoopRunner(); std::unique_ptr<SyntheticSmoothScrollGesture> gesture( new SyntheticSmoothScrollGesture(params)); GetWidgetHost()->QueueSyntheticGesture( std::move(gesture), base::Bind(&TouchActionBrowserTest::OnSyntheticGestureCompleted, base::Unretained(this))); runner_->Run(); runner_ = NULL; while (wait_until_scrolled && frame_watcher->LastMetadata().root_scroll_offset.y() <= 0) { frame_watcher->WaitFrames(1); } int scrollTop = GetScrollTop(); if (scrollTop == 0) return false; EXPECT_EQ(distance.y(), scrollTop); return true; } Commit Message: Drive out additional flakiness of TouchAction browser test. It is relatively stable but it has flaked a couple of times specifically with this: Actual: 44 Expected: distance.y() Which is: 45 I presume that the failure is either we aren't waiting for the additional frame or a subpixel scrolling problem. As a speculative fix wait for the pixel item we are waiting to scroll for. BUG=376668 Review-Url: https://codereview.chromium.org/2281613002 Cr-Commit-Position: refs/heads/master@{#414525} CWE ID: CWE-119
bool DoTouchScroll(const gfx::Point& point, const gfx::Vector2d& distance, bool wait_until_scrolled) { EXPECT_EQ(0, GetScrollTop()); int scrollHeight = ExecuteScriptAndExtractInt( "document.documentElement.scrollHeight"); EXPECT_EQ(1200, scrollHeight); scoped_refptr<FrameWatcher> frame_watcher(new FrameWatcher()); frame_watcher->AttachTo(shell()->web_contents()); SyntheticSmoothScrollGestureParams params; params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; params.anchor = gfx::PointF(point); params.distances.push_back(-distance); runner_ = new MessageLoopRunner(); std::unique_ptr<SyntheticSmoothScrollGesture> gesture( new SyntheticSmoothScrollGesture(params)); GetWidgetHost()->QueueSyntheticGesture( std::move(gesture), base::Bind(&TouchActionBrowserTest::OnSyntheticGestureCompleted, base::Unretained(this))); runner_->Run(); runner_ = NULL; while (wait_until_scrolled && frame_watcher->LastMetadata().root_scroll_offset.y() < distance.y()) { frame_watcher->WaitFrames(1); } int scrollTop = GetScrollTop(); if (scrollTop == 0) return false; EXPECT_EQ(distance.y(), scrollTop); return true; }
171,600
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Bool FFD_CanHandleURL(GF_InputService *plug, const char *url) { Bool has_audio, has_video; s32 i; AVFormatContext *ctx; AVOutputFormat *fmt_out; Bool ret = GF_FALSE; char *ext, szName[1000], szExt[20]; const char *szExtList; FFDemux *ffd; if (!plug || !url) return GF_FALSE; /*disable RTP/RTSP from ffmpeg*/ if (!strnicmp(url, "rtsp://", 7)) return GF_FALSE; if (!strnicmp(url, "rtspu://", 8)) return GF_FALSE; if (!strnicmp(url, "rtp://", 6)) return GF_FALSE; if (!strnicmp(url, "plato://", 8)) return GF_FALSE; if (!strnicmp(url, "udp://", 6)) return GF_FALSE; if (!strnicmp(url, "tcp://", 6)) return GF_FALSE; if (!strnicmp(url, "data:", 5)) return GF_FALSE; ffd = (FFDemux*)plug->priv; strcpy(szName, url); ext = strrchr(szName, '#'); if (ext) ext[0] = 0; ext = strrchr(szName, '?'); if (ext) ext[0] = 0; ext = strrchr(szName, '.'); if (ext && strlen(ext) > 19) ext = NULL; if (ext && strlen(ext) > 1) { strcpy(szExt, &ext[1]); strlwr(szExt); #ifndef FFMPEG_DEMUX_ENABLE_MPEG2TS if (strstr("ts m2t mts dmb trp", szExt) ) return GF_FALSE; #endif /*note we forbid ffmpeg to handle files we support*/ if (!strcmp(szExt, "mp4") || !strcmp(szExt, "mpg4") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m21") || !strcmp(szExt, "m4v") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m4s") || !strcmp(szExt, "3gs") || !strcmp(szExt, "3gp") || !strcmp(szExt, "3gpp") || !strcmp(szExt, "3gp2") || !strcmp(szExt, "3g2") || !strcmp(szExt, "mp3") || !strcmp(szExt, "ac3") || !strcmp(szExt, "amr") || !strcmp(szExt, "bt") || !strcmp(szExt, "wrl") || !strcmp(szExt, "x3dv") || !strcmp(szExt, "xmt") || !strcmp(szExt, "xmta") || !strcmp(szExt, "x3d") || !strcmp(szExt, "jpg") || !strcmp(szExt, "jpeg") || !strcmp(szExt, "png") ) return GF_FALSE; /*check any default stuff that should work with ffmpeg*/ { u32 i; for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) { if (gf_service_check_mime_register(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2], ext)) return GF_TRUE; } } } ffd_parse_options(ffd, url); ctx = NULL; if (open_file(&ctx, szName, NULL, ffd->options ? &ffd->options : NULL)<0) { AVInputFormat *av_in = NULL; /*some extensions not supported by ffmpeg*/ if (ext && !strcmp(szExt, "cmp")) av_in = av_find_input_format("m4v"); if (open_file(&ctx, szName, av_in, ffd->options ? &ffd->options : NULL)<0) { return GF_FALSE; } } if (!ctx) goto exit; if (av_find_stream_info(ctx) <0) goto exit; /*figure out if we can use codecs or not*/ has_video = has_audio = GF_FALSE; for(i = 0; i < (s32)ctx->nb_streams; i++) { AVCodecContext *enc = ctx->streams[i]->codec; switch(enc->codec_type) { case AVMEDIA_TYPE_AUDIO: if (!has_audio) has_audio = GF_TRUE; break; case AVMEDIA_TYPE_VIDEO: if (!has_video) has_video= GF_TRUE; break; default: break; } } if (!has_audio && !has_video) goto exit; ret = GF_TRUE; #if ((LIBAVFORMAT_VERSION_MAJOR == 52) && (LIBAVFORMAT_VERSION_MINOR <= 47)) || (LIBAVFORMAT_VERSION_MAJOR < 52) fmt_out = guess_stream_format(NULL, url, NULL); #else fmt_out = av_guess_format(NULL, url, NULL); #endif if (fmt_out) gf_service_register_mime(plug, fmt_out->mime_type, fmt_out->extensions, fmt_out->name); else { ext = strrchr(szName, '.'); if (ext) { strcpy(szExt, &ext[1]); strlwr(szExt); szExtList = gf_modules_get_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg"); if (!szExtList) { gf_service_register_mime(plug, "application/x-ffmpeg", szExt, "Other Movies (FFMPEG)"); } else if (!strstr(szExtList, szExt)) { u32 len; char *buf; len = (u32) (strlen(szExtList) + strlen(szExt) + 10); buf = (char*)gf_malloc(sizeof(char)*len); sprintf(buf, "\"%s ", szExt); strcat(buf, &szExtList[1]); gf_modules_set_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg", buf); gf_free(buf); } } } exit: #if FF_API_CLOSE_INPUT_FILE if (ctx) av_close_input_file(ctx); #else if (ctx) avformat_close_input(&ctx); #endif return ret; } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119
static Bool FFD_CanHandleURL(GF_InputService *plug, const char *url) { Bool has_audio, has_video; s32 i; AVFormatContext *ctx; AVOutputFormat *fmt_out; Bool ret = GF_FALSE; char *ext, szName[1024], szExt[20]; const char *szExtList; FFDemux *ffd; if (!plug || !url) return GF_FALSE; /*disable RTP/RTSP from ffmpeg*/ if (!strnicmp(url, "rtsp://", 7)) return GF_FALSE; if (!strnicmp(url, "rtspu://", 8)) return GF_FALSE; if (!strnicmp(url, "rtp://", 6)) return GF_FALSE; if (!strnicmp(url, "plato://", 8)) return GF_FALSE; if (!strnicmp(url, "udp://", 6)) return GF_FALSE; if (!strnicmp(url, "tcp://", 6)) return GF_FALSE; if (!strnicmp(url, "data:", 5)) return GF_FALSE; ffd = (FFDemux*)plug->priv; if (strlen(url) >= sizeof(szName)) return GF_FALSE; strcpy(szName, url); ext = strrchr(szName, '#'); if (ext) ext[0] = 0; ext = strrchr(szName, '?'); if (ext) ext[0] = 0; ext = strrchr(szName, '.'); if (ext && strlen(ext) > 19) ext = NULL; if (ext && strlen(ext) > 1 && strlen(ext) <= sizeof(szExt)) { strcpy(szExt, &ext[1]); strlwr(szExt); #ifndef FFMPEG_DEMUX_ENABLE_MPEG2TS if (strstr("ts m2t mts dmb trp", szExt) ) return GF_FALSE; #endif /*note we forbid ffmpeg to handle files we support*/ if (!strcmp(szExt, "mp4") || !strcmp(szExt, "mpg4") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m21") || !strcmp(szExt, "m4v") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m4s") || !strcmp(szExt, "3gs") || !strcmp(szExt, "3gp") || !strcmp(szExt, "3gpp") || !strcmp(szExt, "3gp2") || !strcmp(szExt, "3g2") || !strcmp(szExt, "mp3") || !strcmp(szExt, "ac3") || !strcmp(szExt, "amr") || !strcmp(szExt, "bt") || !strcmp(szExt, "wrl") || !strcmp(szExt, "x3dv") || !strcmp(szExt, "xmt") || !strcmp(szExt, "xmta") || !strcmp(szExt, "x3d") || !strcmp(szExt, "jpg") || !strcmp(szExt, "jpeg") || !strcmp(szExt, "png") ) return GF_FALSE; /*check any default stuff that should work with ffmpeg*/ { u32 i; for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) { if (gf_service_check_mime_register(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2], ext)) return GF_TRUE; } } } ffd_parse_options(ffd, url); ctx = NULL; if (open_file(&ctx, szName, NULL, ffd->options ? &ffd->options : NULL)<0) { AVInputFormat *av_in = NULL; /*some extensions not supported by ffmpeg*/ if (ext && !strcmp(szExt, "cmp")) av_in = av_find_input_format("m4v"); if (open_file(&ctx, szName, av_in, ffd->options ? &ffd->options : NULL)<0) { return GF_FALSE; } } if (!ctx) goto exit; if (av_find_stream_info(ctx) <0) goto exit; /*figure out if we can use codecs or not*/ has_video = has_audio = GF_FALSE; for(i = 0; i < (s32)ctx->nb_streams; i++) { AVCodecContext *enc = ctx->streams[i]->codec; switch(enc->codec_type) { case AVMEDIA_TYPE_AUDIO: if (!has_audio) has_audio = GF_TRUE; break; case AVMEDIA_TYPE_VIDEO: if (!has_video) has_video= GF_TRUE; break; default: break; } } if (!has_audio && !has_video) goto exit; ret = GF_TRUE; #if ((LIBAVFORMAT_VERSION_MAJOR == 52) && (LIBAVFORMAT_VERSION_MINOR <= 47)) || (LIBAVFORMAT_VERSION_MAJOR < 52) fmt_out = guess_stream_format(NULL, url, NULL); #else fmt_out = av_guess_format(NULL, url, NULL); #endif if (fmt_out) gf_service_register_mime(plug, fmt_out->mime_type, fmt_out->extensions, fmt_out->name); else { ext = strrchr(szName, '.'); if (ext) { strcpy(szExt, &ext[1]); strlwr(szExt); szExtList = gf_modules_get_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg"); if (!szExtList) { gf_service_register_mime(plug, "application/x-ffmpeg", szExt, "Other Movies (FFMPEG)"); } else if (!strstr(szExtList, szExt)) { u32 len; char *buf; len = (u32) (strlen(szExtList) + strlen(szExt) + 10); buf = (char*)gf_malloc(sizeof(char)*len); sprintf(buf, "\"%s ", szExt); strcat(buf, &szExtList[1]); gf_modules_set_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg", buf); gf_free(buf); } } } exit: #if FF_API_CLOSE_INPUT_FILE if (ctx) av_close_input_file(ctx); #else if (ctx) avformat_close_input(&ctx); #endif return ret; }
169,792
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void svc_rdma_xdr_encode_write_list(struct rpcrdma_msg *rmsgp, int chunks) { struct rpcrdma_write_array *ary; /* no read-list */ rmsgp->rm_body.rm_chunks[0] = xdr_zero; /* write-array discrim */ ary = (struct rpcrdma_write_array *) &rmsgp->rm_body.rm_chunks[1]; ary->wc_discrim = xdr_one; ary->wc_nchunks = cpu_to_be32(chunks); /* write-list terminator */ ary->wc_array[chunks].wc_target.rs_handle = xdr_zero; /* reply-array discriminator */ ary->wc_array[chunks].wc_target.rs_length = xdr_zero; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
void svc_rdma_xdr_encode_write_list(struct rpcrdma_msg *rmsgp, int chunks)
168,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct sco_options opts; struct sco_conninfo cinfo; int len, err = 0; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case SCO_OPTIONS: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } opts.mtu = sco_pi(sk)->conn->mtu; BT_DBG("mtu %d", opts.mtu); len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *)&opts, len)) err = -EFAULT; break; case SCO_CONNINFO: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } cinfo.hci_handle = sco_pi(sk)->conn->hcon->handle; memcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *)&cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } Commit Message: Bluetooth: sco: fix information leak to userspace struct sco_conninfo has one padding byte in the end. Local variable cinfo of type sco_conninfo is copied to userspace with this uninizialized one byte, leading to old stack contents leak. Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Gustavo F. Padovan <[email protected]> CWE ID: CWE-200
static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct sco_options opts; struct sco_conninfo cinfo; int len, err = 0; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case SCO_OPTIONS: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } opts.mtu = sco_pi(sk)->conn->mtu; BT_DBG("mtu %d", opts.mtu); len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *)&opts, len)) err = -EFAULT; break; case SCO_CONNINFO: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = sco_pi(sk)->conn->hcon->handle; memcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *)&cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; }
165,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderFrameHostManager::DetermineSiteInstanceForURL( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* current_instance, SiteInstance* dest_instance, ui::PageTransition transition, bool dest_is_restore, bool dest_is_view_source_mode, bool force_browsing_instance_swap, bool was_server_redirect) { SiteInstanceImpl* current_instance_impl = static_cast<SiteInstanceImpl*>(current_instance); NavigationControllerImpl& controller = delegate_->GetControllerForRenderManager(); BrowserContext* browser_context = controller.GetBrowserContext(); if (dest_instance) { if (force_browsing_instance_swap) { CHECK(!dest_instance->IsRelatedSiteInstance( render_frame_host_->GetSiteInstance())); } return SiteInstanceDescriptor(dest_instance); } if (force_browsing_instance_swap) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kProcessPerSite) && ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) { return SiteInstanceDescriptor(current_instance_impl); } if (SiteIsolationPolicy::AreCrossProcessFramesPossible() && !frame_tree_node_->IsMainFrame()) { SiteInstance* parent_site_instance = frame_tree_node_->parent()->current_frame_host()->GetSiteInstance(); if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) && dest_url.SchemeIs(kChromeUIScheme)) { return SiteInstanceDescriptor(parent_site_instance); } } if (!current_instance_impl->HasSite()) { bool use_process_per_site = RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) && RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url); if (current_instance_impl->HasRelatedSiteInstance(dest_url) || use_process_per_site) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } if (current_instance_impl->HasWrongProcessForURL(dest_url)) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); if (dest_is_view_source_mode) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } if (dest_is_restore && GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) { current_instance_impl->SetSite(dest_url); } return SiteInstanceDescriptor(current_instance_impl); } NavigationEntry* current_entry = controller.GetLastCommittedEntry(); if (interstitial_page_) { current_entry = controller.GetEntryAtOffset(-1); } if (current_entry && current_entry->IsViewSourceMode() != dest_is_view_source_mode && !IsRendererDebugURL(dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } GURL about_blank(url::kAboutBlankURL); GURL about_srcdoc(content::kAboutSrcDocURL); bool dest_is_data_or_about = dest_url == about_srcdoc || dest_url == about_blank || dest_url.scheme() == url::kDataScheme; if (source_instance && dest_is_data_or_about && !was_server_redirect) return SiteInstanceDescriptor(source_instance); if (IsCurrentlySameSite(render_frame_host_.get(), dest_url)) return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) { if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* main_frame = frame_tree_node_->frame_tree()->root()->current_frame_host(); if (IsCurrentlySameSite(main_frame, dest_url)) return SiteInstanceDescriptor(main_frame->GetSiteInstance()); } if (frame_tree_node_->opener()) { RenderFrameHostImpl* opener_frame = frame_tree_node_->opener()->current_frame_host(); if (IsCurrentlySameSite(opener_frame, dest_url)) return SiteInstanceDescriptor(opener_frame->GetSiteInstance()); } } if (!frame_tree_node_->IsMainFrame() && SiteIsolationPolicy::IsTopDocumentIsolationEnabled() && !SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url)) { if (GetContentClient() ->browser() ->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation( dest_url, current_instance)) { return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); } return SiteInstanceDescriptor( browser_context, dest_url, SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME); } if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* parent = frame_tree_node_->parent()->current_frame_host(); bool dest_url_requires_dedicated_process = SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url); if (!parent->GetSiteInstance()->RequiresDedicatedProcess() && !dest_url_requires_dedicated_process) { return SiteInstanceDescriptor(parent->GetSiteInstance()); } } return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
RenderFrameHostManager::DetermineSiteInstanceForURL( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* current_instance, SiteInstance* dest_instance, ui::PageTransition transition, bool dest_is_restore, bool dest_is_view_source_mode, bool force_browsing_instance_swap, bool was_server_redirect) { SiteInstanceImpl* current_instance_impl = static_cast<SiteInstanceImpl*>(current_instance); NavigationControllerImpl& controller = delegate_->GetControllerForRenderManager(); BrowserContext* browser_context = controller.GetBrowserContext(); if (dest_instance) { if (force_browsing_instance_swap) { CHECK(!dest_instance->IsRelatedSiteInstance( render_frame_host_->GetSiteInstance())); } return SiteInstanceDescriptor(dest_instance); } if (force_browsing_instance_swap) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kProcessPerSite) && ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) { return SiteInstanceDescriptor(current_instance_impl); } if (SiteIsolationPolicy::AreCrossProcessFramesPossible() && !frame_tree_node_->IsMainFrame()) { SiteInstance* parent_site_instance = frame_tree_node_->parent()->current_frame_host()->GetSiteInstance(); if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) && dest_url.SchemeIs(kChromeUIScheme)) { return SiteInstanceDescriptor(parent_site_instance); } } if (!current_instance_impl->HasSite()) { bool use_process_per_site = RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) && RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url); if (current_instance_impl->HasRelatedSiteInstance(dest_url) || use_process_per_site) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } if (current_instance_impl->HasWrongProcessForURL(dest_url)) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); if (dest_is_view_source_mode) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } if (dest_is_restore && GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) { current_instance_impl->SetSite(dest_url); } return SiteInstanceDescriptor(current_instance_impl); } NavigationEntry* current_entry = controller.GetLastCommittedEntry(); if (delegate_->GetInterstitialForRenderManager()) { current_entry = controller.GetEntryAtOffset(-1); } if (current_entry && current_entry->IsViewSourceMode() != dest_is_view_source_mode && !IsRendererDebugURL(dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } GURL about_blank(url::kAboutBlankURL); GURL about_srcdoc(content::kAboutSrcDocURL); bool dest_is_data_or_about = dest_url == about_srcdoc || dest_url == about_blank || dest_url.scheme() == url::kDataScheme; if (source_instance && dest_is_data_or_about && !was_server_redirect) return SiteInstanceDescriptor(source_instance); if (IsCurrentlySameSite(render_frame_host_.get(), dest_url)) return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) { if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* main_frame = frame_tree_node_->frame_tree()->root()->current_frame_host(); if (IsCurrentlySameSite(main_frame, dest_url)) return SiteInstanceDescriptor(main_frame->GetSiteInstance()); } if (frame_tree_node_->opener()) { RenderFrameHostImpl* opener_frame = frame_tree_node_->opener()->current_frame_host(); if (IsCurrentlySameSite(opener_frame, dest_url)) return SiteInstanceDescriptor(opener_frame->GetSiteInstance()); } } if (!frame_tree_node_->IsMainFrame() && SiteIsolationPolicy::IsTopDocumentIsolationEnabled() && !SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url)) { if (GetContentClient() ->browser() ->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation( dest_url, current_instance)) { return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); } return SiteInstanceDescriptor( browser_context, dest_url, SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME); } if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* parent = frame_tree_node_->parent()->current_frame_host(); bool dest_url_requires_dedicated_process = SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url); if (!parent->GetSiteInstance()->RequiresDedicatedProcess() && !dest_url_requires_dedicated_process) { return SiteInstanceDescriptor(parent->GetSiteInstance()); } } return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); }
172,320
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437) CWE ID: CWE-125
NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { jspReplaceWithOrAddToRoot(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; }
169,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DoCheckFakeData(uint8* audio_data, size_t length) { Type* output = reinterpret_cast<Type*>(audio_data); for (size_t i = 0; i < length; i++) { EXPECT_TRUE(algorithm_.is_muted() || output[i] != 0); } } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void DoCheckFakeData(uint8* audio_data, size_t length) { if (algorithm_.is_muted()) ASSERT_EQ(sum, 0); else ASSERT_NE(sum, 0); }
171,531
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: HeadlessWebContentsImpl::HeadlessWebContentsImpl( content::WebContents* web_contents, HeadlessBrowserContextImpl* browser_context) : content::WebContentsObserver(web_contents), web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)), web_contents_(web_contents), agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)), inject_mojo_services_into_isolated_world_(false), browser_context_(browser_context), render_process_host_(web_contents->GetMainFrame()->GetProcess()), weak_ptr_factory_(this) { #if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD) HeadlessPrintManager::CreateForWebContents(web_contents); //// TODO(weili): Add support for printing OOPIFs. #endif web_contents->GetMutableRendererPrefs()->accept_languages = browser_context->options()->accept_language(); web_contents_->SetDelegate(web_contents_delegate_.get()); render_process_host_->AddObserver(this); agent_host_->AddObserver(this); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
HeadlessWebContentsImpl::HeadlessWebContentsImpl( content::WebContents* web_contents, HeadlessBrowserContextImpl* browser_context) : content::WebContentsObserver(web_contents), web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)), web_contents_(web_contents), agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)), inject_mojo_services_into_isolated_world_(false), browser_context_(browser_context), render_process_host_(web_contents->GetMainFrame()->GetProcess()), weak_ptr_factory_(this) { #if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD) HeadlessPrintManager::CreateForWebContents(web_contents); //// TODO(weili): Add support for printing OOPIFs. #endif web_contents->GetMutableRendererPrefs()->accept_languages = browser_context->options()->accept_language(); web_contents_->SetDelegate(web_contents_delegate_.get()); render_process_host_->AddObserver(this); agent_host_->AddObserver(this); }
171,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_emit_signals (MyObject *obj, GError **error) { GValue val = {0, }; g_signal_emit (obj, signals[SIG0], 0, "foo", 22, "moo"); g_value_init (&val, G_TYPE_STRING); g_value_set_string (&val, "bar"); g_signal_emit (obj, signals[SIG1], 0, "baz", &val); g_value_unset (&val); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_emit_signals (MyObject *obj, GError **error)
165,096
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_video::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr) { unsigned int index = 0; OMX_U8 *temp_buff ; if (bufferHdr == NULL || m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: free_input: Invalid bufferHdr[%p] or m_inp_mem_ptr[%p]", bufferHdr, m_inp_mem_ptr); return OMX_ErrorBadParameter; } index = bufferHdr - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr); #ifdef _ANDROID_ICS_ if (meta_mode_enable) { if (index < m_sInPortDef.nBufferCountActual) { memset(&meta_buffer_hdr[index], 0, sizeof(meta_buffer_hdr[index])); memset(&meta_buffers[index], 0, sizeof(meta_buffers[index])); } if (!mUseProxyColorFormat) return OMX_ErrorNone; else { c2d_conv.close(); opaque_buffer_hdr[index] = NULL; } } #endif if (index < m_sInPortDef.nBufferCountActual && !mUseProxyColorFormat && dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_LOW("ERROR: dev_free_buf() Failed for i/p buf"); } if (index < m_sInPortDef.nBufferCountActual && m_pInput_pmem) { if (m_pInput_pmem[index].fd > 0 && input_use_buffer == false) { DEBUG_PRINT_LOW("FreeBuffer:: i/p AllocateBuffer case"); if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); } else { free(m_pInput_pmem[index].buffer); } close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else if (m_pInput_pmem[index].fd > 0 && (input_use_buffer == true && m_use_input_pmem == OMX_FALSE)) { DEBUG_PRINT_LOW("FreeBuffer:: i/p Heap UseBuffer case"); if (dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_ERROR("ERROR: dev_free_buf() Failed for i/p buf"); } if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); } close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else { DEBUG_PRINT_ERROR("FreeBuffer:: fd is invalid or i/p PMEM UseBuffer case"); } } return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27903498 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVenc problem #3) CRs-Fixed: 1010088 Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3 CWE ID:
OMX_ERRORTYPE omx_video::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr) { unsigned int index = 0; OMX_U8 *temp_buff ; if (bufferHdr == NULL || m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: free_input: Invalid bufferHdr[%p] or m_inp_mem_ptr[%p]", bufferHdr, m_inp_mem_ptr); return OMX_ErrorBadParameter; } index = bufferHdr - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr); #ifdef _ANDROID_ICS_ if (meta_mode_enable) { if (index < m_sInPortDef.nBufferCountActual) { memset(&meta_buffer_hdr[index], 0, sizeof(meta_buffer_hdr[index])); memset(&meta_buffers[index], 0, sizeof(meta_buffers[index])); } if (!mUseProxyColorFormat) return OMX_ErrorNone; else { c2d_conv.close(); opaque_buffer_hdr[index] = NULL; } } #endif if (index < m_sInPortDef.nBufferCountActual && !mUseProxyColorFormat && dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_LOW("ERROR: dev_free_buf() Failed for i/p buf"); } if (index < m_sInPortDef.nBufferCountActual && m_pInput_pmem) { auto_lock l(m_lock); if (m_pInput_pmem[index].fd > 0 && input_use_buffer == false) { DEBUG_PRINT_LOW("FreeBuffer:: i/p AllocateBuffer case"); if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); } else { free(m_pInput_pmem[index].buffer); } m_pInput_pmem[index].buffer = NULL; close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else if (m_pInput_pmem[index].fd > 0 && (input_use_buffer == true && m_use_input_pmem == OMX_FALSE)) { DEBUG_PRINT_LOW("FreeBuffer:: i/p Heap UseBuffer case"); if (dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_ERROR("ERROR: dev_free_buf() Failed for i/p buf"); } if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); m_pInput_pmem[index].buffer = NULL; } close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else { DEBUG_PRINT_ERROR("FreeBuffer:: fd is invalid or i/p PMEM UseBuffer case"); } } return OMX_ErrorNone; }
173,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output; size_t ssh1keylen, rlen, slen, ilen, olen; int r; u_int ssh1cipher = 0; if (!compat20) { if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 || (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 || (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 || (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0) return r; if (ssh1cipher > INT_MAX) return SSH_ERR_KEY_UNKNOWN_CIPHER; ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen, (int)ssh1cipher); if (cipher_get_keyiv_len(state->send_context) != (int)slen || cipher_get_keyiv_len(state->receive_context) != (int)rlen) return SSH_ERR_INVALID_FORMAT; if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 || (r = cipher_set_keyiv(state->receive_context, ivin)) != 0) return r; } else { if ((r = kex_from_blob(m, &ssh->kex)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 || (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0) return r; /* * We set the time here so that in post-auth privsep slave we * count from the completion of the authentication. */ state->rekey_time = monotime(); /* XXX ssh_set_newkeys overrides p_read.packets? XXX */ if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 || (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0) return r; } if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0) return r; if (cipher_get_keycontext(state->send_context, NULL) != (int)slen || cipher_get_keycontext(state->receive_context, NULL) != (int)rlen) return SSH_ERR_INVALID_FORMAT; cipher_set_keycontext(state->send_context, keyout); cipher_set_keycontext(state->receive_context, keyin); if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 || (r = ssh_packet_set_postauth(ssh)) != 0) return r; sshbuf_reset(state->input); sshbuf_reset(state->output); if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 || (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 || (r = sshbuf_put(state->input, input, ilen)) != 0 || (r = sshbuf_put(state->output, output, olen)) != 0) return r; if (sshbuf_len(m)) return SSH_ERR_INVALID_FORMAT; debug3("%s: done", __func__); return 0; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output; size_t ssh1keylen, rlen, slen, ilen, olen; int r; u_int ssh1cipher = 0; if (!compat20) { if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 || (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 || (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 || (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0) return r; if (ssh1cipher > INT_MAX) return SSH_ERR_KEY_UNKNOWN_CIPHER; ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen, (int)ssh1cipher); if (cipher_get_keyiv_len(state->send_context) != (int)slen || cipher_get_keyiv_len(state->receive_context) != (int)rlen) return SSH_ERR_INVALID_FORMAT; if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 || (r = cipher_set_keyiv(state->receive_context, ivin)) != 0) return r; } else { if ((r = kex_from_blob(m, &ssh->kex)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 || (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0) return r; /* * We set the time here so that in post-auth privsep slave we * count from the completion of the authentication. */ state->rekey_time = monotime(); /* XXX ssh_set_newkeys overrides p_read.packets? XXX */ if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 || (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0) return r; } if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0) return r; if (cipher_get_keycontext(state->send_context, NULL) != (int)slen || cipher_get_keycontext(state->receive_context, NULL) != (int)rlen) return SSH_ERR_INVALID_FORMAT; cipher_set_keycontext(state->send_context, keyout); cipher_set_keycontext(state->receive_context, keyin); if ((r = ssh_packet_set_postauth(ssh)) != 0) return r; sshbuf_reset(state->input); sshbuf_reset(state->output); if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 || (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 || (r = sshbuf_put(state->input, input, ilen)) != 0 || (r = sshbuf_put(state->output, output, olen)) != 0) return r; if (sshbuf_len(m)) return SSH_ERR_INVALID_FORMAT; debug3("%s: done", __func__); return 0; }
168,656
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: tt_cmap8_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_Byte* is32; FT_UInt32 length; FT_UInt32 num_groups; if ( table + 16 + 8192 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); if ( table + length > valid->limit || length < 8208 ) FT_INVALID_TOO_SHORT; is32 = table + 12; p = is32 + 8192; /* skip `is32' array */ num_groups = TT_NEXT_ULONG( p ); if ( p + num_groups * 12 > valid->limit ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ { FT_UInt32 n, start, end, start_id, count, last = 0; for ( n = 0; n < num_groups; n++ ) { FT_UInt hi, lo; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; count = (FT_UInt32)( end - start + 1 ); if ( start & ~0xFFFFU ) { /* start_hi != 0; check that is32[i] is 1 for each i in */ /* the `hi' and `lo' of the range [start..end] */ for ( ; count > 0; count--, start++ ) { hi = (FT_UInt)( start >> 16 ); lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 ) FT_INVALID_DATA; if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 ) FT_INVALID_DATA; } } else { /* start_hi == 0; check that is32[i] is 0 for each i in */ /* the range [start..end] */ /* end_hi cannot be != 0! */ if ( end & ~0xFFFFU ) FT_INVALID_DATA; for ( ; count > 0; count--, start++ ) { lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 ) FT_INVALID_DATA; } } } last = end; } } return SFNT_Err_Ok; } Commit Message: CWE ID: CWE-189
tt_cmap8_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_Byte* is32; FT_UInt32 length; FT_UInt32 num_groups; if ( table + 16 + 8192 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 ) FT_INVALID_TOO_SHORT; is32 = table + 12; p = is32 + 8192; /* skip `is32' array */ num_groups = TT_NEXT_ULONG( p ); if ( p + num_groups * 12 > valid->limit ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ { FT_UInt32 n, start, end, start_id, count, last = 0; for ( n = 0; n < num_groups; n++ ) { FT_UInt hi, lo; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; count = (FT_UInt32)( end - start + 1 ); if ( start & ~0xFFFFU ) { /* start_hi != 0; check that is32[i] is 1 for each i in */ /* the `hi' and `lo' of the range [start..end] */ for ( ; count > 0; count--, start++ ) { hi = (FT_UInt)( start >> 16 ); lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 ) FT_INVALID_DATA; if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 ) FT_INVALID_DATA; } } else { /* start_hi == 0; check that is32[i] is 0 for each i in */ /* the range [start..end] */ /* end_hi cannot be != 0! */ if ( end & ~0xFFFFU ) FT_INVALID_DATA; for ( ; count > 0; count--, start++ ) { lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 ) FT_INVALID_DATA; } } } last = end; } } return SFNT_Err_Ok; }
164,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebUIExtension::Send(gin::Arguments* args) { blink::WebLocalFrame* frame; RenderFrame* render_frame; if (!ShouldRespondToRequest(&frame, &render_frame)) return; std::string message; if (!args->GetNext(&message)) { args->ThrowError(); return; } if (base::EndsWith(message, "RequiringGesture", base::CompareCase::SENSITIVE) && !blink::WebUserGestureIndicator::IsProcessingUserGesture(frame)) { NOTREACHED(); return; } std::unique_ptr<base::ListValue> content; if (args->PeekNext().IsEmpty() || args->PeekNext()->IsUndefined()) { content.reset(new base::ListValue()); } else { v8::Local<v8::Object> obj; if (!args->GetNext(&obj)) { args->ThrowError(); return; } content = base::ListValue::From(V8ValueConverter::Create()->FromV8Value( obj, frame->MainWorldScriptContext())); DCHECK(content); } render_frame->Send(new FrameHostMsg_WebUISend(render_frame->GetRoutingID(), frame->GetDocument().Url(), message, *content)); } Commit Message: Validate frame after conversion in chrome.send BUG=797511 TEST=Manually, see https://crbug.com/797511#c1 Change-Id: Ib1a99db4d7648fb1325eb6d7af4ef111d6dda4cb Reviewed-on: https://chromium-review.googlesource.com/844076 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#526197} CWE ID: CWE-416
void WebUIExtension::Send(gin::Arguments* args) { blink::WebLocalFrame* frame; RenderFrame* render_frame; if (!ShouldRespondToRequest(&frame, &render_frame)) return; std::string message; if (!args->GetNext(&message)) { args->ThrowError(); return; } if (base::EndsWith(message, "RequiringGesture", base::CompareCase::SENSITIVE) && !blink::WebUserGestureIndicator::IsProcessingUserGesture(frame)) { NOTREACHED(); return; } std::unique_ptr<base::ListValue> content; if (args->PeekNext().IsEmpty() || args->PeekNext()->IsUndefined()) { content.reset(new base::ListValue()); } else { v8::Local<v8::Object> obj; if (!args->GetNext(&obj)) { args->ThrowError(); return; } content = base::ListValue::From(V8ValueConverter::Create()->FromV8Value( obj, frame->MainWorldScriptContext())); DCHECK(content); // The conversion of |obj| could have triggered arbitrary JavaScript code, // so check that the frame is still valid to avoid dereferencing a stale // pointer. if (frame != blink::WebLocalFrame::FrameForCurrentContext()) { NOTREACHED(); return; } } render_frame->Send(new FrameHostMsg_WebUISend(render_frame->GetRoutingID(), frame->GetDocument().Url(), message, *content)); }
172,695
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize enhanced image attributes. */ assert(image != (const 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); enhance_image=CloneImage(image,0,0,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; register const Quantum *magick_restrict r; GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); if (total_weight > MagickEpsilon) { pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); } SetPixelViaPixelInfo(image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1611 CWE ID: CWE-119
MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize enhanced image attributes. */ assert(image != (const 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); enhance_image=CloneImage(image,0,0,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; register const Quantum *magick_restrict r; GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); if (total_weight > MagickEpsilon) { pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); } SetPixelViaPixelInfo(enhance_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); }
169,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } Commit Message: l2tp: fix info leak in l2tp_ip6_recvmsg() The L2TP code for IPv6 fails to initialize the l2tp_conn_id member of struct sockaddr_l2tpip6 and therefore leaks four bytes kernel stack in l2tp_ip6_recvmsg() in case msg_name is set. Initialize l2tp_conn_id with 0 to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_conn_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; }
166,037
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IsSystemModal(aura::Window* window) { return window->transient_parent() && window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; } Commit Message: Removed requirement for ash::Window::transient_parent() presence for system modal dialogs. BUG=130420 TEST=SystemModalContainerLayoutManagerTest.ModalTransientAndNonTransient Review URL: https://chromiumcodereview.appspot.com/10514012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@140647 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool IsSystemModal(aura::Window* window) { return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; }
170,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a) { return (tsfb->numlvls > 0) ? jpc_tsfb_synthesize2(tsfb, jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)), jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a), jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0; } Commit Message: Fixed an integral type promotion problem by adding a JAS_CAST. Modified the jpc_tsfb_synthesize function so that it will be a noop for an empty sequence (in order to avoid dereferencing a null pointer). CWE ID: CWE-476
int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a) { return (tsfb->numlvls > 0 && jas_seq2d_size(a)) ? jpc_tsfb_synthesize2(tsfb, jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)), jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a), jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0; }
168,478
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHPAPI php_stream *_php_stream_memory_create(int mode STREAMS_DC TSRMLS_DC) { php_stream_memory_data *self; php_stream *stream; self = emalloc(sizeof(*self)); self->data = NULL; self->fpos = 0; self->fsize = 0; self->smax = ~0u; self->mode = mode; stream = php_stream_alloc_rel(&php_stream_memory_ops, self, 0, mode & TEMP_STREAM_READONLY ? "rb" : "w+b"); stream->flags |= PHP_STREAM_FLAG_NO_BUFFER; return stream; } Commit Message: CWE ID: CWE-20
PHPAPI php_stream *_php_stream_memory_create(int mode STREAMS_DC TSRMLS_DC) { php_stream_memory_data *self; php_stream *stream; self = emalloc(sizeof(*self)); self->data = NULL; self->fpos = 0; self->fsize = 0; self->smax = ~0u; self->mode = mode; stream = php_stream_alloc_rel(&php_stream_memory_ops, self, 0, mode & TEMP_STREAM_READONLY ? "rb" : "w+b"); stream->flags |= PHP_STREAM_FLAG_NO_BUFFER; return stream; }
165,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { char *key; size_t nkey; int i = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; assert(c != NULL); do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if(nkey > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } it = item_get(key, nkey, c, DO_UPDATE); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * "VALUE " * key * " " + flags + " " + data length + "\r\n" + data (with \r\n) */ if (return_cas || !settings.inline_ascii_response) { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix"); item_remove(it); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } *(c->suffixlist + i) = suffix; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || (settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0) { item_remove(it); break; } } else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 || add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d sending key ", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].get_hits++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); *(c->ilist + i) = it; i++; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_misses++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); c->icurr = c->ilist; c->ileft = i; if (return_cas || !settings.inline_ascii_response) { c->suffixcurr = c->suffixlist; c->suffixleft = i; } if (settings.verbose > 1) fprintf(stderr, ">%d END\n", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { out_of_memory(c, "SERVER_ERROR out of memory writing get response"); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } } Commit Message: Don't overflow item refcount on get Counts as a miss if the refcount is too high. ASCII multigets are the only time refcounts can be held for so long. doing a dirty read of refcount. is aligned. trying to avoid adding an extra refcount branch for all calls of item_get due to performance. might be able to move it in there after logging refactoring simplifies some of the branches. CWE ID: CWE-190
static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { char *key; size_t nkey; int i = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; assert(c != NULL); do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if(nkey > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } it = limited_get(key, nkey, c); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * "VALUE " * key * " " + flags + " " + data length + "\r\n" + data (with \r\n) */ if (return_cas || !settings.inline_ascii_response) { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix"); item_remove(it); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } *(c->suffixlist + i) = suffix; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || (settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0) { item_remove(it); break; } } else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 || add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d sending key ", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].get_hits++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); *(c->ilist + i) = it; i++; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_misses++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); c->icurr = c->ilist; c->ileft = i; if (return_cas || !settings.inline_ascii_response) { c->suffixcurr = c->suffixlist; c->suffixleft = i; } if (settings.verbose > 1) fprintf(stderr, ">%d END\n", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { out_of_memory(c, "SERVER_ERROR out of memory writing get response"); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } }
168,943
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) { return (OMX_BUFFERHEADERTYPE *)buffer; } Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32 Bug: 20634516 Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c (cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4) CWE ID: CWE-119
OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) {
173,357
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: on_response(void *data, krb5_error_code retval, otp_response response) { struct request_state rs = *(struct request_state *)data; free(data); if (retval == 0 && response != otp_response_success) retval = KRB5_PREAUTH_FAILED; rs.respond(rs.arg, retval, NULL, NULL, NULL); } Commit Message: Prevent requires_preauth bypass [CVE-2015-2694] In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until the request is successfully verified. In the PKINIT kdcpreauth module, don't respond with code 0 on empty input or an unconfigured realm. Together these bugs could cause the KDC preauth framework to erroneously treat a request as pre-authenticated. CVE-2015-2694: In MIT krb5 1.12 and later, when the KDC is configured with PKINIT support, an unauthenticated remote attacker can bypass the requires_preauth flag on a client principal and obtain a ciphertext encrypted in the principal's long-term key. This ciphertext could be used to conduct an off-line dictionary attack against the user's password. CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C ticket: 8160 (new) target_version: 1.13.2 tags: pullup subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694] CWE ID: CWE-264
on_response(void *data, krb5_error_code retval, otp_response response) { struct request_state rs = *(struct request_state *)data; free(data); if (retval == 0 && response != otp_response_success) retval = KRB5_PREAUTH_FAILED; if (retval == 0) rs.enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH; rs.respond(rs.arg, retval, NULL, NULL, NULL); }
166,676
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod) { struct usbnet *dev; struct net_device *net; struct usb_host_interface *interface; struct driver_info *info; struct usb_device *xdev; int status; const char *name; struct usb_driver *driver = to_usb_driver(udev->dev.driver); /* usbnet already took usb runtime pm, so have to enable the feature * for usb interface, otherwise usb_autopm_get_interface may return * failure if RUNTIME_PM is enabled. */ if (!driver->supports_autosuspend) { driver->supports_autosuspend = 1; pm_runtime_enable(&udev->dev); } name = udev->dev.driver->name; info = (struct driver_info *) prod->driver_info; if (!info) { dev_dbg (&udev->dev, "blacklisted by %s\n", name); return -ENODEV; } xdev = interface_to_usbdev (udev); interface = udev->cur_altsetting; status = -ENOMEM; net = alloc_etherdev(sizeof(*dev)); if (!net) goto out; /* netdev_printk() needs this so do it as early as possible */ SET_NETDEV_DEV(net, &udev->dev); dev = netdev_priv(net); dev->udev = xdev; dev->intf = udev; dev->driver_info = info; dev->driver_name = name; dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK); init_waitqueue_head(&dev->wait); skb_queue_head_init (&dev->rxq); skb_queue_head_init (&dev->txq); skb_queue_head_init (&dev->done); skb_queue_head_init(&dev->rxq_pause); dev->bh.func = usbnet_bh; dev->bh.data = (unsigned long) dev; INIT_WORK (&dev->kevent, usbnet_deferred_kevent); init_usb_anchor(&dev->deferred); dev->delay.function = usbnet_bh; dev->delay.data = (unsigned long) dev; init_timer (&dev->delay); mutex_init (&dev->phy_mutex); mutex_init(&dev->interrupt_mutex); dev->interrupt_count = 0; dev->net = net; strcpy (net->name, "usb%d"); memcpy (net->dev_addr, node_id, sizeof node_id); /* rx and tx sides can use different message sizes; * bind() should set rx_urb_size in that case. */ dev->hard_mtu = net->mtu + net->hard_header_len; net->netdev_ops = &usbnet_netdev_ops; net->watchdog_timeo = TX_TIMEOUT_JIFFIES; net->ethtool_ops = &usbnet_ethtool_ops; if (info->bind) { status = info->bind (dev, udev); if (status < 0) goto out1; if ((dev->driver_info->flags & FLAG_ETHER) != 0 && ((dev->driver_info->flags & FLAG_POINTTOPOINT) == 0 || (net->dev_addr [0] & 0x02) == 0)) strcpy (net->name, "eth%d"); /* WLAN devices should always be named "wlan%d" */ if ((dev->driver_info->flags & FLAG_WLAN) != 0) strcpy(net->name, "wlan%d"); /* WWAN devices should always be named "wwan%d" */ if ((dev->driver_info->flags & FLAG_WWAN) != 0) strcpy(net->name, "wwan%d"); /* devices that cannot do ARP */ if ((dev->driver_info->flags & FLAG_NOARP) != 0) net->flags |= IFF_NOARP; /* maybe the remote can't receive an Ethernet MTU */ if (net->mtu > (dev->hard_mtu - net->hard_header_len)) net->mtu = dev->hard_mtu - net->hard_header_len; } else if (!info->in || !info->out) status = usbnet_get_endpoints (dev, udev); else { dev->in = usb_rcvbulkpipe (xdev, info->in); dev->out = usb_sndbulkpipe (xdev, info->out); if (!(info->flags & FLAG_NO_SETINT)) status = usb_set_interface (xdev, interface->desc.bInterfaceNumber, interface->desc.bAlternateSetting); else status = 0; } if (status >= 0 && dev->status) status = init_status (dev, udev); if (status < 0) goto out3; if (!dev->rx_urb_size) dev->rx_urb_size = dev->hard_mtu; dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1); /* let userspace know we have a random address */ if (ether_addr_equal(net->dev_addr, node_id)) net->addr_assign_type = NET_ADDR_RANDOM; if ((dev->driver_info->flags & FLAG_WLAN) != 0) SET_NETDEV_DEVTYPE(net, &wlan_type); if ((dev->driver_info->flags & FLAG_WWAN) != 0) SET_NETDEV_DEVTYPE(net, &wwan_type); /* initialize max rx_qlen and tx_qlen */ usbnet_update_max_qlen(dev); if (dev->can_dma_sg && !(info->flags & FLAG_SEND_ZLP) && !(info->flags & FLAG_MULTI_PACKET)) { dev->padding_pkt = kzalloc(1, GFP_KERNEL); if (!dev->padding_pkt) { status = -ENOMEM; goto out4; } } status = register_netdev (net); if (status) goto out5; netif_info(dev, probe, dev->net, "register '%s' at usb-%s-%s, %s, %pM\n", udev->dev.driver->name, xdev->bus->bus_name, xdev->devpath, dev->driver_info->description, net->dev_addr); usb_set_intfdata (udev, dev); netif_device_attach (net); if (dev->driver_info->flags & FLAG_LINK_INTR) usbnet_link_change(dev, 0, 0); return 0; out5: kfree(dev->padding_pkt); out4: usb_free_urb(dev->interrupt); out3: if (info->unbind) info->unbind (dev, udev); out1: free_netdev(net); out: return status; } Commit Message: usbnet: cleanup after bind() in probe() In case bind() works, but a later error forces bailing in probe() in error cases work and a timer may be scheduled. They must be killed. This fixes an error case related to the double free reported in http://www.spinics.net/lists/netdev/msg367669.html and needs to go on top of Linus' fix to cdc-ncm. Signed-off-by: Oliver Neukum <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod) { struct usbnet *dev; struct net_device *net; struct usb_host_interface *interface; struct driver_info *info; struct usb_device *xdev; int status; const char *name; struct usb_driver *driver = to_usb_driver(udev->dev.driver); /* usbnet already took usb runtime pm, so have to enable the feature * for usb interface, otherwise usb_autopm_get_interface may return * failure if RUNTIME_PM is enabled. */ if (!driver->supports_autosuspend) { driver->supports_autosuspend = 1; pm_runtime_enable(&udev->dev); } name = udev->dev.driver->name; info = (struct driver_info *) prod->driver_info; if (!info) { dev_dbg (&udev->dev, "blacklisted by %s\n", name); return -ENODEV; } xdev = interface_to_usbdev (udev); interface = udev->cur_altsetting; status = -ENOMEM; net = alloc_etherdev(sizeof(*dev)); if (!net) goto out; /* netdev_printk() needs this so do it as early as possible */ SET_NETDEV_DEV(net, &udev->dev); dev = netdev_priv(net); dev->udev = xdev; dev->intf = udev; dev->driver_info = info; dev->driver_name = name; dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK); init_waitqueue_head(&dev->wait); skb_queue_head_init (&dev->rxq); skb_queue_head_init (&dev->txq); skb_queue_head_init (&dev->done); skb_queue_head_init(&dev->rxq_pause); dev->bh.func = usbnet_bh; dev->bh.data = (unsigned long) dev; INIT_WORK (&dev->kevent, usbnet_deferred_kevent); init_usb_anchor(&dev->deferred); dev->delay.function = usbnet_bh; dev->delay.data = (unsigned long) dev; init_timer (&dev->delay); mutex_init (&dev->phy_mutex); mutex_init(&dev->interrupt_mutex); dev->interrupt_count = 0; dev->net = net; strcpy (net->name, "usb%d"); memcpy (net->dev_addr, node_id, sizeof node_id); /* rx and tx sides can use different message sizes; * bind() should set rx_urb_size in that case. */ dev->hard_mtu = net->mtu + net->hard_header_len; net->netdev_ops = &usbnet_netdev_ops; net->watchdog_timeo = TX_TIMEOUT_JIFFIES; net->ethtool_ops = &usbnet_ethtool_ops; if (info->bind) { status = info->bind (dev, udev); if (status < 0) goto out1; if ((dev->driver_info->flags & FLAG_ETHER) != 0 && ((dev->driver_info->flags & FLAG_POINTTOPOINT) == 0 || (net->dev_addr [0] & 0x02) == 0)) strcpy (net->name, "eth%d"); /* WLAN devices should always be named "wlan%d" */ if ((dev->driver_info->flags & FLAG_WLAN) != 0) strcpy(net->name, "wlan%d"); /* WWAN devices should always be named "wwan%d" */ if ((dev->driver_info->flags & FLAG_WWAN) != 0) strcpy(net->name, "wwan%d"); /* devices that cannot do ARP */ if ((dev->driver_info->flags & FLAG_NOARP) != 0) net->flags |= IFF_NOARP; /* maybe the remote can't receive an Ethernet MTU */ if (net->mtu > (dev->hard_mtu - net->hard_header_len)) net->mtu = dev->hard_mtu - net->hard_header_len; } else if (!info->in || !info->out) status = usbnet_get_endpoints (dev, udev); else { dev->in = usb_rcvbulkpipe (xdev, info->in); dev->out = usb_sndbulkpipe (xdev, info->out); if (!(info->flags & FLAG_NO_SETINT)) status = usb_set_interface (xdev, interface->desc.bInterfaceNumber, interface->desc.bAlternateSetting); else status = 0; } if (status >= 0 && dev->status) status = init_status (dev, udev); if (status < 0) goto out3; if (!dev->rx_urb_size) dev->rx_urb_size = dev->hard_mtu; dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1); /* let userspace know we have a random address */ if (ether_addr_equal(net->dev_addr, node_id)) net->addr_assign_type = NET_ADDR_RANDOM; if ((dev->driver_info->flags & FLAG_WLAN) != 0) SET_NETDEV_DEVTYPE(net, &wlan_type); if ((dev->driver_info->flags & FLAG_WWAN) != 0) SET_NETDEV_DEVTYPE(net, &wwan_type); /* initialize max rx_qlen and tx_qlen */ usbnet_update_max_qlen(dev); if (dev->can_dma_sg && !(info->flags & FLAG_SEND_ZLP) && !(info->flags & FLAG_MULTI_PACKET)) { dev->padding_pkt = kzalloc(1, GFP_KERNEL); if (!dev->padding_pkt) { status = -ENOMEM; goto out4; } } status = register_netdev (net); if (status) goto out5; netif_info(dev, probe, dev->net, "register '%s' at usb-%s-%s, %s, %pM\n", udev->dev.driver->name, xdev->bus->bus_name, xdev->devpath, dev->driver_info->description, net->dev_addr); usb_set_intfdata (udev, dev); netif_device_attach (net); if (dev->driver_info->flags & FLAG_LINK_INTR) usbnet_link_change(dev, 0, 0); return 0; out5: kfree(dev->padding_pkt); out4: usb_free_urb(dev->interrupt); out3: if (info->unbind) info->unbind (dev, udev); out1: /* subdrivers must undo all they did in bind() if they * fail it, but we may fail later and a deferred kevent * may trigger an error resubmitting itself and, worse, * schedule a timer. So we kill it all just in case. */ cancel_work_sync(&dev->kevent); del_timer_sync(&dev->delay); free_netdev(net); out: return status; }
169,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned int svc_rdma_xdr_get_reply_hdr_len(__be32 *rdma_resp) { unsigned int nsegs; __be32 *p; p = rdma_resp; /* RPC-over-RDMA V1 replies never have a Read list. */ p += rpcrdma_fixed_maxsz + 1; /* Skip Write list. */ while (*p++ != xdr_zero) { nsegs = be32_to_cpup(p++); p += nsegs * rpcrdma_segment_maxsz; } /* Skip Reply chunk. */ if (*p++ != xdr_zero) { nsegs = be32_to_cpup(p++); p += nsegs * rpcrdma_segment_maxsz; } return (unsigned long)p - (unsigned long)rdma_resp; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
unsigned int svc_rdma_xdr_get_reply_hdr_len(__be32 *rdma_resp)
168,163
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_16_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_16(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_16_set(PNG_CONST image_transform *this, image_transform_png_set_expand_16_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_16(pp); /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */ # if PNG_LIBPNG_VER < 10700 if (that->this.has_tRNS) that->this.is_transparent = 1; # endif this->next->set(this->next, that, pp, pi); }
173,628
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int n_tty_ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg) { struct n_tty_data *ldata = tty->disc_data; int retval; switch (cmd) { case TIOCOUTQ: return put_user(tty_chars_in_buffer(tty), (int __user *) arg); case TIOCINQ: down_write(&tty->termios_rwsem); if (L_ICANON(tty)) retval = inq_canon(ldata); else retval = read_cnt(ldata); up_write(&tty->termios_rwsem); return put_user(retval, (unsigned int __user *) arg); default: return n_tty_ioctl_helper(tty, file, cmd, arg); } } Commit Message: n_tty: fix EXTPROC vs ICANON interaction with TIOCINQ (aka FIONREAD) We added support for EXTPROC back in 2010 in commit 26df6d13406d ("tty: Add EXTPROC support for LINEMODE") and the intent was to allow it to override some (all?) ICANON behavior. Quoting from that original commit message: There is a new bit in the termios local flag word, EXTPROC. When this bit is set, several aspects of the terminal driver are disabled. Input line editing, character echo, and mapping of signals are all disabled. This allows the telnetd to turn off these functions when in linemode, but still keep track of what state the user wants the terminal to be in. but the problem turns out that "several aspects of the terminal driver are disabled" is a bit ambiguous, and you can really confuse the n_tty layer by setting EXTPROC and then causing some of the ICANON invariants to no longer be maintained. This fixes at least one such case (TIOCINQ) becoming unhappy because of the confusion over whether ICANON really means ICANON when EXTPROC is set. This basically makes TIOCINQ match the case of read: if EXTPROC is set, we ignore ICANON. Also, make sure to reset the ICANON state ie EXTPROC changes, not just if ICANON changes. Fixes: 26df6d13406d ("tty: Add EXTPROC support for LINEMODE") Reported-by: Tetsuo Handa <[email protected]> Reported-by: syzkaller <[email protected]> Cc: Jiri Slaby <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-704
static int n_tty_ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg) { struct n_tty_data *ldata = tty->disc_data; int retval; switch (cmd) { case TIOCOUTQ: return put_user(tty_chars_in_buffer(tty), (int __user *) arg); case TIOCINQ: down_write(&tty->termios_rwsem); if (L_ICANON(tty) && !L_EXTPROC(tty)) retval = inq_canon(ldata); else retval = read_cnt(ldata); up_write(&tty->termios_rwsem); return put_user(retval, (unsigned int __user *) arg); default: return n_tty_ioctl_helper(tty, file, cmd, arg); } }
169,009
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ff_jpeg2000_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty) { int reslevelno, bandno, precno; for (reslevelno = 0; comp->reslevel && reslevelno < codsty->nreslevels; reslevelno++) { Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno; for (bandno = 0; bandno < reslevel->nbands; bandno++) { Jpeg2000Band *band = reslevel->band + bandno; for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) { Jpeg2000Prec *prec = band->prec + precno; av_freep(&prec->zerobits); av_freep(&prec->cblkincl); av_freep(&prec->cblk); } av_freep(&band->prec); } av_freep(&reslevel->band); } ff_dwt_destroy(&comp->dwt); av_freep(&comp->reslevel); av_freep(&comp->i_data); av_freep(&comp->f_data); } Commit Message: jpeg2000: fix dereferencing invalid pointers Found-by: Laurent Butti <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID:
void ff_jpeg2000_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty) { int reslevelno, bandno, precno; for (reslevelno = 0; comp->reslevel && reslevelno < codsty->nreslevels; reslevelno++) { Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno; for (bandno = 0; bandno < reslevel->nbands; bandno++) { Jpeg2000Band *band = reslevel->band + bandno; for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) { if (band->prec) { Jpeg2000Prec *prec = band->prec + precno; av_freep(&prec->zerobits); av_freep(&prec->cblkincl); av_freep(&prec->cblk); } } av_freep(&band->prec); } av_freep(&reslevel->band); } ff_dwt_destroy(&comp->dwt); av_freep(&comp->reslevel); av_freep(&comp->i_data); av_freep(&comp->f_data); }
165,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PermissionsContainsFunction::RunImpl() { scoped_ptr<Contains::Params> params(Contains::Params::Create(*args_)); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, &error_); if (!permissions.get()) return false; results_ = Contains::Results::Create( GetExtension()->GetActivePermissions()->Contains(*permissions)); return true; } Commit Message: Check prefs before allowing extension file access in the permissions API. [email protected] BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool PermissionsContainsFunction::RunImpl() { scoped_ptr<Contains::Params> params(Contains::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ExtensionPrefs* prefs = ExtensionSystem::Get(profile_)->extension_prefs(); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, prefs->AllowFileAccess(extension_->id()), &error_); if (!permissions.get()) return false; results_ = Contains::Results::Create( GetExtension()->GetActivePermissions()->Contains(*permissions)); return true; }
171,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewDataService::SetDataEntry( const std::string& preview_ui_addr_str, int index, const base::RefCountedBytes* data_bytes) { PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str); if (it == data_store_map_.end()) data_store_map_[preview_ui_addr_str] = new PrintPreviewDataStore(); data_store_map_[preview_ui_addr_str]->SetPreviewDataForIndex(index, data_bytes); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewDataService::SetDataEntry( int32 preview_ui_id, int index, const base::RefCountedBytes* data_bytes) { if (!ContainsKey(data_store_map_, preview_ui_id)) data_store_map_[preview_ui_id] = new PrintPreviewDataStore(); data_store_map_[preview_ui_id]->SetPreviewDataForIndex(index, data_bytes); }
170,824
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr) { mainprog_info *mainprog_ptr; int color_type, bit_depth; png_uint_32 width, height; #ifdef PNG_FLOATING_POINT_SUPPORTED double gamma; #else png_fixed_point gamma; #endif /* setjmp() doesn't make sense here, because we'd either have to exit(), * longjmp() ourselves, or return control to libpng, which doesn't want * to see us again. By not doing anything here, libpng will instead jump * to readpng2_decode_data(), which can return an error value to the main * program. */ /* retrieve the pointer to our special-purpose struct, using the png_ptr * that libpng passed back to us (i.e., not a global this time--there's * no real difference for a single image, but for a multithreaded browser * decoding several PNG images at the same time, one needs to avoid mixing * up different images' structs) */ mainprog_ptr = png_get_progressive_ptr(png_ptr); if (mainprog_ptr == NULL) { /* we be hosed */ fprintf(stderr, "readpng2 error: main struct not recoverable in info_callback.\n"); fflush(stderr); return; /* * Alternatively, we could call our error-handler just like libpng * does, which would effectively terminate the program. Since this * can only happen if png_ptr gets redirected somewhere odd or the * main PNG struct gets wiped, we're probably toast anyway. (If * png_ptr itself is NULL, we would not have been called.) */ } /* this is just like in the non-progressive case */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); mainprog_ptr->width = (ulg)width; mainprog_ptr->height = (ulg)height; /* since we know we've read all of the PNG file's "header" (i.e., up * to IDAT), we can check for a background color here */ if (mainprog_ptr->need_bgcolor && png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD)) { png_color_16p pBackground; /* it is not obvious from the libpng documentation, but this function * takes a pointer to a pointer, and it always returns valid red, * green and blue values, regardless of color_type: */ png_get_bKGD(png_ptr, info_ptr, &pBackground); /* however, it always returns the raw bKGD data, regardless of any * bit-depth transformations, so check depth and adjust if necessary */ if (bit_depth == 16) { mainprog_ptr->bg_red = pBackground->red >> 8; mainprog_ptr->bg_green = pBackground->green >> 8; mainprog_ptr->bg_blue = pBackground->blue >> 8; } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { if (bit_depth == 1) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = pBackground->gray? 255 : 0; else if (bit_depth == 2) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/3) * pBackground->gray; else /* bit_depth == 4 */ mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/15) * pBackground->gray; } else { mainprog_ptr->bg_red = (uch)pBackground->red; mainprog_ptr->bg_green = (uch)pBackground->green; mainprog_ptr->bg_blue = (uch)pBackground->blue; } } /* as before, let libpng expand palette images to RGB, low-bit-depth * grayscale images to 8 bits, transparency chunks to full alpha channel; * strip 16-bit-per-sample images to 8 bits per sample; and convert * grayscale to RGB[A] */ if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); #ifdef PNG_READ_16_TO_8_SUPPORTED if (bit_depth == 16) # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED png_set_scale_16(png_ptr); # else png_set_strip_16(png_ptr); # endif #endif if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); /* Unlike the basic viewer, which was designed to operate on local files, * this program is intended to simulate a web browser--even though we * actually read from a local file, too. But because we are pretending * that most of the images originate on the Internet, we follow the recom- * mendation of the sRGB proposal and treat unlabelled images (no gAMA * chunk) as existing in the sRGB color space. That is, we assume that * such images have a file gamma of 0.45455, which corresponds to a PC-like * display system. This change in assumptions will have no effect on a * PC-like system, but on a Mac, SGI, NeXT or other system with a non- * identity lookup table, it will darken unlabelled images, which effec- * tively favors images from PC-like systems over those originating on * the local platform. Note that mainprog_ptr->display_exponent is the * "gamma" value for the entire display system, i.e., the product of * LUT_exponent and CRT_exponent. */ #ifdef PNG_FLOATING_POINT_SUPPORTED if (png_get_gAMA(png_ptr, info_ptr, &gamma)) png_set_gamma(png_ptr, mainprog_ptr->display_exponent, gamma); else png_set_gamma(png_ptr, mainprog_ptr->display_exponent, 0.45455); #else if (png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), gamma); else png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), 45455); #endif /* we'll let libpng expand interlaced images, too */ mainprog_ptr->passes = png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data and * then get rowbytes and channels */ png_read_update_info(png_ptr, info_ptr); mainprog_ptr->rowbytes = (int)png_get_rowbytes(png_ptr, info_ptr); mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr); /* Call the main program to allocate memory for the image buffer and * initialize windows and whatnot. (The old-style function-pointer * invocation is used for compatibility with a few supposedly ANSI * compilers that nevertheless barf on "fn_ptr()"-style syntax.) */ (*mainprog_ptr->mainprog_init)(); /* and that takes care of initialization */ return; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static void readpng2_info_callback(png_structp png_ptr, png_infop info_ptr) { mainprog_info *mainprog_ptr; int color_type, bit_depth; png_uint_32 width, height; #ifdef PNG_FLOATING_POINT_SUPPORTED double gamma; #else png_fixed_point gamma; #endif /* setjmp() doesn't make sense here, because we'd either have to exit(), * longjmp() ourselves, or return control to libpng, which doesn't want * to see us again. By not doing anything here, libpng will instead jump * to readpng2_decode_data(), which can return an error value to the main * program. */ /* retrieve the pointer to our special-purpose struct, using the png_ptr * that libpng passed back to us (i.e., not a global this time--there's * no real difference for a single image, but for a multithreaded browser * decoding several PNG images at the same time, one needs to avoid mixing * up different images' structs) */ mainprog_ptr = png_get_progressive_ptr(png_ptr); if (mainprog_ptr == NULL) { /* we be hosed */ fprintf(stderr, "readpng2 error: main struct not recoverable in info_callback.\n"); fflush(stderr); return; /* * Alternatively, we could call our error-handler just like libpng * does, which would effectively terminate the program. Since this * can only happen if png_ptr gets redirected somewhere odd or the * main PNG struct gets wiped, we're probably toast anyway. (If * png_ptr itself is NULL, we would not have been called.) */ } /* this is just like in the non-progressive case */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); mainprog_ptr->width = (ulg)width; mainprog_ptr->height = (ulg)height; /* since we know we've read all of the PNG file's "header" (i.e., up * to IDAT), we can check for a background color here */ if (mainprog_ptr->need_bgcolor) { png_color_16p pBackground; /* it is not obvious from the libpng documentation, but this function * takes a pointer to a pointer, and it always returns valid red, * green and blue values, regardless of color_type: */ if (png_get_bKGD(png_ptr, info_ptr, &pBackground)) { /* however, it always returns the raw bKGD data, regardless of any * bit-depth transformations, so check depth and adjust if necessary */ if (bit_depth == 16) { mainprog_ptr->bg_red = pBackground->red >> 8; mainprog_ptr->bg_green = pBackground->green >> 8; mainprog_ptr->bg_blue = pBackground->blue >> 8; } else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { if (bit_depth == 1) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = pBackground->gray? 255 : 0; else if (bit_depth == 2) mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/3) * pBackground->gray; else /* bit_depth == 4 */ mainprog_ptr->bg_red = mainprog_ptr->bg_green = mainprog_ptr->bg_blue = (255/15) * pBackground->gray; } else { mainprog_ptr->bg_red = (uch)pBackground->red; mainprog_ptr->bg_green = (uch)pBackground->green; mainprog_ptr->bg_blue = (uch)pBackground->blue; } } } /* as before, let libpng expand palette images to RGB, low-bit-depth * grayscale images to 8 bits, transparency chunks to full alpha channel; * strip 16-bit-per-sample images to 8 bits per sample; and convert * grayscale to RGB[A] */ if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); #ifdef PNG_READ_16_TO_8_SUPPORTED if (bit_depth == 16) # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED png_set_scale_16(png_ptr); # else png_set_strip_16(png_ptr); # endif #endif if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); /* Unlike the basic viewer, which was designed to operate on local files, * this program is intended to simulate a web browser--even though we * actually read from a local file, too. But because we are pretending * that most of the images originate on the Internet, we follow the recom- * mendation of the sRGB proposal and treat unlabelled images (no gAMA * chunk) as existing in the sRGB color space. That is, we assume that * such images have a file gamma of 0.45455, which corresponds to a PC-like * display system. This change in assumptions will have no effect on a * PC-like system, but on a Mac, SGI, NeXT or other system with a non- * identity lookup table, it will darken unlabelled images, which effec- * tively favors images from PC-like systems over those originating on * the local platform. Note that mainprog_ptr->display_exponent is the * "gamma" value for the entire display system, i.e., the product of * LUT_exponent and CRT_exponent. */ #ifdef PNG_FLOATING_POINT_SUPPORTED if (png_get_gAMA(png_ptr, info_ptr, &gamma)) png_set_gamma(png_ptr, mainprog_ptr->display_exponent, gamma); else png_set_gamma(png_ptr, mainprog_ptr->display_exponent, 0.45455); #else if (png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), gamma); else png_set_gamma_fixed(png_ptr, (png_fixed_point)(100000*mainprog_ptr->display_exponent+.5), 45455); #endif /* we'll let libpng expand interlaced images, too */ mainprog_ptr->passes = png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data and * then get rowbytes and channels */ png_read_update_info(png_ptr, info_ptr); mainprog_ptr->rowbytes = (int)png_get_rowbytes(png_ptr, info_ptr); mainprog_ptr->channels = png_get_channels(png_ptr, info_ptr); /* Call the main program to allocate memory for the image buffer and * initialize windows and whatnot. (The old-style function-pointer * invocation is used for compatibility with a few supposedly ANSI * compilers that nevertheless barf on "fn_ptr()"-style syntax.) */ (*mainprog_ptr->mainprog_init)(); /* and that takes care of initialization */ return; }
173,569
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __btrfs_set_acl(struct btrfs_trans_handle *trans, struct inode *inode, struct posix_acl *acl, int type) { int ret, size = 0; const char *name; char *value = NULL; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { ret = posix_acl_equiv_mode(acl, &inode->i_mode); if (ret < 0) return ret; if (ret == 0) acl = NULL; } ret = 0; break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) return acl ? -EINVAL : 0; name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: return -EINVAL; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) { ret = -ENOMEM; goto out; } ret = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (ret < 0) goto out; } ret = __btrfs_setxattr(trans, inode, name, value, size, 0); out: kfree(value); if (!ret) set_cached_acl(inode, type, acl); return ret; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
static int __btrfs_set_acl(struct btrfs_trans_handle *trans, struct inode *inode, struct posix_acl *acl, int type) { int ret, size = 0; const char *name; char *value = NULL; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { ret = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (ret) return ret; } ret = 0; break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) return acl ? -EINVAL : 0; name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: return -EINVAL; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) { ret = -ENOMEM; goto out; } ret = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (ret < 0) goto out; } ret = __btrfs_setxattr(trans, inode, name, value, size, 0); out: kfree(value); if (!ret) set_cached_acl(inode, type, acl); return ret; }
166,967
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcXSendExtensionEvent(ClientPtr client) { int ret; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); if (!((EXTENSION_EVENT_BASE <= first->u.u.type) && (first->u.u.type < lastEvent))) { client->errorValue = first->u.u.type; return BadValue; } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; } Commit Message: CWE ID: CWE-119
ProcXSendExtensionEvent(ClientPtr client) { int ret, i; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); for (i = 0; i < stuff->num_events; i++) { if (!((EXTENSION_EVENT_BASE <= first[i].u.u.type) && (first[i].u.u.type < lastEvent))) { client->errorValue = first[i].u.u.type; return BadValue; } } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; }
164,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long BlockGroup::Parse() { const long status = m_block.Parse(m_pCluster); if (status) return status; m_block.SetKey((m_prev > 0) && (m_next <= 0)); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long BlockGroup::Parse()
174,411
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */
167,112
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int64_t AppCacheDatabase::GetOriginUsage(const url::Origin& origin) { std::vector<CacheRecord> records; if (!FindCachesForOrigin(origin, &records)) return 0; int64_t origin_usage = 0; for (const auto& record : records) origin_usage += record.cache_size; return origin_usage; } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
int64_t AppCacheDatabase::GetOriginUsage(const url::Origin& origin) { std::vector<CacheRecord> caches; if (!FindCachesForOrigin(origin, &caches)) return 0; int64_t origin_usage = 0; for (const auto& cache : caches) origin_usage += cache.cache_size + cache.padding_size; return origin_usage; }
172,978
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; } Commit Message: Fix bounds checks again. CWE ID: CWE-119
cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; }
165,625
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, "Missing descriptor data\n"); return NULL; } if (!buflen) { dev_err(&intf->dev, "Zero length descriptor\n"); return NULL; } while (buflen > 0) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "Found union header\n"); return union_desc; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, "Missing CDC union descriptor\n"); return NULL; } Commit Message: Input: ims-psu - check if CDC union descriptor is sane Before trying to use CDC union descriptor, try to validate whether that it is sane by checking that intf->altsetting->extra is big enough and that descriptor bLength is not too big and not too small. Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Dmitry Torokhov <[email protected]> CWE ID: CWE-125
ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, "Missing descriptor data\n"); return NULL; } if (!buflen) { dev_err(&intf->dev, "Zero length descriptor\n"); return NULL; } while (buflen >= sizeof(*union_desc)) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bLength > buflen) { dev_err(&intf->dev, "Too large descriptor\n"); return NULL; } if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "Found union header\n"); if (union_desc->bLength >= sizeof(*union_desc)) return union_desc; dev_err(&intf->dev, "Union descriptor to short (%d vs %zd\n)", union_desc->bLength, sizeof(*union_desc)); return NULL; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, "Missing CDC union descriptor\n"); return NULL; }
167,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif ); GifFileType *file = gif->file; ColorMapObject *map = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap; GifByteType *extension; if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) { vips_foreign_load_gif_error( gif ); return( -1 ); } /* Check that the frame looks sane. Perhaps giflib checks * this for us. */ if( file->Image.Left < 0 || file->Image.Width < 1 || file->Image.Width > 10000 || file->Image.Left + file->Image.Width > file->SWidth || file->Image.Top < 0 || file->Image.Height < 1 || file->Image.Height > 10000 || file->Image.Top + file->Image.Height > file->SHeight ) { vips_error( class->nickname, "%s", _( "bad frame size" ) ); return( -1 ); } /* Test for a non-greyscale colourmap for this frame. */ if( !gif->has_colour && map ) { int i; for( i = 0; i < map->ColorCount; i++ ) if( map->Colors[i].Red != map->Colors[i].Green || map->Colors[i].Green != map->Colors[i].Blue ) { gif->has_colour = TRUE; break; } } /* Step over compressed image data. */ do { if( vips_foreign_load_gif_code_next( gif, &extension ) ) return( -1 ); } while( extension != NULL ); return( 0 ); } Commit Message: fetch map after DGifGetImageDesc() Earlier refactoring broke GIF map fetch. CWE ID:
vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif ); GifFileType *file = gif->file; ColorMapObject *map; GifByteType *extension; if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) { vips_foreign_load_gif_error( gif ); return( -1 ); } /* Check that the frame looks sane. Perhaps giflib checks * this for us. */ if( file->Image.Left < 0 || file->Image.Width < 1 || file->Image.Width > 10000 || file->Image.Left + file->Image.Width > file->SWidth || file->Image.Top < 0 || file->Image.Height < 1 || file->Image.Height > 10000 || file->Image.Top + file->Image.Height > file->SHeight ) { vips_error( class->nickname, "%s", _( "bad frame size" ) ); return( -1 ); } /* Test for a non-greyscale colourmap for this frame. */ map = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap; if( !gif->has_colour && map ) { int i; for( i = 0; i < map->ColorCount; i++ ) if( map->Colors[i].Red != map->Colors[i].Green || map->Colors[i].Green != map->Colors[i].Blue ) { gif->has_colour = TRUE; break; } } /* Step over compressed image data. */ do { if( vips_foreign_load_gif_code_next( gif, &extension ) ) return( -1 ); } while( extension != NULL ); return( 0 ); }
169,490
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; size_t size; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) { return -1; } dec->numtiles = size; JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; } Commit Message: Ensure that not all tiles lie outside the image area. CWE ID: CWE-20
static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; size_t size; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) { return -1; } dec->numtiles = size; JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; }
168,737
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VirtualAuthenticator::AddRegistration( blink::test::mojom::RegisteredKeyPtr registration, AddRegistrationCallback callback) { if (registration->application_parameter.size() != device::kRpIdHashLength) { std::move(callback).Run(false); return; } bool success = false; std::tie(std::ignore, success) = state_->registrations.emplace( std::move(registration->key_handle), ::device::VirtualFidoDevice::RegistrationData( crypto::ECPrivateKey::CreateFromPrivateKeyInfo( registration->private_key), registration->application_parameter, registration->counter)); std::move(callback).Run(success); } Commit Message: [base] Make dynamic container to static span conversion explicit This change disallows implicit conversions from dynamic containers to static spans. This conversion can cause CHECK failures, and thus should be done carefully. Requiring explicit construction makes it more obvious when this happens. To aid usability, appropriate base::make_span<size_t> overloads are added. Bug: 877931 Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d Reviewed-on: https://chromium-review.googlesource.com/1189985 Reviewed-by: Ryan Sleevi <[email protected]> Reviewed-by: Balazs Engedy <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Commit-Queue: Jan Wilken Dörrie <[email protected]> Cr-Commit-Position: refs/heads/master@{#586657} CWE ID: CWE-22
void VirtualAuthenticator::AddRegistration( blink::test::mojom::RegisteredKeyPtr registration, AddRegistrationCallback callback) { if (registration->application_parameter.size() != device::kRpIdHashLength) { std::move(callback).Run(false); return; } bool success = false; std::tie(std::ignore, success) = state_->registrations.emplace( std::move(registration->key_handle), ::device::VirtualFidoDevice::RegistrationData( crypto::ECPrivateKey::CreateFromPrivateKeyInfo( registration->private_key), base::make_span<device::kRpIdHashLength>( registration->application_parameter), registration->counter)); std::move(callback).Run(success); }
172,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_wrap_size_limit( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { OM_uint32 ret; ret = gss_wrap_size_limit(minor_status, context_handle, conf_req_flag, qop_req, req_output_size, max_input_size); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_wrap_size_limit( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_wrap_size_limit(minor_status, sc->ctx_handle, conf_req_flag, qop_req, req_output_size, max_input_size); return (ret); }
166,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); free(name); return 0; } Commit Message: fsck: detect submodule paths starting with dash As with urls, submodule paths with dashes are ignored by git, but may end up confusing older versions. Detecting them via fsck lets us prevent modern versions of git from being a vector to spread broken .gitmodules to older versions. Compared to blocking leading-dash urls, though, this detection may be less of a good idea: 1. While such paths provide confusing and broken results, they don't seem to actually work as option injections against anything except "cd". In particular, the submodule code seems to canonicalize to an absolute path before running "git clone" (so it passes /your/clone/-sub). 2. It's more likely that we may one day make such names actually work correctly. Even after we revert this fsck check, it will continue to be a hassle until hosting servers are all updated. On the other hand, it's not entirely clear that the behavior in older versions is safe. And if we do want to eventually allow this, we may end up doing so with a special syntax anyway (e.g., writing "./-sub" in the .gitmodules file, and teaching the submodule code to canonicalize it when comparing). So on balance, this is probably a good protection. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-20
static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); if (!strcmp(key, "path") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_PATH, "disallowed submodule path: %s", value); free(name); return 0; }
170,160
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *get_header(FILE *fp) { long start; /* First 1024 bytes of doc must be header (1.7 spec pg 1102) */ char *header; header = calloc(1, 1024); start = ftell(fp); fseek(fp, 0, SEEK_SET); SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n"); fseek(fp, start, SEEK_SET); return header; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787
static char *get_header(FILE *fp) { /* First 1024 bytes of doc must be header (1.7 spec pg 1102) */ char *header = safe_calloc(1024); long start = ftell(fp); fseek(fp, 0, SEEK_SET); SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n"); fseek(fp, start, SEEK_SET); return header; }
169,567
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int LELib_Create(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle) { ALOGV("LELib_Create()"); int ret; int i; if (pHandle == NULL || uuid == NULL) { return -EINVAL; } if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) { return -EINVAL; } LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext; pContext->mItfe = &gLEInterface; pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED; pContext->mCompressor = NULL; ret = LE_init(pContext); if (ret < 0) { ALOGW("LELib_Create() init failed"); delete pContext; return ret; } *pHandle = (effect_handle_t)pContext; pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED; ALOGV(" LELib_Create context is %p", pContext); return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int LELib_Create(const effect_uuid_t *uuid, int32_t sessionId __unused, int32_t ioId __unused, effect_handle_t *pHandle) { ALOGV("LELib_Create()"); int ret; int i; if (pHandle == NULL || uuid == NULL) { return -EINVAL; } if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) { return -EINVAL; } LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext; pContext->mItfe = &gLEInterface; pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED; pContext->mCompressor = NULL; ret = LE_init(pContext); if (ret < 0) { ALOGW("LELib_Create() init failed"); delete pContext; return ret; } *pHandle = (effect_handle_t)pContext; pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED; ALOGV(" LELib_Create context is %p", pContext); return 0; }
173,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PaymentRequest::NoUpdatedPaymentDetails() { spec_->RecomputeSpecForDetails(); } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189
void PaymentRequest::NoUpdatedPaymentDetails() { // This Mojo call is triggered by the user of the API doing nothing in // response to a shipping address update event, so the error messages cannot // be more verbose. if (!IsInitialized()) { log_.Error("Not initialized"); OnConnectionTerminated(); return; } if (!IsThisPaymentRequestShowing()) { log_.Error("Not shown"); OnConnectionTerminated(); return; } spec_->RecomputeSpecForDetails(); }
173,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; ext4_lblk_t punch_start, punch_stop; handle_t *handle; unsigned int credits; loff_t new_size, ioffset; int ret; /* * We need to test this early because xfstests assumes that a * collapse range of (0, 1) will return EOPNOTSUPP if the file * system does not support collapse range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Collapse range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EINVAL; trace_ext4_collapse_range(inode, offset, len); punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb); punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down offset to be aligned with page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* * There is no need to overlap collapse range with EOF, in which case * it is effectively a truncate operation */ if (offset + len >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } truncate_pagecache(inode, ioffset); /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_dio; } down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ext4_discard_preallocations(inode); ret = ext4_ext_shift_extents(inode, handle, punch_stop, punch_stop - punch_start, SHIFT_LEFT); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } new_size = i_size_read(inode) - len; i_size_write(inode, new_size); EXT4_I(inode)->i_disksize = new_size; up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-362
int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; ext4_lblk_t punch_start, punch_stop; handle_t *handle; unsigned int credits; loff_t new_size, ioffset; int ret; /* * We need to test this early because xfstests assumes that a * collapse range of (0, 1) will return EOPNOTSUPP if the file * system does not support collapse range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Collapse range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EINVAL; trace_ext4_collapse_range(inode, offset, len); punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb); punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down offset to be aligned with page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* * There is no need to overlap collapse range with EOF, in which case * it is effectively a truncate operation */ if (offset + len >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* * Prevent page faults from reinstantiating pages we have released from * page cache. */ down_write(&EXT4_I(inode)->i_mmap_sem); truncate_pagecache(inode, ioffset); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_mmap; } down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ext4_discard_preallocations(inode); ret = ext4_ext_shift_extents(inode, handle, punch_stop, punch_stop - punch_start, SHIFT_LEFT); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } new_size = i_size_read(inode) - len; i_size_write(inode, new_size); EXT4_I(inode)->i_disksize = new_size; up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_mmap: up_write(&EXT4_I(inode)->i_mmap_sem); ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; }
167,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_select_font_encoding(xps_font_t *font, int idx) { byte *cmapdata, *entry; int pid, eid; if (idx < 0 || idx >= font->cmapsubcount) return; cmapdata = font->data + font->cmaptable; entry = cmapdata + 4 + idx * 8; pid = u16(entry + 0); eid = u16(entry + 2); font->cmapsubtable = font->cmaptable + u32(entry + 4); font->usepua = (pid == 3 && eid == 0); } Commit Message: CWE ID: CWE-125
xps_select_font_encoding(xps_font_t *font, int idx) { byte *cmapdata, *entry; int pid, eid; if (idx < 0 || idx >= font->cmapsubcount) return 0; cmapdata = font->data + font->cmaptable; entry = cmapdata + 4 + idx * 8; pid = u16(entry + 0); eid = u16(entry + 2); font->cmapsubtable = font->cmaptable + u32(entry + 4); if (font->cmapsubtable >= font->length) { font->cmapsubtable = 0; return 0; } font->usepua = (pid == 3 && eid == 0); return 1; }
164,782
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FindBarController::UpdateFindBarForCurrentResult() { FindManager* find_manager = tab_contents_->GetFindManager(); const FindNotificationDetails& find_result = find_manager->find_result(); if (find_result.number_of_matches() > -1) { if (last_reported_matchcount_ > 0 && find_result.number_of_matches() == 1 && !find_result.final_update()) return; // Don't let interim result override match count. last_reported_matchcount_ = find_result.number_of_matches(); } find_bar_->UpdateUIForFindResult(find_result, find_manager->find_text()); } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void FindBarController::UpdateFindBarForCurrentResult() { FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper(); const FindNotificationDetails& find_result = find_tab_helper->find_result(); if (find_result.number_of_matches() > -1) { if (last_reported_matchcount_ > 0 && find_result.number_of_matches() == 1 && !find_result.final_update()) return; // Don't let interim result override match count. last_reported_matchcount_ = find_result.number_of_matches(); } find_bar_->UpdateUIForFindResult(find_result, find_tab_helper->find_text()); }
170,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int read_request(int fd, debugger_request_t* out_request) { ucred cr; socklen_t len = sizeof(cr); int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len); if (status != 0) { ALOGE("cannot get credentials"); return -1; } ALOGV("reading tid"); fcntl(fd, F_SETFL, O_NONBLOCK); pollfd pollfds[1]; pollfds[0].fd = fd; pollfds[0].events = POLLIN; pollfds[0].revents = 0; status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000)); if (status != 1) { ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid); return -1; } debugger_msg_t msg; memset(&msg, 0, sizeof(msg)); status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg))); if (status < 0) { ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid); return -1; } if (status != sizeof(debugger_msg_t)) { ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid); return -1; } out_request->action = static_cast<debugger_action_t>(msg.action); out_request->tid = msg.tid; out_request->pid = cr.pid; out_request->uid = cr.uid; out_request->gid = cr.gid; out_request->abort_msg_address = msg.abort_msg_address; out_request->original_si_code = msg.original_si_code; if (msg.action == DEBUGGER_ACTION_CRASH) { char buf[64]; struct stat s; snprintf(buf, sizeof buf, "/proc/%d/task/%d", out_request->pid, out_request->tid); if (stat(buf, &s)) { ALOGE("tid %d does not exist in pid %d. ignoring debug request\n", out_request->tid, out_request->pid); return -1; } } else if (cr.uid == 0 || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) { status = get_process_info(out_request->tid, &out_request->pid, &out_request->uid, &out_request->gid); if (status < 0) { ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid); return -1; } if (!selinux_action_allowed(fd, out_request)) return -1; } else { return -1; } return 0; } Commit Message: debuggerd: verify that traced threads belong to the right process. Fix two races in debuggerd's PTRACE_ATTACH logic: 1. The target thread in a crash dump request could exit between the /proc/<pid>/task/<tid> check and the PTRACE_ATTACH. 2. Sibling threads could exit between listing /proc/<pid>/task and the PTRACE_ATTACH. Bug: http://b/29555636 Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591 CWE ID: CWE-264
static int read_request(int fd, debugger_request_t* out_request) { ucred cr; socklen_t len = sizeof(cr); int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len); if (status != 0) { ALOGE("cannot get credentials"); return -1; } ALOGV("reading tid"); fcntl(fd, F_SETFL, O_NONBLOCK); pollfd pollfds[1]; pollfds[0].fd = fd; pollfds[0].events = POLLIN; pollfds[0].revents = 0; status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000)); if (status != 1) { ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid); return -1; } debugger_msg_t msg; memset(&msg, 0, sizeof(msg)); status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg))); if (status < 0) { ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid); return -1; } if (status != sizeof(debugger_msg_t)) { ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid); return -1; } out_request->action = static_cast<debugger_action_t>(msg.action); out_request->tid = msg.tid; out_request->pid = cr.pid; out_request->uid = cr.uid; out_request->gid = cr.gid; out_request->abort_msg_address = msg.abort_msg_address; out_request->original_si_code = msg.original_si_code; if (msg.action == DEBUGGER_ACTION_CRASH) { // This check needs to happen again after ptracing the requested thread to prevent a race. if (!pid_contains_tid(out_request->pid, out_request->tid)) { ALOGE("tid %d does not exist in pid %d. ignoring debug request\n", out_request->tid, out_request->pid); return -1; } } else if (cr.uid == 0 || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) { status = get_process_info(out_request->tid, &out_request->pid, &out_request->uid, &out_request->gid); if (status < 0) { ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid); return -1; } if (!selinux_action_allowed(fd, out_request)) return -1; } else { return -1; } return 0; }
173,407
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftVPXEncoder::onQueueFilled(OMX_U32 portIndex) { if (mCodecContext == NULL) { if (OK != initEncoder()) { ALOGE("Failed to initialize encoder"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } } vpx_codec_err_t codec_return; List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex); while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) { BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader; BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader; if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) { inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); inputBufferInfo->mOwnedByUs = false; notifyEmptyBufferDone(inputBufferHeader); outputBufferHeader->nFilledLen = 0; outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); outputBufferInfo->mOwnedByUs = false; notifyFillBufferDone(outputBufferHeader); return; } const uint8_t *source = inputBufferHeader->pBuffer + inputBufferHeader->nOffset; size_t frameSize = mWidth * mHeight * 3 / 2; if (mInputDataIsMeta) { source = extractGraphicBuffer( mConversionBuffer, frameSize, source, inputBufferHeader->nFilledLen, mWidth, mHeight); if (source == NULL) { ALOGE("Unable to extract gralloc buffer in metadata mode"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } } else { if (inputBufferHeader->nFilledLen < frameSize) { android_errorWriteLog(0x534e4554, "27569635"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } else if (inputBufferHeader->nFilledLen > frameSize) { ALOGW("Input buffer contains too many pixels"); } if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { ConvertYUV420SemiPlanarToYUV420Planar( source, mConversionBuffer, mWidth, mHeight); source = mConversionBuffer; } } vpx_image_t raw_frame; vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight, kInputBufferAlignment, (uint8_t *)source); vpx_enc_frame_flags_t flags = 0; if (mTemporalPatternLength > 0) { flags = getEncodeFlags(); } if (mKeyFrameRequested) { flags |= VPX_EFLAG_FORCE_KF; mKeyFrameRequested = false; } if (mBitrateUpdated) { mCodecConfiguration->rc_target_bitrate = mBitrate/1000; vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext, mCodecConfiguration); if (res != VPX_CODEC_OK) { ALOGE("vp8 encoder failed to update bitrate: %s", vpx_codec_err_to_string(res)); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer } mBitrateUpdated = false; } uint32_t frameDuration; if (inputBufferHeader->nTimeStamp > mLastTimestamp) { frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp); } else { frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate); } mLastTimestamp = inputBufferHeader->nTimeStamp; codec_return = vpx_codec_encode( mCodecContext, &raw_frame, inputBufferHeader->nTimeStamp, // in timebase units frameDuration, // frame duration in timebase units flags, // frame flags VPX_DL_REALTIME); // encoding deadline if (codec_return != VPX_CODEC_OK) { ALOGE("vpx encoder failed to encode frame"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } vpx_codec_iter_t encoded_packet_iterator = NULL; const vpx_codec_cx_pkt_t* encoded_packet; while ((encoded_packet = vpx_codec_get_cx_data( mCodecContext, &encoded_packet_iterator))) { if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) { outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts; outputBufferHeader->nFlags = 0; if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY) outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; outputBufferHeader->nOffset = 0; outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz; if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) { android_errorWriteLog(0x534e4554, "27569635"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } memcpy(outputBufferHeader->pBuffer, encoded_packet->data.frame.buf, encoded_packet->data.frame.sz); outputBufferInfo->mOwnedByUs = false; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); notifyFillBufferDone(outputBufferHeader); } } inputBufferInfo->mOwnedByUs = false; inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); notifyEmptyBufferDone(inputBufferHeader); } } Commit Message: codecs: handle onReset() for a few encoders Test: Run PoC binaries Bug: 34749392 Bug: 34705519 Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd CWE ID:
void SoftVPXEncoder::onQueueFilled(OMX_U32 portIndex) { if (mCodecContext == NULL) { if (OK != initEncoder()) { ALOGE("Failed to initialize encoder"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } } vpx_codec_err_t codec_return; List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex); while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) { BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader; BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader; if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) { inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); inputBufferInfo->mOwnedByUs = false; notifyEmptyBufferDone(inputBufferHeader); outputBufferHeader->nFilledLen = 0; outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); outputBufferInfo->mOwnedByUs = false; notifyFillBufferDone(outputBufferHeader); return; } const uint8_t *source = inputBufferHeader->pBuffer + inputBufferHeader->nOffset; size_t frameSize = mWidth * mHeight * 3 / 2; if (mInputDataIsMeta) { source = extractGraphicBuffer( mConversionBuffer, frameSize, source, inputBufferHeader->nFilledLen, mWidth, mHeight); if (source == NULL) { ALOGE("Unable to extract gralloc buffer in metadata mode"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } } else { if (inputBufferHeader->nFilledLen < frameSize) { android_errorWriteLog(0x534e4554, "27569635"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } else if (inputBufferHeader->nFilledLen > frameSize) { ALOGW("Input buffer contains too many pixels"); } if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { ConvertYUV420SemiPlanarToYUV420Planar( source, mConversionBuffer, mWidth, mHeight); source = mConversionBuffer; } } vpx_image_t raw_frame; vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight, kInputBufferAlignment, (uint8_t *)source); vpx_enc_frame_flags_t flags = 0; if (mTemporalPatternLength > 0) { flags = getEncodeFlags(); } if (mKeyFrameRequested) { flags |= VPX_EFLAG_FORCE_KF; mKeyFrameRequested = false; } if (mBitrateUpdated) { mCodecConfiguration->rc_target_bitrate = mBitrate/1000; vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext, mCodecConfiguration); if (res != VPX_CODEC_OK) { ALOGE("vp8 encoder failed to update bitrate: %s", vpx_codec_err_to_string(res)); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer } mBitrateUpdated = false; } uint32_t frameDuration; if (inputBufferHeader->nTimeStamp > mLastTimestamp) { frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp); } else { // Use default of 30 fps in case of 0 frame rate. uint32_t framerate = mFramerate ?: (30 << 16); frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / framerate); } mLastTimestamp = inputBufferHeader->nTimeStamp; codec_return = vpx_codec_encode( mCodecContext, &raw_frame, inputBufferHeader->nTimeStamp, // in timebase units frameDuration, // frame duration in timebase units flags, // frame flags VPX_DL_REALTIME); // encoding deadline if (codec_return != VPX_CODEC_OK) { ALOGE("vpx encoder failed to encode frame"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } vpx_codec_iter_t encoded_packet_iterator = NULL; const vpx_codec_cx_pkt_t* encoded_packet; while ((encoded_packet = vpx_codec_get_cx_data( mCodecContext, &encoded_packet_iterator))) { if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) { outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts; outputBufferHeader->nFlags = 0; if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY) outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; outputBufferHeader->nOffset = 0; outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz; if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) { android_errorWriteLog(0x534e4554, "27569635"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } memcpy(outputBufferHeader->pBuffer, encoded_packet->data.frame.buf, encoded_packet->data.frame.sz); outputBufferInfo->mOwnedByUs = false; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); notifyFillBufferDone(outputBufferHeader); } } inputBufferInfo->mOwnedByUs = false; inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); notifyEmptyBufferDone(inputBufferHeader); } }
174,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); } if (cfg_.ts_number_layers > 1) { if (video->frame() == 1) { encoder->Control(VP9E_SET_SVC, 1); } vpx_svc_layer_id_t layer_id = {0, 0}; layer_id.spatial_layer_id = 0; frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers); layer_id.temporal_layer_id = SetLayerId(video->frame(), cfg_.ts_number_layers); if (video->frame() > 0) { encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id); } } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 0) encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); if (denoiser_offon_test_) { ASSERT_GT(denoiser_offon_period_, 0) << "denoiser_offon_period_ is not positive."; if ((video->frame() + 1) % denoiser_offon_period_ == 0) { // Flip denoiser_on_ periodically denoiser_on_ ^= 1; } } encoder->Control(VP9E_SET_NOISE_SENSITIVITY, denoiser_on_); if (cfg_.ts_number_layers > 1) { if (video->frame() == 0) { encoder->Control(VP9E_SET_SVC, 1); } vpx_svc_layer_id_t layer_id; layer_id.spatial_layer_id = 0; frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers); layer_id.temporal_layer_id = SetLayerId(video->frame(), cfg_.ts_number_layers); encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id); } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; }
174,516
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host, const base::string16& message, const base::string16& default_prompt, const GURL& frame_url, JavaScriptDialogType dialog_type, IPC::Message* reply_msg) { bool suppress_this_message = ShowingInterstitialPage() || !delegate_ || delegate_->ShouldSuppressDialogs(this) || !delegate_->GetJavaScriptDialogManager(this); if (!suppress_this_message) { is_showing_javascript_dialog_ = true; dialog_manager_ = delegate_->GetJavaScriptDialogManager(this); dialog_manager_->RunJavaScriptDialog( this, frame_url, dialog_type, message, default_prompt, base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, false), &suppress_this_message); } if (suppress_this_message) { OnDialogClosed(render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, true, false, base::string16()); } } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20
void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host, const base::string16& message, const base::string16& default_prompt, const GURL& frame_url, JavaScriptDialogType dialog_type, IPC::Message* reply_msg) { // Running a dialog causes an exit to webpage-initiated fullscreen. // http://crbug.com/728276 if (IsFullscreenForCurrentTab()) ExitFullscreen(true); bool suppress_this_message = ShowingInterstitialPage() || !delegate_ || delegate_->ShouldSuppressDialogs(this) || !delegate_->GetJavaScriptDialogManager(this); if (!suppress_this_message) { is_showing_javascript_dialog_ = true; dialog_manager_ = delegate_->GetJavaScriptDialogManager(this); dialog_manager_->RunJavaScriptDialog( this, frame_url, dialog_type, message, default_prompt, base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, false), &suppress_this_message); } if (suppress_this_message) { OnDialogClosed(render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, true, false, base::string16()); } }
172,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LinkChangeSerializerMarkupAccumulator::appendAttribute(StringBuilder& result, Element* element, const Attribute& attribute, Namespaces* namespaces) { if (m_replaceLinks && element->isURLAttribute(attribute) && !element->isJavaScriptURLAttribute(attribute)) { String completeURL = m_document->completeURL(attribute.value()); if (m_replaceLinks->contains(completeURL)) { result.append(' '); result.append(attribute.name().toString()); result.appendLiteral("=\""); if (!m_directoryName.isEmpty()) { result.appendLiteral("./"); result.append(m_directoryName); result.append('/'); } result.append(m_replaceLinks->get(completeURL)); result.appendLiteral("\""); return; } } MarkupAccumulator::appendAttribute(result, element, attribute, namespaces); } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LinkChangeSerializerMarkupAccumulator::appendAttribute(StringBuilder& result, Element* element, const Attribute& attribute, Namespaces* namespaces)
171,565
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, getSupportedCompression) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, "GZ", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, "BZIP2", 5, 1); } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, getSupportedCompression) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, "GZ", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, "BZIP2", 5, 1); } }
165,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SpdyWriteQueue::RemovePendingWritesForStreamsAfter( SpdyStreamId last_good_stream_id) { CHECK(!removing_writes_); removing_writes_ = true; for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { std::deque<PendingWrite>* queue = &queue_[i]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() && (it->stream->stream_id() > last_good_stream_id || it->stream->stream_id() == 0)) { delete it->frame_producer; } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); } removing_writes_ = false; } Commit Message: These can post callbacks which re-enter into SpdyWriteQueue. BUG=369539 Review URL: https://codereview.chromium.org/265933007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SpdyWriteQueue::RemovePendingWritesForStreamsAfter( SpdyStreamId last_good_stream_id) { CHECK(!removing_writes_); removing_writes_ = true; std::vector<SpdyBufferProducer*> erased_buffer_producers; for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { std::deque<PendingWrite>* queue = &queue_[i]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() && (it->stream->stream_id() > last_good_stream_id || it->stream->stream_id() == 0)) { erased_buffer_producers.push_back(it->frame_producer); } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); } removing_writes_ = false; STLDeleteElements(&erased_buffer_producers); // Invokes callbacks. }
171,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt) { struct ipv6_txoptions *opt2; opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC); if (opt2) { long dif = (char *)opt2 - (char *)opt; memcpy(opt2, opt, opt->tot_len); if (opt2->hopopt) *((char **)&opt2->hopopt) += dif; if (opt2->dst0opt) *((char **)&opt2->dst0opt) += dif; if (opt2->dst1opt) *((char **)&opt2->dst1opt) += dif; if (opt2->srcrt) *((char **)&opt2->srcrt) += dif; } return opt2; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt) { struct ipv6_txoptions *opt2; opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC); if (opt2) { long dif = (char *)opt2 - (char *)opt; memcpy(opt2, opt, opt->tot_len); if (opt2->hopopt) *((char **)&opt2->hopopt) += dif; if (opt2->dst0opt) *((char **)&opt2->dst0opt) += dif; if (opt2->dst1opt) *((char **)&opt2->dst1opt) += dif; if (opt2->srcrt) *((char **)&opt2->srcrt) += dif; atomic_set(&opt2->refcnt, 1); } return opt2; }
167,330
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ip6_frag_queue(struct frag_queue *fq, struct sk_buff *skb, struct frag_hdr *fhdr, int nhoff) { struct sk_buff *prev, *next; struct net_device *dev; int offset, end; struct net *net = dev_net(skb_dst(skb)->dev); if (fq->q.last_in & INET_FRAG_COMPLETE) goto err; offset = ntohs(fhdr->frag_off) & ~0x7; end = offset + (ntohs(ipv6_hdr(skb)->payload_len) - ((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1))); if ((unsigned int)end > IPV6_MAXPLEN) { IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_INHDRERRORS); icmpv6_param_prob(skb, ICMPV6_HDR_FIELD, ((u8 *)&fhdr->frag_off - skb_network_header(skb))); return -1; } if (skb->ip_summed == CHECKSUM_COMPLETE) { const unsigned char *nh = skb_network_header(skb); skb->csum = csum_sub(skb->csum, csum_partial(nh, (u8 *)(fhdr + 1) - nh, 0)); } /* Is this the final fragment? */ if (!(fhdr->frag_off & htons(IP6_MF))) { /* If we already have some bits beyond end * or have different end, the segment is corrupted. */ if (end < fq->q.len || ((fq->q.last_in & INET_FRAG_LAST_IN) && end != fq->q.len)) goto err; fq->q.last_in |= INET_FRAG_LAST_IN; fq->q.len = end; } else { /* Check if the fragment is rounded to 8 bytes. * Required by the RFC. */ if (end & 0x7) { /* RFC2460 says always send parameter problem in * this case. -DaveM */ IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_INHDRERRORS); icmpv6_param_prob(skb, ICMPV6_HDR_FIELD, offsetof(struct ipv6hdr, payload_len)); return -1; } if (end > fq->q.len) { /* Some bits beyond end -> corruption. */ if (fq->q.last_in & INET_FRAG_LAST_IN) goto err; fq->q.len = end; } } if (end == offset) goto err; /* Point into the IP datagram 'data' part. */ if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data)) goto err; if (pskb_trim_rcsum(skb, end - offset)) goto err; /* Find out which fragments are in front and at the back of us * in the chain of fragments so far. We must know where to put * this fragment, right? */ prev = fq->q.fragments_tail; if (!prev || FRAG6_CB(prev)->offset < offset) { next = NULL; goto found; } prev = NULL; for(next = fq->q.fragments; next != NULL; next = next->next) { if (FRAG6_CB(next)->offset >= offset) break; /* bingo! */ prev = next; } found: /* We found where to put this one. Check for overlap with * preceding fragment, and, if needed, align things so that * any overlaps are eliminated. */ if (prev) { int i = (FRAG6_CB(prev)->offset + prev->len) - offset; if (i > 0) { offset += i; if (end <= offset) goto err; if (!pskb_pull(skb, i)) goto err; if (skb->ip_summed != CHECKSUM_UNNECESSARY) skb->ip_summed = CHECKSUM_NONE; } } /* Look for overlap with succeeding segments. * If we can merge fragments, do it. */ while (next && FRAG6_CB(next)->offset < end) { int i = end - FRAG6_CB(next)->offset; /* overlap is 'i' bytes */ if (i < next->len) { /* Eat head of the next overlapped fragment * and leave the loop. The next ones cannot overlap. */ if (!pskb_pull(next, i)) goto err; FRAG6_CB(next)->offset += i; /* next fragment */ fq->q.meat -= i; if (next->ip_summed != CHECKSUM_UNNECESSARY) next->ip_summed = CHECKSUM_NONE; break; } else { struct sk_buff *free_it = next; /* Old fragment is completely overridden with * new one drop it. */ next = next->next; if (prev) prev->next = next; else fq->q.fragments = next; fq->q.meat -= free_it->len; frag_kfree_skb(fq->q.net, free_it); } } FRAG6_CB(skb)->offset = offset; /* Insert this fragment in the chain of fragments. */ skb->next = next; if (!next) fq->q.fragments_tail = skb; if (prev) prev->next = skb; else fq->q.fragments = skb; dev = skb->dev; if (dev) { fq->iif = dev->ifindex; skb->dev = NULL; } fq->q.stamp = skb->tstamp; fq->q.meat += skb->len; atomic_add(skb->truesize, &fq->q.net->mem); /* The first fragment. * nhoffset is obtained from the first fragment, of course. */ if (offset == 0) { fq->nhoffset = nhoff; fq->q.last_in |= INET_FRAG_FIRST_IN; } if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len) return ip6_frag_reasm(fq, prev, dev); write_lock(&ip6_frags.lock); list_move_tail(&fq->q.lru_list, &fq->q.net->lru_list); write_unlock(&ip6_frags.lock); return -1; err: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_REASMFAILS); kfree_skb(skb); return -1; } Commit Message: ipv6: discard overlapping fragment RFC5722 prohibits reassembling fragments when some data overlaps. Bug spotted by Zhang Zuotao <[email protected]>. Signed-off-by: Nicolas Dichtel <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int ip6_frag_queue(struct frag_queue *fq, struct sk_buff *skb, struct frag_hdr *fhdr, int nhoff) { struct sk_buff *prev, *next; struct net_device *dev; int offset, end; struct net *net = dev_net(skb_dst(skb)->dev); if (fq->q.last_in & INET_FRAG_COMPLETE) goto err; offset = ntohs(fhdr->frag_off) & ~0x7; end = offset + (ntohs(ipv6_hdr(skb)->payload_len) - ((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1))); if ((unsigned int)end > IPV6_MAXPLEN) { IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_INHDRERRORS); icmpv6_param_prob(skb, ICMPV6_HDR_FIELD, ((u8 *)&fhdr->frag_off - skb_network_header(skb))); return -1; } if (skb->ip_summed == CHECKSUM_COMPLETE) { const unsigned char *nh = skb_network_header(skb); skb->csum = csum_sub(skb->csum, csum_partial(nh, (u8 *)(fhdr + 1) - nh, 0)); } /* Is this the final fragment? */ if (!(fhdr->frag_off & htons(IP6_MF))) { /* If we already have some bits beyond end * or have different end, the segment is corrupted. */ if (end < fq->q.len || ((fq->q.last_in & INET_FRAG_LAST_IN) && end != fq->q.len)) goto err; fq->q.last_in |= INET_FRAG_LAST_IN; fq->q.len = end; } else { /* Check if the fragment is rounded to 8 bytes. * Required by the RFC. */ if (end & 0x7) { /* RFC2460 says always send parameter problem in * this case. -DaveM */ IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_INHDRERRORS); icmpv6_param_prob(skb, ICMPV6_HDR_FIELD, offsetof(struct ipv6hdr, payload_len)); return -1; } if (end > fq->q.len) { /* Some bits beyond end -> corruption. */ if (fq->q.last_in & INET_FRAG_LAST_IN) goto err; fq->q.len = end; } } if (end == offset) goto err; /* Point into the IP datagram 'data' part. */ if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data)) goto err; if (pskb_trim_rcsum(skb, end - offset)) goto err; /* Find out which fragments are in front and at the back of us * in the chain of fragments so far. We must know where to put * this fragment, right? */ prev = fq->q.fragments_tail; if (!prev || FRAG6_CB(prev)->offset < offset) { next = NULL; goto found; } prev = NULL; for(next = fq->q.fragments; next != NULL; next = next->next) { if (FRAG6_CB(next)->offset >= offset) break; /* bingo! */ prev = next; } found: /* RFC5722, Section 4: * When reassembling an IPv6 datagram, if * one or more its constituent fragments is determined to be an * overlapping fragment, the entire datagram (and any constituent * fragments, including those not yet received) MUST be silently * discarded. */ /* Check for overlap with preceding fragment. */ if (prev && (FRAG6_CB(prev)->offset + prev->len) - offset > 0) goto discard_fq; /* Look for overlap with succeeding segment. */ if (next && FRAG6_CB(next)->offset < end) goto discard_fq; FRAG6_CB(skb)->offset = offset; /* Insert this fragment in the chain of fragments. */ skb->next = next; if (!next) fq->q.fragments_tail = skb; if (prev) prev->next = skb; else fq->q.fragments = skb; dev = skb->dev; if (dev) { fq->iif = dev->ifindex; skb->dev = NULL; } fq->q.stamp = skb->tstamp; fq->q.meat += skb->len; atomic_add(skb->truesize, &fq->q.net->mem); /* The first fragment. * nhoffset is obtained from the first fragment, of course. */ if (offset == 0) { fq->nhoffset = nhoff; fq->q.last_in |= INET_FRAG_FIRST_IN; } if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len) return ip6_frag_reasm(fq, prev, dev); write_lock(&ip6_frags.lock); list_move_tail(&fq->q.lru_list, &fq->q.net->lru_list); write_unlock(&ip6_frags.lock); return -1; discard_fq: fq_kill(fq); err: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_REASMFAILS); kfree_skb(skb); return -1; }
165,539
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (ts->innerstream) { ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE)); } else { ret = 0; } if (ts->meta) { zval_ptr_dtor(&ts->meta); } efree(ts); return ret; } Commit Message: CWE ID: CWE-20
static int php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (ts->innerstream) { ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE)); } else { ret = 0; } if (ts->meta) { zval_ptr_dtor(&ts->meta); } efree(ts); return ret; }
165,479
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string ChromeOSGetKeyboardOverlayId(const std::string& input_method_id) { for (size_t i = 0; i < arraysize(kKeyboardOverlayMap); ++i) { if (kKeyboardOverlayMap[i].input_method_id == input_method_id) { return kKeyboardOverlayMap[i].keyboard_overlay_id; } } return ""; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
std::string ChromeOSGetKeyboardOverlayId(const std::string& input_method_id) { virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { return true; }
170,522
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_response(const char *nurl, const char *method, unsigned int *rp_code) { char *page, *fpath; struct MHD_Response *resp = NULL; if (!strncmp(nurl, URL_BASE_API_1_1, strlen(URL_BASE_API_1_1))) { resp = create_response_api(nurl, method, rp_code); } else { fpath = get_path(nurl, server_data.www_dir); resp = create_response_file(nurl, method, rp_code, fpath); free(fpath); } } Commit Message: CWE ID: CWE-22
create_response(const char *nurl, const char *method, unsigned int *rp_code) { char *page, *fpath, *rpath; struct MHD_Response *resp = NULL; int n; if (!strncmp(nurl, URL_BASE_API_1_1, strlen(URL_BASE_API_1_1))) { resp = create_response_api(nurl, method, rp_code); } else { fpath = get_path(nurl, server_data.www_dir); rpath = realpath(fpath, NULL); if (rpath) { n = strlen(server_data.www_dir); if (!strncmp(server_data.www_dir, rpath, n)) resp = create_response_file(nurl, method, rp_code, fpath); free(rpath); } free(fpath); } }
165,509
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static RList *r_bin_wasm_get_data_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmDataEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; size_t n = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmDataEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(n = consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } ptr->offset.len = n; if (!(consume_u32 (buf + i, buf + len, &ptr->size, &i))) { free (ptr); return ret; } ptr->data = sec->payload_data + i; r_list_append (ret, ptr); r += 1; } return ret; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125
static RList *r_bin_wasm_get_data_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmDataEntry *ptr = NULL; ut32 len = sec->payload_len; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; int buflen = bin->buf->length - (ut32)sec->payload_data; ut32 count = sec->count; ut32 i = 0, r = 0; size_t n = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmDataEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { goto beach; } if (i + 4 >= buflen) { goto beach; } if (!(n = consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } ptr->offset.len = n; if (!(consume_u32 (buf + i, buf + len, &ptr->size, &i))) { goto beach; } if (i + 4 >= buflen) { goto beach; } ptr->data = sec->payload_data + i; r_list_append (ret, ptr); r += 1; } return ret; beach: free (ptr); return ret; }
168,251
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if it wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; /* ->current must be initialized; rewind doesn't set it and valid * doesn't check whether it's set */ iterator->current = object; } zval_add_ref(&object); return (zend_object_iterator*)iterator; } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if it wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; /* ->current must be initialized; rewind doesn't set it and valid * doesn't check whether it's set */ iterator->current = object; } zval_add_ref(&object); return (zend_object_iterator*)iterator; }
167,069
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl_unused) { struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 fl6; struct dst_entry *dst; int res; dst = inet6_csk_route_socket(sk, &fl6); if (IS_ERR(dst)) { sk->sk_err_soft = -PTR_ERR(dst); sk->sk_route_caps = 0; kfree_skb(skb); return PTR_ERR(dst); } rcu_read_lock(); skb_dst_set_noref(skb, dst); /* Restore final destination back after routing done */ fl6.daddr = sk->sk_v6_daddr; res = ip6_xmit(sk, skb, &fl6, np->opt, np->tclass); rcu_read_unlock(); return res; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl_unused) { struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 fl6; struct dst_entry *dst; int res; dst = inet6_csk_route_socket(sk, &fl6); if (IS_ERR(dst)) { sk->sk_err_soft = -PTR_ERR(dst); sk->sk_route_caps = 0; kfree_skb(skb); return PTR_ERR(dst); } rcu_read_lock(); skb_dst_set_noref(skb, dst); /* Restore final destination back after routing done */ fl6.daddr = sk->sk_v6_daddr; res = ip6_xmit(sk, skb, &fl6, rcu_dereference(np->opt), np->tclass); rcu_read_unlock(); return res; }
167,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() { CHECK(mHandle != NULL); memset(mHandle, 0, sizeof(tagvideoEncControls)); CHECK(mEncParams != NULL); memset(mEncParams, 0, sizeof(tagvideoEncOptions)); if (!PVGetDefaultEncOption(mEncParams, 0)) { ALOGE("Failed to get default encoding parameters"); return OMX_ErrorUndefined; } mEncParams->encMode = mEncodeMode; mEncParams->encWidth[0] = mWidth; mEncParams->encHeight[0] = mHeight; mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format mEncParams->rcType = VBR_1; mEncParams->vbvDelay = 5.0f; mEncParams->profile_level = CORE_PROFILE_LEVEL2; mEncParams->packetSize = 32; mEncParams->rvlcEnable = PV_OFF; mEncParams->numLayers = 1; mEncParams->timeIncRes = 1000; mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate; mEncParams->bitRate[0] = mBitrate; mEncParams->iQuant[0] = 15; mEncParams->pQuant[0] = 12; mEncParams->quantType[0] = 0; mEncParams->noFrameSkipped = PV_OFF; if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) { free(mInputFrameData); mInputFrameData = NULL; if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) { ALOGE("b/25812794, Buffer size is too big."); return OMX_ErrorBadParameter; } mInputFrameData = (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1); CHECK(mInputFrameData != NULL); } if (mWidth % 16 != 0 || mHeight % 16 != 0) { ALOGE("Video frame size %dx%d must be a multiple of 16", mWidth, mHeight); return OMX_ErrorBadParameter; } if (mIDRFrameRefreshIntervalInSec < 0) { mEncParams->intraPeriod = -1; } else if (mIDRFrameRefreshIntervalInSec == 0) { mEncParams->intraPeriod = 1; // All I frames } else { mEncParams->intraPeriod = (mIDRFrameRefreshIntervalInSec * mFramerate) >> 16; } mEncParams->numIntraMB = 0; mEncParams->sceneDetect = PV_ON; mEncParams->searchRange = 16; mEncParams->mv8x8Enable = PV_OFF; mEncParams->gobHeaderInterval = 0; mEncParams->useACPred = PV_ON; mEncParams->intraDCVlcTh = 0; return OMX_ErrorNone; } Commit Message: SoftMPEG4: Check the buffer size before writing the reference frame. Also prevent overflow in SoftMPEG4 and division by zero in SoftMPEG4Encoder. Bug: 30033990 Change-Id: I7701f5fc54c2670587d122330e5dc851f64ed3c2 (cherry picked from commit 695123195034402ca76169b195069c28c30342d3) CWE ID: CWE-264
OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() { CHECK(mHandle != NULL); memset(mHandle, 0, sizeof(tagvideoEncControls)); CHECK(mEncParams != NULL); memset(mEncParams, 0, sizeof(tagvideoEncOptions)); if (!PVGetDefaultEncOption(mEncParams, 0)) { ALOGE("Failed to get default encoding parameters"); return OMX_ErrorUndefined; } if (mFramerate == 0) { ALOGE("Framerate should not be 0"); return OMX_ErrorUndefined; } mEncParams->encMode = mEncodeMode; mEncParams->encWidth[0] = mWidth; mEncParams->encHeight[0] = mHeight; mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format mEncParams->rcType = VBR_1; mEncParams->vbvDelay = 5.0f; mEncParams->profile_level = CORE_PROFILE_LEVEL2; mEncParams->packetSize = 32; mEncParams->rvlcEnable = PV_OFF; mEncParams->numLayers = 1; mEncParams->timeIncRes = 1000; mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate; mEncParams->bitRate[0] = mBitrate; mEncParams->iQuant[0] = 15; mEncParams->pQuant[0] = 12; mEncParams->quantType[0] = 0; mEncParams->noFrameSkipped = PV_OFF; if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) { free(mInputFrameData); mInputFrameData = NULL; if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) { ALOGE("b/25812794, Buffer size is too big."); return OMX_ErrorBadParameter; } mInputFrameData = (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1); CHECK(mInputFrameData != NULL); } if (mWidth % 16 != 0 || mHeight % 16 != 0) { ALOGE("Video frame size %dx%d must be a multiple of 16", mWidth, mHeight); return OMX_ErrorBadParameter; } if (mIDRFrameRefreshIntervalInSec < 0) { mEncParams->intraPeriod = -1; } else if (mIDRFrameRefreshIntervalInSec == 0) { mEncParams->intraPeriod = 1; // All I frames } else { mEncParams->intraPeriod = (mIDRFrameRefreshIntervalInSec * mFramerate) >> 16; } mEncParams->numIntraMB = 0; mEncParams->sceneDetect = PV_ON; mEncParams->searchRange = 16; mEncParams->mv8x8Enable = PV_OFF; mEncParams->gobHeaderInterval = 0; mEncParams->useACPred = PV_ON; mEncParams->intraDCVlcTh = 0; return OMX_ErrorNone; }
173,402
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: usage(int iExitCode) { char word[32]; sprintf( word, getJobActionString(mode) ); fprintf( stderr, "Usage: %s [options] [constraints]\n", MyName ); fprintf( stderr, " where [options] is zero or more of:\n" ); fprintf( stderr, " -help Display this message and exit\n" ); fprintf( stderr, " -version Display version information and exit\n" ); fprintf( stderr, " -name schedd_name Connect to the given schedd\n" ); fprintf( stderr, " -pool hostname Use the given central manager to find daemons\n" ); fprintf( stderr, " -addr <ip:port> Connect directly to the given \"sinful string\"\n" ); if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -reason reason Use the given RemoveReason\n"); } else if( mode == JA_RELEASE_JOBS ) { fprintf( stderr, " -reason reason Use the given ReleaseReason\n"); } else if( mode == JA_HOLD_JOBS ) { fprintf( stderr, " -reason reason Use the given HoldReason\n"); fprintf( stderr, " -subcode number Set HoldReasonSubCode\n"); } if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -forcex Force the immediate local removal of jobs in the X state\n" " (only affects jobs already being removed)\n" ); } if( mode == JA_VACATE_JOBS || mode == JA_VACATE_FAST_JOBS ) { fprintf( stderr, " -fast Use a fast vacate (hardkill)\n" ); } fprintf( stderr, " and where [constraints] is one of:\n" ); fprintf( stderr, " cluster.proc %s the given job\n", word ); fprintf( stderr, " cluster %s the given cluster of jobs\n", word ); fprintf( stderr, " user %s all jobs owned by user\n", word ); fprintf( stderr, " -constraint expr %s all jobs matching the boolean expression\n", word ); fprintf( stderr, " -all %s all jobs " "(cannot be used with other constraints)\n", word ); exit( iExitCode ); } Commit Message: CWE ID: CWE-134
usage(int iExitCode) { char word[32]; sprintf( word, "%s", getJobActionString(mode) ); fprintf( stderr, "Usage: %s [options] [constraints]\n", MyName ); fprintf( stderr, " where [options] is zero or more of:\n" ); fprintf( stderr, " -help Display this message and exit\n" ); fprintf( stderr, " -version Display version information and exit\n" ); fprintf( stderr, " -name schedd_name Connect to the given schedd\n" ); fprintf( stderr, " -pool hostname Use the given central manager to find daemons\n" ); fprintf( stderr, " -addr <ip:port> Connect directly to the given \"sinful string\"\n" ); if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -reason reason Use the given RemoveReason\n"); } else if( mode == JA_RELEASE_JOBS ) { fprintf( stderr, " -reason reason Use the given ReleaseReason\n"); } else if( mode == JA_HOLD_JOBS ) { fprintf( stderr, " -reason reason Use the given HoldReason\n"); fprintf( stderr, " -subcode number Set HoldReasonSubCode\n"); } if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -forcex Force the immediate local removal of jobs in the X state\n" " (only affects jobs already being removed)\n" ); } if( mode == JA_VACATE_JOBS || mode == JA_VACATE_FAST_JOBS ) { fprintf( stderr, " -fast Use a fast vacate (hardkill)\n" ); } fprintf( stderr, " and where [constraints] is one of:\n" ); fprintf( stderr, " cluster.proc %s the given job\n", word ); fprintf( stderr, " cluster %s the given cluster of jobs\n", word ); fprintf( stderr, " user %s all jobs owned by user\n", word ); fprintf( stderr, " -constraint expr %s all jobs matching the boolean expression\n", word ); fprintf( stderr, " -all %s all jobs " "(cannot be used with other constraints)\n", word ); exit( iExitCode ); }
165,375
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t oz_cdev_write(struct file *filp, const char __user *buf, size_t count, loff_t *fpos) { struct oz_pd *pd; struct oz_elt_buf *eb; struct oz_elt_info *ei; struct oz_elt *elt; struct oz_app_hdr *app_hdr; struct oz_serial_ctx *ctx; spin_lock_bh(&g_cdev.lock); pd = g_cdev.active_pd; if (pd) oz_pd_get(pd); spin_unlock_bh(&g_cdev.lock); if (pd == NULL) return -ENXIO; if (!(pd->state & OZ_PD_S_CONNECTED)) return -EAGAIN; eb = &pd->elt_buff; ei = oz_elt_info_alloc(eb); if (ei == NULL) { count = 0; goto out; } elt = (struct oz_elt *)ei->data; app_hdr = (struct oz_app_hdr *)(elt+1); elt->length = sizeof(struct oz_app_hdr) + count; elt->type = OZ_ELT_APP_DATA; ei->app_id = OZ_APPID_SERIAL; ei->length = elt->length + sizeof(struct oz_elt); app_hdr->app_id = OZ_APPID_SERIAL; if (copy_from_user(app_hdr+1, buf, count)) goto out; spin_lock_bh(&pd->app_lock[OZ_APPID_USB-1]); ctx = (struct oz_serial_ctx *)pd->app_ctx[OZ_APPID_SERIAL-1]; if (ctx) { app_hdr->elt_seq_num = ctx->tx_seq_num++; if (ctx->tx_seq_num == 0) ctx->tx_seq_num = 1; spin_lock(&eb->lock); if (oz_queue_elt_info(eb, 0, 0, ei) == 0) ei = NULL; spin_unlock(&eb->lock); } spin_unlock_bh(&pd->app_lock[OZ_APPID_USB-1]); out: if (ei) { count = 0; spin_lock_bh(&eb->lock); oz_elt_info_free(eb, ei); spin_unlock_bh(&eb->lock); } oz_pd_put(pd); return count; } Commit Message: staging: ozwpan: prevent overflow in oz_cdev_write() We need to check "count" so we don't overflow the ei->data buffer. Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119
static ssize_t oz_cdev_write(struct file *filp, const char __user *buf, size_t count, loff_t *fpos) { struct oz_pd *pd; struct oz_elt_buf *eb; struct oz_elt_info *ei; struct oz_elt *elt; struct oz_app_hdr *app_hdr; struct oz_serial_ctx *ctx; if (count > sizeof(ei->data) - sizeof(*elt) - sizeof(*app_hdr)) return -EINVAL; spin_lock_bh(&g_cdev.lock); pd = g_cdev.active_pd; if (pd) oz_pd_get(pd); spin_unlock_bh(&g_cdev.lock); if (pd == NULL) return -ENXIO; if (!(pd->state & OZ_PD_S_CONNECTED)) return -EAGAIN; eb = &pd->elt_buff; ei = oz_elt_info_alloc(eb); if (ei == NULL) { count = 0; goto out; } elt = (struct oz_elt *)ei->data; app_hdr = (struct oz_app_hdr *)(elt+1); elt->length = sizeof(struct oz_app_hdr) + count; elt->type = OZ_ELT_APP_DATA; ei->app_id = OZ_APPID_SERIAL; ei->length = elt->length + sizeof(struct oz_elt); app_hdr->app_id = OZ_APPID_SERIAL; if (copy_from_user(app_hdr+1, buf, count)) goto out; spin_lock_bh(&pd->app_lock[OZ_APPID_USB-1]); ctx = (struct oz_serial_ctx *)pd->app_ctx[OZ_APPID_SERIAL-1]; if (ctx) { app_hdr->elt_seq_num = ctx->tx_seq_num++; if (ctx->tx_seq_num == 0) ctx->tx_seq_num = 1; spin_lock(&eb->lock); if (oz_queue_elt_info(eb, 0, 0, ei) == 0) ei = NULL; spin_unlock(&eb->lock); } spin_unlock_bh(&pd->app_lock[OZ_APPID_USB-1]); out: if (ei) { count = 0; spin_lock_bh(&eb->lock); oz_elt_info_free(eb, ei); spin_unlock_bh(&eb->lock); } oz_pd_put(pd); return count; }
165,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name) { ASSERT(m_world->isMainWorld()); if (m_context.isEmpty()) return; if (document->hasNamedItem(name.impl()) || document->hasExtraNamedItem(name.impl())) return; v8::HandleScope handleScope(m_isolate); v8::Context::Scope contextScope(m_context.newLocal(m_isolate)); ASSERT(!m_document.isEmpty()); v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate); checkDocumentWrapper(documentHandle, document); documentHandle->Delete(v8String(name, m_isolate)); } Commit Message: Fix tracking of the id attribute string if it is shared across elements. The patch to remove AtomicStringImpl: http://src.chromium.org/viewvc/blink?view=rev&rev=154790 Exposed a lifetime issue with strings for id attributes. We simply need to use AtomicString. BUG=290566 Review URL: https://codereview.chromium.org/33793004 git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name) { ASSERT(m_world->isMainWorld()); if (m_context.isEmpty()) return; if (document->hasNamedItem(name) || document->hasExtraNamedItem(name)) return; v8::HandleScope handleScope(m_isolate); v8::Context::Scope contextScope(m_context.newLocal(m_isolate)); ASSERT(!m_document.isEmpty()); v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate); checkDocumentWrapper(documentHandle, document); documentHandle->Delete(v8String(name, m_isolate)); }
171,154
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/348 CWE ID: CWE-787
static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); }
170,102
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->len = len; JAS_DBGLOG(10, ( "preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n", '"', boxinfo->name, '"', box->type, box->len )); if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); box->ops = &boxinfo->ops; if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jp2_box_create0())) { goto error; } if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->len = len; JAS_DBGLOG(10, ( "preliminary processing of JP2 box: " "type=%c%s%c (0x%08x); length=%"PRIuFAST32"\n", '"', boxinfo->name, '"', box->type, box->len )); if (box->len == 1) { JAS_DBGLOG(10, ("big length\n")); if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); box->ops = &boxinfo->ops; if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; }
168,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(xml_set_object) { xml_parser *parser; zval *pind, *mythis; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ro", &pind, &mythis) == FAILURE) { return; } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); /* please leave this commented - or ask [email protected] before doing it (again) */ if (parser->object) { zval_ptr_dtor(&parser->object); } /* please leave this commented - or ask [email protected] before doing it (again) */ /* #ifdef ZEND_ENGINE_2 zval_add_ref(&parser->object); #endif */ ALLOC_ZVAL(parser->object); MAKE_COPY_ZVAL(&mythis, parser->object); RETVAL_TRUE; } Commit Message: CWE ID: CWE-119
PHP_FUNCTION(xml_set_object) { xml_parser *parser; zval *pind, *mythis; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ro", &pind, &mythis) == FAILURE) { return; } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); /* please leave this commented - or ask [email protected] before doing it (again) */ if (parser->object) { zval_ptr_dtor(&parser->object); } /* please leave this commented - or ask [email protected] before doing it (again) */ /* #ifdef ZEND_ENGINE_2 zval_add_ref(&parser->object); #endif */ ALLOC_ZVAL(parser->object); MAKE_COPY_ZVAL(&mythis, parser->object); RETVAL_TRUE; }
165,036
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION( locale_get_keywords ) { UEnumeration* e = NULL; UErrorCode status = U_ZERO_ERROR; const char* kw_key = NULL; int32_t kw_key_len = 0; const char* loc_name = NULL; int loc_name_len = 0; /* ICU expects the buffer to be allocated before calling the function and so the buffer size has been explicitly specified ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 hence the kw_value buffer size is 100 */ char* kw_value = NULL; int32_t kw_value_len = 100; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Get the keywords */ e = uloc_openKeywords( loc_name, &status ); if( e != NULL ) { /* Traverse it, filling the return array. */ array_init( return_value ); while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){ kw_value = ecalloc( 1 , kw_value_len ); /* Get the keyword value for each keyword */ kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status ); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; kw_value = erealloc( kw_value , kw_value_len+1); kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status ); } else if(!U_FAILURE(status)) { kw_value = erealloc( kw_value , kw_value_len+1); } if (U_FAILURE(status)) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC ); if( kw_value){ efree( kw_value ); } zval_dtor(return_value); RETURN_FALSE; } add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0); } /* end of while */ } /* end of if e!=NULL */ uenum_close( e ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION( locale_get_keywords ) { UEnumeration* e = NULL; UErrorCode status = U_ZERO_ERROR; const char* kw_key = NULL; int32_t kw_key_len = 0; const char* loc_name = NULL; int loc_name_len = 0; /* ICU expects the buffer to be allocated before calling the function and so the buffer size has been explicitly specified ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 hence the kw_value buffer size is 100 */ char* kw_value = NULL; int32_t kw_value_len = 100; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Get the keywords */ e = uloc_openKeywords( loc_name, &status ); if( e != NULL ) { /* Traverse it, filling the return array. */ array_init( return_value ); while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){ kw_value = ecalloc( 1 , kw_value_len ); /* Get the keyword value for each keyword */ kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status ); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; kw_value = erealloc( kw_value , kw_value_len+1); kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status ); } else if(!U_FAILURE(status)) { kw_value = erealloc( kw_value , kw_value_len+1); } if (U_FAILURE(status)) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC ); if( kw_value){ efree( kw_value ); } zval_dtor(return_value); RETURN_FALSE; } add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0); } /* end of while */ } /* end of if e!=NULL */ uenum_close( e ); }
167,190
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *path_name(const struct name_path *path, const char *name) { const struct name_path *p; char *n, *m; int nlen = strlen(name); int len = nlen + 1; for (p = path; p; p = p->up) { if (p->elem_len) len += p->elem_len + 1; } n = xmalloc(len); m = n + len - (nlen + 1); strcpy(m, name); for (p = path; p; p = p->up) { if (p->elem_len) { m -= p->elem_len + 1; memcpy(m, p->elem, p->elem_len); m[p->elem_len] = '/'; } } return n; } Commit Message: prefer memcpy to strcpy When we already know the length of a string (e.g., because we just malloc'd to fit it), it's nicer to use memcpy than strcpy, as it makes it more obvious that we are not going to overflow the buffer (because the size we pass matches the size in the allocation). This also eliminates calls to strcpy, which make auditing the code base harder. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
char *path_name(const struct name_path *path, const char *name) { const struct name_path *p; char *n, *m; int nlen = strlen(name); int len = nlen + 1; for (p = path; p; p = p->up) { if (p->elem_len) len += p->elem_len + 1; } n = xmalloc(len); m = n + len - (nlen + 1); memcpy(m, name, nlen + 1); for (p = path; p; p = p->up) { if (p->elem_len) { m -= p->elem_len + 1; memcpy(m, p->elem, p->elem_len); m[p->elem_len] = '/'; } } return n; }
167,429
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ehci_advance_state(EHCIState *ehci, int async) { EHCIQueue *q = NULL; int again; do { case EST_WAITLISTHEAD: again = ehci_state_waitlisthead(ehci, async); break; case EST_FETCHENTRY: again = ehci_state_fetchentry(ehci, async); break; case EST_FETCHQH: q = ehci_state_fetchqh(ehci, async); if (q != NULL) { assert(q->async == async); again = 1; } else { again = 0; } break; case EST_FETCHITD: again = ehci_state_fetchitd(ehci, async); break; case EST_FETCHSITD: again = ehci_state_fetchsitd(ehci, async); break; case EST_ADVANCEQUEUE: case EST_FETCHQTD: assert(q != NULL); again = ehci_state_fetchqtd(q); break; case EST_HORIZONTALQH: assert(q != NULL); again = ehci_state_horizqh(q); break; case EST_EXECUTE: assert(q != NULL); again = ehci_state_execute(q); if (async) { ehci->async_stepdown = 0; } break; case EST_EXECUTING: assert(q != NULL); if (async) { ehci->async_stepdown = 0; } again = ehci_state_executing(q); break; case EST_WRITEBACK: assert(q != NULL); again = ehci_state_writeback(q); if (!async) { ehci->periodic_sched_active = PERIODIC_ACTIVE; } break; default: fprintf(stderr, "Bad state!\n"); again = -1; g_assert_not_reached(); break; } break; } Commit Message: CWE ID: CWE-20
static void ehci_advance_state(EHCIState *ehci, int async) { EHCIQueue *q = NULL; int itd_count = 0; int again; do { case EST_WAITLISTHEAD: again = ehci_state_waitlisthead(ehci, async); break; case EST_FETCHENTRY: again = ehci_state_fetchentry(ehci, async); break; case EST_FETCHQH: q = ehci_state_fetchqh(ehci, async); if (q != NULL) { assert(q->async == async); again = 1; } else { again = 0; } break; case EST_FETCHITD: again = ehci_state_fetchitd(ehci, async); itd_count++; break; case EST_FETCHSITD: again = ehci_state_fetchsitd(ehci, async); itd_count++; break; case EST_ADVANCEQUEUE: case EST_FETCHQTD: assert(q != NULL); again = ehci_state_fetchqtd(q); break; case EST_HORIZONTALQH: assert(q != NULL); again = ehci_state_horizqh(q); break; case EST_EXECUTE: assert(q != NULL); again = ehci_state_execute(q); if (async) { ehci->async_stepdown = 0; } break; case EST_EXECUTING: assert(q != NULL); if (async) { ehci->async_stepdown = 0; } again = ehci_state_executing(q); break; case EST_WRITEBACK: assert(q != NULL); again = ehci_state_writeback(q); if (!async) { ehci->periodic_sched_active = PERIODIC_ACTIVE; } break; default: fprintf(stderr, "Bad state!\n"); again = -1; g_assert_not_reached(); break; } break; }
165,075
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int write_empty_blocks(struct page *page, unsigned from, unsigned to, int mode) { struct inode *inode = page->mapping->host; unsigned start, end, next, blksize; sector_t block = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits); int ret; blksize = 1 << inode->i_blkbits; next = end = 0; while (next < from) { next += blksize; block++; } start = next; do { next += blksize; ret = needs_empty_write(block, inode); if (unlikely(ret < 0)) return ret; if (ret == 0) { if (end) { ret = __block_write_begin(page, start, end - start, gfs2_block_map); if (unlikely(ret)) return ret; ret = empty_write_end(page, start, end, mode); if (unlikely(ret)) return ret; end = 0; } start = next; } else end = next; block++; } while (next < to); if (end) { ret = __block_write_begin(page, start, end - start, gfs2_block_map); if (unlikely(ret)) return ret; ret = empty_write_end(page, start, end, mode); if (unlikely(ret)) return ret; } return 0; } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <[email protected]> Signed-off-by: Steven Whitehouse <[email protected]> CWE ID: CWE-119
static int write_empty_blocks(struct page *page, unsigned from, unsigned to,
166,215
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void vp8mt_de_alloc_temp_buffers(VP8D_COMP *pbi, int mb_rows) { int i; if (pbi->b_multithreaded_rd) { vpx_free(pbi->mt_current_mb_col); pbi->mt_current_mb_col = NULL ; /* Free above_row buffers. */ if (pbi->mt_yabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_yabove_row[i]); pbi->mt_yabove_row[i] = NULL ; } vpx_free(pbi->mt_yabove_row); pbi->mt_yabove_row = NULL ; } if (pbi->mt_uabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_uabove_row[i]); pbi->mt_uabove_row[i] = NULL ; } vpx_free(pbi->mt_uabove_row); pbi->mt_uabove_row = NULL ; } if (pbi->mt_vabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_vabove_row[i]); pbi->mt_vabove_row[i] = NULL ; } vpx_free(pbi->mt_vabove_row); pbi->mt_vabove_row = NULL ; } /* Free left_col buffers. */ if (pbi->mt_yleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_yleft_col[i]); pbi->mt_yleft_col[i] = NULL ; } vpx_free(pbi->mt_yleft_col); pbi->mt_yleft_col = NULL ; } if (pbi->mt_uleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_uleft_col[i]); pbi->mt_uleft_col[i] = NULL ; } vpx_free(pbi->mt_uleft_col); pbi->mt_uleft_col = NULL ; } if (pbi->mt_vleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_vleft_col[i]); pbi->mt_vleft_col[i] = NULL ; } vpx_free(pbi->mt_vleft_col); pbi->mt_vleft_col = NULL ; } } } Commit Message: vp8:fix threading issues 1 - stops de allocating before threads are closed. 2 - limits threads to mb_rows when mb_rows < partitions BUG=webm:851 Bug: 30436808 Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b (cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e) CWE ID:
void vp8mt_de_alloc_temp_buffers(VP8D_COMP *pbi, int mb_rows) void vp8mt_de_alloc_temp_buffers(VP8D_COMP *pbi, int mb_rows) { int i; vpx_free(pbi->mt_current_mb_col); pbi->mt_current_mb_col = NULL; /* Free above_row buffers. */ if (pbi->mt_yabove_row) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_yabove_row[i]); pbi->mt_yabove_row[i] = NULL; } vpx_free(pbi->mt_yabove_row); pbi->mt_yabove_row = NULL; } if (pbi->mt_uabove_row) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_uabove_row[i]); pbi->mt_uabove_row[i] = NULL; } vpx_free(pbi->mt_uabove_row); pbi->mt_uabove_row = NULL; } if (pbi->mt_vabove_row) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_vabove_row[i]); pbi->mt_vabove_row[i] = NULL; } vpx_free(pbi->mt_vabove_row); pbi->mt_vabove_row = NULL; } /* Free left_col buffers. */ if (pbi->mt_yleft_col) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_yleft_col[i]); pbi->mt_yleft_col[i] = NULL; } vpx_free(pbi->mt_yleft_col); pbi->mt_yleft_col = NULL; } if (pbi->mt_uleft_col) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_uleft_col[i]); pbi->mt_uleft_col[i] = NULL; } vpx_free(pbi->mt_uleft_col); pbi->mt_uleft_col = NULL; } if (pbi->mt_vleft_col) { for (i = 0; i < mb_rows; ++i) { vpx_free(pbi->mt_vleft_col[i]); pbi->mt_vleft_col[i] = NULL; } vpx_free(pbi->mt_vleft_col); pbi->mt_vleft_col = NULL; } }
174,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SelectionInDOMTree ConvertToSelectionInDOMTree( const SelectionInFlatTree& selection_in_flat_tree) { return SelectionInDOMTree::Builder() .SetAffinity(selection_in_flat_tree.Affinity()) .SetBaseAndExtent(ToPositionInDOMTree(selection_in_flat_tree.Base()), ToPositionInDOMTree(selection_in_flat_tree.Extent())) .SetIsDirectional(selection_in_flat_tree.IsDirectional()) .SetIsHandleVisible(selection_in_flat_tree.IsHandleVisible()) .Build(); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
SelectionInDOMTree ConvertToSelectionInDOMTree( const SelectionInFlatTree& selection_in_flat_tree) { return SelectionInDOMTree::Builder() .SetAffinity(selection_in_flat_tree.Affinity()) .SetBaseAndExtent(ToPositionInDOMTree(selection_in_flat_tree.Base()), ToPositionInDOMTree(selection_in_flat_tree.Extent())) .SetIsDirectional(selection_in_flat_tree.IsDirectional()) .Build(); }
171,762
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; switch (ioctl) { case KVM_ARM_VCPU_INIT: { struct kvm_vcpu_init init; if (copy_from_user(&init, argp, sizeof(init))) return -EFAULT; return kvm_vcpu_set_target(vcpu, &init); } case KVM_SET_ONE_REG: case KVM_GET_ONE_REG: { struct kvm_one_reg reg; if (copy_from_user(&reg, argp, sizeof(reg))) return -EFAULT; if (ioctl == KVM_SET_ONE_REG) return kvm_arm_set_reg(vcpu, &reg); else return kvm_arm_get_reg(vcpu, &reg); } case KVM_GET_REG_LIST: { struct kvm_reg_list __user *user_list = argp; struct kvm_reg_list reg_list; unsigned n; if (copy_from_user(&reg_list, user_list, sizeof(reg_list))) return -EFAULT; n = reg_list.n; reg_list.n = kvm_arm_num_regs(vcpu); if (copy_to_user(user_list, &reg_list, sizeof(reg_list))) return -EFAULT; if (n < reg_list.n) return -E2BIG; return kvm_arm_copy_reg_indices(vcpu, user_list->reg); } default: return -EINVAL; } } Commit Message: ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl Some ARM KVM VCPU ioctls require the vCPU to be properly initialized with the KVM_ARM_VCPU_INIT ioctl before being used with further requests. KVM_RUN checks whether this initialization has been done, but other ioctls do not. Namely KVM_GET_REG_LIST will dereference an array with index -1 without initialization and thus leads to a kernel oops. Fix this by adding checks before executing the ioctl handlers. [ Removed superflous comment from static function - Christoffer ] Changes from v1: * moved check into a static function with a meaningful name Signed-off-by: Andre Przywara <[email protected]> Signed-off-by: Christoffer Dall <[email protected]> CWE ID: CWE-399
long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; switch (ioctl) { case KVM_ARM_VCPU_INIT: { struct kvm_vcpu_init init; if (copy_from_user(&init, argp, sizeof(init))) return -EFAULT; return kvm_vcpu_set_target(vcpu, &init); } case KVM_SET_ONE_REG: case KVM_GET_ONE_REG: { struct kvm_one_reg reg; if (unlikely(!kvm_vcpu_initialized(vcpu))) return -ENOEXEC; if (copy_from_user(&reg, argp, sizeof(reg))) return -EFAULT; if (ioctl == KVM_SET_ONE_REG) return kvm_arm_set_reg(vcpu, &reg); else return kvm_arm_get_reg(vcpu, &reg); } case KVM_GET_REG_LIST: { struct kvm_reg_list __user *user_list = argp; struct kvm_reg_list reg_list; unsigned n; if (unlikely(!kvm_vcpu_initialized(vcpu))) return -ENOEXEC; if (copy_from_user(&reg_list, user_list, sizeof(reg_list))) return -EFAULT; n = reg_list.n; reg_list.n = kvm_arm_num_regs(vcpu); if (copy_to_user(user_list, &reg_list, sizeof(reg_list))) return -EFAULT; if (n < reg_list.n) return -E2BIG; return kvm_arm_copy_reg_indices(vcpu, user_list->reg); } default: return -EINVAL; } }
165,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CuePoint::Load(IMkvReader* pReader) { if (m_timecode >= 0) // already loaded return; assert(m_track_positions == NULL); assert(m_track_positions_count == 0); long long pos_ = -m_timecode; const long long element_start = pos_; long long stop; { long len; const long long id = ReadUInt(pReader, pos_, len); assert(id == 0x3B); // CuePoint ID if (id != 0x3B) return; pos_ += len; // consume ID const long long size = ReadUInt(pReader, pos_, len); assert(size >= 0); pos_ += len; // consume Size field stop = pos_ + size; } const long long element_size = stop - element_start; long long pos = pos_; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x33) // CueTime ID m_timecode = UnserializeUInt(pReader, pos, size); else if (id == 0x37) // CueTrackPosition(s) ID ++m_track_positions_count; pos += size; // consume payload assert(pos <= stop); } assert(m_timecode >= 0); assert(m_track_positions_count > 0); m_track_positions = new TrackPosition[m_track_positions_count]; TrackPosition* p = m_track_positions; pos = pos_; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x37) { // CueTrackPosition(s) ID TrackPosition& tp = *p++; tp.Parse(pReader, pos, size); } pos += size; // consume payload assert(pos <= stop); } assert(size_t(p - m_track_positions) == m_track_positions_count); m_element_start = element_start; m_element_size = element_size; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
void CuePoint::Load(IMkvReader* pReader) { bool CuePoint::Load(IMkvReader* pReader) { if (m_timecode >= 0) // already loaded return true; assert(m_track_positions == NULL); assert(m_track_positions_count == 0); long long pos_ = -m_timecode; const long long element_start = pos_; long long stop; { long len; const long long id = ReadID(pReader, pos_, len); if (id != 0x3B) return false; pos_ += len; // consume ID const long long size = ReadUInt(pReader, pos_, len); assert(size >= 0); pos_ += len; // consume Size field stop = pos_ + size; } const long long element_size = stop - element_start; long long pos = pos_; while (pos < stop) { long len; const long long id = ReadID(pReader, pos, len); if ((id < 0) || (pos + len > stop)) { return false; } pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); if ((size < 0) || (pos + len > stop)) { return false; } pos += len; // consume Size field if ((pos + size) > stop) { return false; } if (id == 0x33) // CueTime ID m_timecode = UnserializeUInt(pReader, pos, size); else if (id == 0x37) // CueTrackPosition(s) ID ++m_track_positions_count; pos += size; // consume payload } if (m_timecode < 0 || m_track_positions_count <= 0) { return false; } m_track_positions = new (std::nothrow) TrackPosition[m_track_positions_count]; if (m_track_positions == NULL) return false; TrackPosition* p = m_track_positions; pos = pos_; while (pos < stop) { long len; const long long id = ReadID(pReader, pos, len); if (id < 0 || (pos + len) > stop) return false; pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x37) { // CueTrackPosition(s) ID TrackPosition& tp = *p++; if (!tp.Parse(pReader, pos, size)) { return false; } } pos += size; // consume payload if (pos > stop) return false; } assert(size_t(p - m_track_positions) == m_track_positions_count); m_element_start = element_start; m_element_size = element_size; return true; }
173,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_string( cJSON *item ) { return print_string_ptr( item->valuestring ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static char *print_string( cJSON *item )
167,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(0 TSRMLS_CC); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } Commit Message: fix bug #64660 - yyparse can return 2, not only 1 CWE ID: CWE-20
zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result != 0) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(0 TSRMLS_CC); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; }
166,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, int xoff, int yoff, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); int diff = r - src[w * y + x]; se += diff; sse += diff * diff; } } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src, static unsigned int mb_ss_ref(const int16_t *src) { unsigned int res = 0; for (int i = 0; i < 256; ++i) { res += src[i] * src[i]; } return res; } static uint32_t variance_ref(const uint8_t *src, const uint8_t *ref, int l2w, int l2h, int src_stride_coeff, int ref_stride_coeff, uint32_t *sse_ptr, bool use_high_bit_depth_, vpx_bit_depth_t bit_depth) { int64_t se = 0; uint64_t sse = 0; const int w = 1 << l2w; const int h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int diff; if (!use_high_bit_depth_) { diff = ref[w * y * ref_stride_coeff + x] - src[w * y * src_stride_coeff + x]; se += diff; sse += diff * diff; #if CONFIG_VP9_HIGHBITDEPTH } else { diff = CONVERT_TO_SHORTPTR(ref)[w * y * ref_stride_coeff + x] - CONVERT_TO_SHORTPTR(src)[w * y * src_stride_coeff + x]; se += diff; sse += diff * diff; #endif // CONFIG_VP9_HIGHBITDEPTH } } } RoundHighBitDepth(bit_depth, &se, &sse); *sse_ptr = static_cast<uint32_t>(sse); return static_cast<uint32_t>(sse - ((static_cast<int64_t>(se) * se) >> (l2w + l2h))); } /* The subpel reference functions differ from the codec version in one aspect: * they calculate the bilinear factors directly instead of using a lookup table * and therefore upshift xoff and yoff by 1. Only every other calculated value * is used so the codec version shrinks the table to save space and maintain * compatibility with vp8. */ static uint32_t subpel_variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, int xoff, int yoff, uint32_t *sse_ptr, bool use_high_bit_depth_, vpx_bit_depth_t bit_depth) { int64_t se = 0; uint64_t sse = 0; const int w = 1 << l2w; const int h = 1 << l2h; xoff <<= 1; yoff <<= 1; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { // Bilinear interpolation at a 16th pel step. if (!use_high_bit_depth_) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); const int diff = r - src[w * y + x]; se += diff; sse += diff * diff; #if CONFIG_VP9_HIGHBITDEPTH } else { uint16_t *ref16 = CONVERT_TO_SHORTPTR(ref); uint16_t *src16 = CONVERT_TO_SHORTPTR(src); const int a1 = ref16[(w + 1) * (y + 0) + x + 0]; const int a2 = ref16[(w + 1) * (y + 0) + x + 1]; const int b1 = ref16[(w + 1) * (y + 1) + x + 0]; const int b2 = ref16[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); const int diff = r - src16[w * y + x]; se += diff; sse += diff * diff; #endif // CONFIG_VP9_HIGHBITDEPTH } } } RoundHighBitDepth(bit_depth, &se, &sse); *sse_ptr = static_cast<uint32_t>(sse); return static_cast<uint32_t>(sse - ((static_cast<int64_t>(se) * se) >> (l2w + l2h))); } class SumOfSquaresTest : public ::testing::TestWithParam<SumOfSquaresFunction> { public: SumOfSquaresTest() : func_(GetParam()) {} virtual ~SumOfSquaresTest() { libvpx_test::ClearSystemState(); } protected: void ConstTest(); void RefTest(); SumOfSquaresFunction func_; ACMRandom rnd_; }; void SumOfSquaresTest::ConstTest() { int16_t mem[256]; unsigned int res; for (int v = 0; v < 256; ++v) { for (int i = 0; i < 256; ++i) { mem[i] = v; } ASM_REGISTER_STATE_CHECK(res = func_(mem)); EXPECT_EQ(256u * (v * v), res); } } void SumOfSquaresTest::RefTest() { int16_t mem[256]; for (int i = 0; i < 100; ++i) { for (int j = 0; j < 256; ++j) { mem[j] = rnd_.Rand8() - rnd_.Rand8(); } const unsigned int expected = mb_ss_ref(mem); unsigned int res; ASM_REGISTER_STATE_CHECK(res = func_(mem)); EXPECT_EQ(expected, res); } }
174,595
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), #if defined(OS_WIN) accessible_parent_(NULL), #endif frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), is_loading_(false), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), displayed_insecure_content_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), is_being_destroyed_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), render_view_message_source_(NULL), render_frame_message_source_(NULL), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), virtual_keyboard_requested_(false), page_scale_factor_is_one_(true), loading_weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); wake_lock_service_context_.reset(new WakeLockServiceContext(this)); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID:
WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), #if defined(OS_WIN) accessible_parent_(NULL), #endif frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), is_loading_(false), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), displayed_insecure_content_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), is_being_destroyed_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), render_view_message_source_(NULL), render_frame_message_source_(NULL), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), virtual_keyboard_requested_(false), page_scale_factor_is_one_(true), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); wake_lock_service_context_.reset(new WakeLockServiceContext(this)); }
172,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __inet_del_ifa(struct in_device *in_dev, struct in_ifaddr **ifap, int destroy, struct nlmsghdr *nlh, u32 portid) { struct in_ifaddr *promote = NULL; struct in_ifaddr *ifa, *ifa1 = *ifap; struct in_ifaddr *last_prim = in_dev->ifa_list; struct in_ifaddr *prev_prom = NULL; int do_promote = IN_DEV_PROMOTE_SECONDARIES(in_dev); ASSERT_RTNL(); /* 1. Deleting primary ifaddr forces deletion all secondaries * unless alias promotion is set **/ if (!(ifa1->ifa_flags & IFA_F_SECONDARY)) { struct in_ifaddr **ifap1 = &ifa1->ifa_next; while ((ifa = *ifap1) != NULL) { if (!(ifa->ifa_flags & IFA_F_SECONDARY) && ifa1->ifa_scope <= ifa->ifa_scope) last_prim = ifa; if (!(ifa->ifa_flags & IFA_F_SECONDARY) || ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) { ifap1 = &ifa->ifa_next; prev_prom = ifa; continue; } if (!do_promote) { inet_hash_remove(ifa); *ifap1 = ifa->ifa_next; rtmsg_ifa(RTM_DELADDR, ifa, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa); inet_free_ifa(ifa); } else { promote = ifa; break; } } } /* On promotion all secondaries from subnet are changing * the primary IP, we must remove all their routes silently * and later to add them back with new prefsrc. Do this * while all addresses are on the device list. */ for (ifa = promote; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask == ifa->ifa_mask && inet_ifa_match(ifa1->ifa_address, ifa)) fib_del_ifaddr(ifa, ifa1); } /* 2. Unlink it */ *ifap = ifa1->ifa_next; inet_hash_remove(ifa1); /* 3. Announce address deletion */ /* Send message first, then call notifier. At first sight, FIB update triggered by notifier will refer to already deleted ifaddr, that could confuse netlink listeners. It is not true: look, gated sees that route deleted and if it still thinks that ifaddr is valid, it will try to restore deleted routes... Grr. So that, this order is correct. */ rtmsg_ifa(RTM_DELADDR, ifa1, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa1); if (promote) { struct in_ifaddr *next_sec = promote->ifa_next; if (prev_prom) { prev_prom->ifa_next = promote->ifa_next; promote->ifa_next = last_prim->ifa_next; last_prim->ifa_next = promote; } promote->ifa_flags &= ~IFA_F_SECONDARY; rtmsg_ifa(RTM_NEWADDR, promote, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_UP, promote); for (ifa = next_sec; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) continue; fib_add_ifaddr(ifa); } } if (destroy) inet_free_ifa(ifa1); } Commit Message: ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <[email protected]> Signed-off-by: David S. Miller <[email protected]> Tested-by: Cyrill Gorcunov <[email protected]> CWE ID: CWE-399
static void __inet_del_ifa(struct in_device *in_dev, struct in_ifaddr **ifap, int destroy, struct nlmsghdr *nlh, u32 portid) { struct in_ifaddr *promote = NULL; struct in_ifaddr *ifa, *ifa1 = *ifap; struct in_ifaddr *last_prim = in_dev->ifa_list; struct in_ifaddr *prev_prom = NULL; int do_promote = IN_DEV_PROMOTE_SECONDARIES(in_dev); ASSERT_RTNL(); if (in_dev->dead) goto no_promotions; /* 1. Deleting primary ifaddr forces deletion all secondaries * unless alias promotion is set **/ if (!(ifa1->ifa_flags & IFA_F_SECONDARY)) { struct in_ifaddr **ifap1 = &ifa1->ifa_next; while ((ifa = *ifap1) != NULL) { if (!(ifa->ifa_flags & IFA_F_SECONDARY) && ifa1->ifa_scope <= ifa->ifa_scope) last_prim = ifa; if (!(ifa->ifa_flags & IFA_F_SECONDARY) || ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) { ifap1 = &ifa->ifa_next; prev_prom = ifa; continue; } if (!do_promote) { inet_hash_remove(ifa); *ifap1 = ifa->ifa_next; rtmsg_ifa(RTM_DELADDR, ifa, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa); inet_free_ifa(ifa); } else { promote = ifa; break; } } } /* On promotion all secondaries from subnet are changing * the primary IP, we must remove all their routes silently * and later to add them back with new prefsrc. Do this * while all addresses are on the device list. */ for (ifa = promote; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask == ifa->ifa_mask && inet_ifa_match(ifa1->ifa_address, ifa)) fib_del_ifaddr(ifa, ifa1); } no_promotions: /* 2. Unlink it */ *ifap = ifa1->ifa_next; inet_hash_remove(ifa1); /* 3. Announce address deletion */ /* Send message first, then call notifier. At first sight, FIB update triggered by notifier will refer to already deleted ifaddr, that could confuse netlink listeners. It is not true: look, gated sees that route deleted and if it still thinks that ifaddr is valid, it will try to restore deleted routes... Grr. So that, this order is correct. */ rtmsg_ifa(RTM_DELADDR, ifa1, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa1); if (promote) { struct in_ifaddr *next_sec = promote->ifa_next; if (prev_prom) { prev_prom->ifa_next = promote->ifa_next; promote->ifa_next = last_prim->ifa_next; last_prim->ifa_next = promote; } promote->ifa_flags &= ~IFA_F_SECONDARY; rtmsg_ifa(RTM_NEWADDR, promote, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_UP, promote); for (ifa = next_sec; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) continue; fib_add_ifaddr(ifa); } } if (destroy) inet_free_ifa(ifa1); }
167,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Reverb_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData){ android::ReverbContext * pContext = (android::ReverbContext *) self; int retsize; LVREV_ControlParams_st ActiveParams; /* Current control Parameters */ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */ if (pContext == NULL){ ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL"); return -EINVAL; } switch (cmdCode){ case EFFECT_CMD_INIT: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_INIT: ERROR"); return -EINVAL; } *(int *) pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_CONFIG: ERROR"); return -EINVAL; } *(int *) pReplyData = android::Reverb_setConfig(pContext, (effect_config_t *) pCmdData); break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_GET_CONFIG: ERROR"); return -EINVAL; } android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: Reverb_setConfig(pContext, &pContext->config); break; case EFFECT_CMD_GET_PARAM:{ effect_param_t *p = (effect_param_t *)pCmdData; if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) || cmdSize < (sizeof(effect_param_t) + p->psize) || pReplyData == NULL || replySize == NULL || *replySize < (sizeof(effect_param_t) + p->psize)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); p->status = android::Reverb_getParameter(pContext, (void *)p->data, (size_t *)&p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } break; case EFFECT_CMD_SET_PARAM:{ if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } *(int *)pReplyData = android::Reverb_setParameter(pContext, (void *)p->data, p->data + p->psize); } break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_ENABLE: ERROR"); return -EINVAL; } if(pContext->bEnabled == LVM_TRUE){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_ENABLE: ERROR-Effect is already enabled"); return -EINVAL; } *(int *)pReplyData = 0; pContext->bEnabled = LVM_TRUE; /* Get the current settings */ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE") pContext->SamplesToExitCount = (ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000; pContext->volumeMode = android::REVERB_VOLUME_FLAT; break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_DISABLE: ERROR"); return -EINVAL; } if(pContext->bEnabled == LVM_FALSE){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled"); return -EINVAL; } *(int *)pReplyData = 0; pContext->bEnabled = LVM_FALSE; break; case EFFECT_CMD_SET_VOLUME: if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_VOLUME: ERROR"); return -EINVAL; } if (pReplyData != NULL) { // we have volume control pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12); pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12); *(uint32_t *)pReplyData = (1 << 24); *((uint32_t *)pReplyData + 1) = (1 << 24); if (pContext->volumeMode == android::REVERB_VOLUME_OFF) { pContext->volumeMode = android::REVERB_VOLUME_FLAT; } } else { // we don't have volume control pContext->leftVolume = REVERB_UNIT_VOLUME; pContext->rightVolume = REVERB_UNIT_VOLUME; pContext->volumeMode = android::REVERB_VOLUME_OFF; } ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d", pContext->leftVolume, pContext->rightVolume, pContext->volumeMode); break; case EFFECT_CMD_SET_DEVICE: case EFFECT_CMD_SET_AUDIO_MODE: break; default: ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "DEFAULT start %d ERROR",cmdCode); return -EINVAL; } return 0; } /* end Reverb_command */ Commit Message: fix possible overflow in effect wrappers. Add checks on parameter size field in effect command handlers to avoid overflow leading to invalid comparison with min allowed size for command and reply buffers. Bug: 26347509. Change-Id: I20e6a9b6de8e5172b957caa1ac9410b9752efa4d (cherry picked from commit ad1bd92a49d78df6bc6e75bee68c517c1326f3cf) CWE ID: CWE-189
int Reverb_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData){ android::ReverbContext * pContext = (android::ReverbContext *) self; int retsize; LVREV_ControlParams_st ActiveParams; /* Current control Parameters */ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */ if (pContext == NULL){ ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL"); return -EINVAL; } switch (cmdCode){ case EFFECT_CMD_INIT: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_INIT: ERROR"); return -EINVAL; } *(int *) pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_CONFIG: ERROR"); return -EINVAL; } *(int *) pReplyData = android::Reverb_setConfig(pContext, (effect_config_t *) pCmdData); break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_GET_CONFIG: ERROR"); return -EINVAL; } android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: Reverb_setConfig(pContext, &pContext->config); break; case EFFECT_CMD_GET_PARAM:{ effect_param_t *p = (effect_param_t *)pCmdData; if (SIZE_MAX - sizeof(effect_param_t) < (size_t)p->psize) { android_errorWriteLog(0x534e4554, "26347509"); return -EINVAL; } if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) || cmdSize < (sizeof(effect_param_t) + p->psize) || pReplyData == NULL || replySize == NULL || *replySize < (sizeof(effect_param_t) + p->psize)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); p->status = android::Reverb_getParameter(pContext, (void *)p->data, (size_t *)&p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } break; case EFFECT_CMD_SET_PARAM:{ if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } *(int *)pReplyData = android::Reverb_setParameter(pContext, (void *)p->data, p->data + p->psize); } break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_ENABLE: ERROR"); return -EINVAL; } if(pContext->bEnabled == LVM_TRUE){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_ENABLE: ERROR-Effect is already enabled"); return -EINVAL; } *(int *)pReplyData = 0; pContext->bEnabled = LVM_TRUE; /* Get the current settings */ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE") pContext->SamplesToExitCount = (ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000; pContext->volumeMode = android::REVERB_VOLUME_FLAT; break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_DISABLE: ERROR"); return -EINVAL; } if(pContext->bEnabled == LVM_FALSE){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled"); return -EINVAL; } *(int *)pReplyData = 0; pContext->bEnabled = LVM_FALSE; break; case EFFECT_CMD_SET_VOLUME: if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_VOLUME: ERROR"); return -EINVAL; } if (pReplyData != NULL) { // we have volume control pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12); pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12); *(uint32_t *)pReplyData = (1 << 24); *((uint32_t *)pReplyData + 1) = (1 << 24); if (pContext->volumeMode == android::REVERB_VOLUME_OFF) { pContext->volumeMode = android::REVERB_VOLUME_FLAT; } } else { // we don't have volume control pContext->leftVolume = REVERB_UNIT_VOLUME; pContext->rightVolume = REVERB_UNIT_VOLUME; pContext->volumeMode = android::REVERB_VOLUME_OFF; } ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d", pContext->leftVolume, pContext->rightVolume, pContext->volumeMode); break; case EFFECT_CMD_SET_DEVICE: case EFFECT_CMD_SET_AUDIO_MODE: break; default: ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "DEFAULT start %d ERROR",cmdCode); return -EINVAL; } return 0; } /* end Reverb_command */
173,935
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, bool should_reuse_default_view, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } SecurityOrigin* previous_security_origin = nullptr; if (frame_->GetDocument()) previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); if (!should_reuse_default_view) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); bool user_gesture_bit_set = frame_->HasReceivedUserGesture() || frame_->HasReceivedUserGestureBeforeNavigation(); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithFrame(frame_) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext(), false); if (user_gesture_bit_set) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( ShouldPersistUserGestureValue(previous_security_origin, document->GetSecurityOrigin())); if (frame_->IsMainFrame()) frame_->ClearDocumentHasReceivedUserGesture(); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } frame_->GetPage()->GetChromeClient().InstallSupplements(*frame_); if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(); writer_ = DocumentWriter::Create(document, parsing_policy, mime_type, encoding); document->SetFeaturePolicy( RuntimeEnabledFeatures::FeaturePolicyExperimentalFeaturesEnabled() ? response_.HttpHeaderField(HTTPNames::Feature_Policy) : g_empty_string); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732
void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, bool should_reuse_default_view, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } SecurityOrigin* previous_security_origin = nullptr; if (frame_->GetDocument()) previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); if (!should_reuse_default_view) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); bool user_gesture_bit_set = frame_->HasReceivedUserGesture() || frame_->HasReceivedUserGestureBeforeNavigation(); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithFrame(frame_) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext(), false); if (user_gesture_bit_set) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( ShouldPersistUserGestureValue(previous_security_origin, document->GetSecurityOrigin())); if (frame_->IsMainFrame()) frame_->ClearDocumentHasReceivedUserGesture(); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } frame_->GetPage()->GetChromeClient().InstallSupplements(*frame_); if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document, reason); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(); writer_ = DocumentWriter::Create(document, parsing_policy, mime_type, encoding); document->SetFeaturePolicy( RuntimeEnabledFeatures::FeaturePolicyExperimentalFeaturesEnabled() ? response_.HttpHeaderField(HTTPNames::Feature_Policy) : g_empty_string); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); }
172,303
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Maybe<bool> CollectValuesOrEntriesImpl( Isolate* isolate, Handle<JSObject> object, Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items, PropertyFilter filter) { int count = 0; KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES); Subclass::CollectElementIndicesImpl( object, handle(object->elements(), isolate), &accumulator); Handle<FixedArray> keys = accumulator.GetKeys(); for (int i = 0; i < keys->length(); ++i) { Handle<Object> key(keys->get(i), isolate); Handle<Object> value; uint32_t index; if (!key->ToUint32(&index)) continue; uint32_t entry = Subclass::GetEntryForIndexImpl( isolate, *object, object->elements(), index, filter); if (entry == kMaxUInt32) continue; PropertyDetails details = Subclass::GetDetailsImpl(*object, entry); if (details.kind() == kData) { value = Subclass::GetImpl(isolate, object->elements(), entry); } else { LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(&it), Nothing<bool>()); } if (get_entries) { value = MakeEntryPair(isolate, index, value); } values_or_entries->set(count++, *value); } *nof_items = count; return Just(true); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704
static Maybe<bool> CollectValuesOrEntriesImpl( Isolate* isolate, Handle<JSObject> object, Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items, PropertyFilter filter) { DCHECK_EQ(*nof_items, 0); KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES); Subclass::CollectElementIndicesImpl( object, handle(object->elements(), isolate), &accumulator); Handle<FixedArray> keys = accumulator.GetKeys(); int count = 0; int i = 0; Handle<Map> original_map(object->map(), isolate); for (; i < keys->length(); ++i) { Handle<Object> key(keys->get(i), isolate); uint32_t index; if (!key->ToUint32(&index)) continue; DCHECK_EQ(object->map(), *original_map); uint32_t entry = Subclass::GetEntryForIndexImpl( isolate, *object, object->elements(), index, filter); if (entry == kMaxUInt32) continue; PropertyDetails details = Subclass::GetDetailsImpl(*object, entry); Handle<Object> value; if (details.kind() == kData) { value = Subclass::GetImpl(isolate, object->elements(), entry); } else { // This might modify the elements and/or change the elements kind. LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(&it), Nothing<bool>()); } if (get_entries) value = MakeEntryPair(isolate, index, value); values_or_entries->set(count++, *value); if (object->map() != *original_map) break; } // Slow path caused by changes in elements kind during iteration. for (; i < keys->length(); i++) { Handle<Object> key(keys->get(i), isolate); uint32_t index; if (!key->ToUint32(&index)) continue; if (filter & ONLY_ENUMERABLE) { InternalElementsAccessor* accessor = reinterpret_cast<InternalElementsAccessor*>( object->GetElementsAccessor()); uint32_t entry = accessor->GetEntryForIndex(isolate, *object, object->elements(), index); if (entry == kMaxUInt32) continue; PropertyDetails details = accessor->GetDetails(*object, entry); if (!details.IsEnumerable()) continue; } Handle<Object> value; LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, value, Object::GetProperty(&it), Nothing<bool>()); if (get_entries) value = MakeEntryPair(isolate, index, value); values_or_entries->set(count++, *value); } *nof_items = count; return Just(true); }
174,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b, *avail, nl); if (len >= 0) len += tested; } return (len); } Commit Message: Issue 747 (and others?): Avoid OOB read when parsing multiple long lines The mtree bidder needs to look several lines ahead in the input. It does this by extending the read-ahead and parsing subsequent lines from the same growing buffer. A bookkeeping error when extending the read-ahead would sometimes lead it to significantly over-count the size of the line being read. CWE ID: CWE-125
next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b + len, *avail - len, nl); if (len >= 0) len += tested; } return (len); }
168,765