instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int audit_log_single_execve_arg(struct audit_context *context, struct audit_buffer **ab, int arg_num, size_t *len_sent, const char __user *p, char *buf) { char arg_num_len_buf[12]; const char __user *tmp_p = p; /* how many digits are in arg_num? 5 is the length of ' a=""' */ size_t arg_num_len = snprintf(arg_num_len_buf, 12, "%d", arg_num) + 5; size_t len, len_left, to_send; size_t max_execve_audit_len = MAX_EXECVE_AUDIT_LEN; unsigned int i, has_cntl = 0, too_long = 0; int ret; /* strnlen_user includes the null we don't want to send */ len_left = len = strnlen_user(p, MAX_ARG_STRLEN) - 1; /* * We just created this mm, if we can't find the strings * we just copied into it something is _very_ wrong. Similar * for strings that are too long, we should not have created * any. */ if (WARN_ON_ONCE(len < 0 || len > MAX_ARG_STRLEN - 1)) { send_sig(SIGKILL, current, 0); return -1; } /* walk the whole argument looking for non-ascii chars */ do { if (len_left > MAX_EXECVE_AUDIT_LEN) to_send = MAX_EXECVE_AUDIT_LEN; else to_send = len_left; ret = copy_from_user(buf, tmp_p, to_send); /* * There is no reason for this copy to be short. We just * copied them here, and the mm hasn't been exposed to user- * space yet. */ if (ret) { WARN_ON(1); send_sig(SIGKILL, current, 0); return -1; } buf[to_send] = '\0'; has_cntl = audit_string_contains_control(buf, to_send); if (has_cntl) { /* * hex messages get logged as 2 bytes, so we can only * send half as much in each message */ max_execve_audit_len = MAX_EXECVE_AUDIT_LEN / 2; break; } len_left -= to_send; tmp_p += to_send; } while (len_left > 0); len_left = len; if (len > max_execve_audit_len) too_long = 1; /* rewalk the argument actually logging the message */ for (i = 0; len_left > 0; i++) { int room_left; if (len_left > max_execve_audit_len) to_send = max_execve_audit_len; else to_send = len_left; /* do we have space left to send this argument in this ab? */ room_left = MAX_EXECVE_AUDIT_LEN - arg_num_len - *len_sent; if (has_cntl) room_left -= (to_send * 2); else room_left -= to_send; if (room_left < 0) { *len_sent = 0; audit_log_end(*ab); *ab = audit_log_start(context, GFP_KERNEL, AUDIT_EXECVE); if (!*ab) return 0; } /* * first record needs to say how long the original string was * so we can be sure nothing was lost. */ if ((i == 0) && (too_long)) audit_log_format(*ab, " a%d_len=%zu", arg_num, has_cntl ? 2*len : len); /* * normally arguments are small enough to fit and we already * filled buf above when we checked for control characters * so don't bother with another copy_from_user */ if (len >= max_execve_audit_len) ret = copy_from_user(buf, p, to_send); else ret = 0; if (ret) { WARN_ON(1); send_sig(SIGKILL, current, 0); return -1; } buf[to_send] = '\0'; /* actually log it */ audit_log_format(*ab, " a%d", arg_num); if (too_long) audit_log_format(*ab, "[%d]", i); audit_log_format(*ab, "="); if (has_cntl) audit_log_n_hex(*ab, buf, to_send); else audit_log_string(*ab, buf); p += to_send; len_left -= to_send; *len_sent += arg_num_len; if (has_cntl) *len_sent += to_send * 2; else *len_sent += to_send; } /* include the null we didn't log */ return len + 1; } Commit Message: audit: fix a double fetch in audit_log_single_execve_arg() There is a double fetch problem in audit_log_single_execve_arg() where we first check the execve(2) argumnets for any "bad" characters which would require hex encoding and then re-fetch the arguments for logging in the audit record[1]. Of course this leaves a window of opportunity for an unsavory application to munge with the data. This patch reworks things by only fetching the argument data once[2] into a buffer where it is scanned and logged into the audit records(s). In addition to fixing the double fetch, this patch improves on the original code in a few other ways: better handling of large arguments which require encoding, stricter record length checking, and some performance improvements (completely unverified, but we got rid of some strlen() calls, that's got to be a good thing). As part of the development of this patch, I've also created a basic regression test for the audit-testsuite, the test can be tracked on GitHub at the following link: * https://github.com/linux-audit/audit-testsuite/issues/25 [1] If you pay careful attention, there is actually a triple fetch problem due to a strnlen_user() call at the top of the function. [2] This is a tiny white lie, we do make a call to strnlen_user() prior to fetching the argument data. I don't like it, but due to the way the audit record is structured we really have no choice unless we copy the entire argument at once (which would require a rather wasteful allocation). The good news is that with this patch the kernel no longer relies on this strnlen_user() value for anything beyond recording it in the log, we also update it with a trustworthy value whenever possible. Reported-by: Pengfei Wang <[email protected]> Cc: <[email protected]> Signed-off-by: Paul Moore <[email protected]> CWE ID: CWE-362
static int audit_log_single_execve_arg(struct audit_context *context, static void audit_log_execve_info(struct audit_context *context, struct audit_buffer **ab) { long len_max; long len_rem; long len_full; long len_buf; long len_abuf; long len_tmp; bool require_data; bool encode; unsigned int iter; unsigned int arg; char *buf_head; char *buf; const char __user *p = (const char __user *)current->mm->arg_start; /* NOTE: this buffer needs to be large enough to hold all the non-arg * data we put in the audit record for this argument (see the * code below) ... at this point in time 96 is plenty */ char abuf[96]; /* NOTE: we set MAX_EXECVE_AUDIT_LEN to a rather arbitrary limit, the * current value of 7500 is not as important as the fact that it * is less than 8k, a setting of 7500 gives us plenty of wiggle * room if we go over a little bit in the logging below */ WARN_ON_ONCE(MAX_EXECVE_AUDIT_LEN > 7500); len_max = MAX_EXECVE_AUDIT_LEN; /* scratch buffer to hold the userspace args */ buf_head = kmalloc(MAX_EXECVE_AUDIT_LEN + 1, GFP_KERNEL); if (!buf_head) { audit_panic("out of memory for argv string"); return; } buf = buf_head; audit_log_format(*ab, "argc=%d", context->execve.argc); len_rem = len_max; len_buf = 0; len_full = 0; require_data = true; encode = false; iter = 0; arg = 0; do { /* NOTE: we don't ever want to trust this value for anything * serious, but the audit record format insists we * provide an argument length for really long arguments, * e.g. > MAX_EXECVE_AUDIT_LEN, so we have no choice but * to use strncpy_from_user() to obtain this value for * recording in the log, although we don't use it * anywhere here to avoid a double-fetch problem */ if (len_full == 0) len_full = strnlen_user(p, MAX_ARG_STRLEN) - 1; /* read more data from userspace */ if (require_data) { /* can we make more room in the buffer? */ if (buf != buf_head) { memmove(buf_head, buf, len_buf); buf = buf_head; } /* fetch as much as we can of the argument */ len_tmp = strncpy_from_user(&buf_head[len_buf], p, len_max - len_buf); if (len_tmp == -EFAULT) { /* unable to copy from userspace */ send_sig(SIGKILL, current, 0); goto out; } else if (len_tmp == (len_max - len_buf)) { /* buffer is not large enough */ require_data = true; /* NOTE: if we are going to span multiple * buffers force the encoding so we stand * a chance at a sane len_full value and * consistent record encoding */ encode = true; len_full = len_full * 2; p += len_tmp; } else { require_data = false; if (!encode) encode = audit_string_contains_control( buf, len_tmp); /* try to use a trusted value for len_full */ if (len_full < len_max) len_full = (encode ? len_tmp * 2 : len_tmp); p += len_tmp + 1; } len_buf += len_tmp; buf_head[len_buf] = '\0'; /* length of the buffer in the audit record? */ len_abuf = (encode ? len_buf * 2 : len_buf + 2); }
167,019
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame) { const uint8_t* as_pack; int freq, stype, smpls, quant, i, ach; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack || !c->sys) { /* No audio ? */ c->ach = 0; return 0; } smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ /* note: ach counts PAIRS of channels (i.e. stereo channels) */ ach = ((int[4]){ 1, 0, 2, 4})[stype]; if (ach == 1 && quant && freq == 2) if (!c->ast[i]) break; avpriv_set_pts_info(c->ast[i], 64, 1, 30000); c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO; c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE; av_init_packet(&c->audio_pkt[i]); c->audio_pkt[i].size = 0; c->audio_pkt[i].data = c->audio_buf[i]; c->audio_pkt[i].stream_index = c->ast[i]->index; c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY; } Commit Message: CWE ID: CWE-20
static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame) { const uint8_t* as_pack; int freq, stype, smpls, quant, i, ach; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack || !c->sys) { /* No audio ? */ c->ach = 0; return 0; } smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (stype > 3) { av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype); c->ach = 0; return 0; } /* note: ach counts PAIRS of channels (i.e. stereo channels) */ ach = ((int[4]){ 1, 0, 2, 4})[stype]; if (ach == 1 && quant && freq == 2) if (!c->ast[i]) break; avpriv_set_pts_info(c->ast[i], 64, 1, 30000); c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO; c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE; av_init_packet(&c->audio_pkt[i]); c->audio_pkt[i].size = 0; c->audio_pkt[i].data = c->audio_buf[i]; c->audio_pkt[i].stream_index = c->ast[i]->index; c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY; }
165,243
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: g_NPN_GetValue(NPP instance, NPNVariable variable, void *value) { D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable))); if (!thread_check()) { npw_printf("WARNING: NPN_GetValue not called from the main thread\n"); return NPERR_INVALID_INSTANCE_ERROR; } PluginInstance *plugin = NULL; if (instance) plugin = PLUGIN_INSTANCE(instance); switch (variable) { case NPNVxDisplay: *(void **)value = x_display; break; case NPNVxtAppContext: *(void **)value = XtDisplayToApplicationContext(x_display); break; case NPNVToolkit: *(NPNToolkitType *)value = NPW_TOOLKIT; break; #if USE_XPCOM case NPNVserviceManager: { nsIServiceManager *sm; int ret = NS_GetServiceManager(&sm); if (NS_FAILED(ret)) { npw_printf("WARNING: NS_GetServiceManager failed\n"); return NPERR_GENERIC_ERROR; } *(nsIServiceManager **)value = sm; break; } case NPNVDOMWindow: case NPNVDOMElement: npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable)); return NPERR_INVALID_PARAM; #endif case NPNVnetscapeWindow: if (plugin == NULL) { npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n"); return NPERR_INVALID_INSTANCE_ERROR; } if (plugin->browser_toplevel == NULL) { GdkNativeWindow netscape_xid = None; NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid); if (error != NPERR_NO_ERROR) return error; if (netscape_xid == None) return NPERR_GENERIC_ERROR; plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid); if (plugin->browser_toplevel == NULL) return NPERR_GENERIC_ERROR; } *((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel); break; #if ALLOW_WINDOWLESS_PLUGINS case NPNVSupportsWindowless: #endif case NPNVSupportsXEmbedBool: case NPNVWindowNPObject: case NPNVPluginElementNPObject: return g_NPN_GetValue_real(instance, variable, value); default: switch (variable & 0xff) { case 13: /* NPNVToolkit */ if (NPW_TOOLKIT == NPNVGtk2) { *(NPNToolkitType *)value = NPW_TOOLKIT; return NPERR_NO_ERROR; } break; } D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable))); return NPERR_INVALID_PARAM; } return NPERR_NO_ERROR; } Commit Message: Support all the new variables added CWE ID: CWE-264
g_NPN_GetValue(NPP instance, NPNVariable variable, void *value) { D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable))); if (!thread_check()) { npw_printf("WARNING: NPN_GetValue not called from the main thread\n"); return NPERR_INVALID_INSTANCE_ERROR; } PluginInstance *plugin = NULL; if (instance) plugin = PLUGIN_INSTANCE(instance); switch (variable) { case NPNVxDisplay: *(void **)value = x_display; break; case NPNVxtAppContext: *(void **)value = XtDisplayToApplicationContext(x_display); break; case NPNVToolkit: *(NPNToolkitType *)value = NPW_TOOLKIT; break; #if USE_XPCOM case NPNVserviceManager: { nsIServiceManager *sm; int ret = NS_GetServiceManager(&sm); if (NS_FAILED(ret)) { npw_printf("WARNING: NS_GetServiceManager failed\n"); return NPERR_GENERIC_ERROR; } *(nsIServiceManager **)value = sm; break; } case NPNVDOMWindow: case NPNVDOMElement: npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable)); return NPERR_INVALID_PARAM; #endif case NPNVnetscapeWindow: if (plugin == NULL) { npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n"); return NPERR_INVALID_INSTANCE_ERROR; } if (plugin->browser_toplevel == NULL) { GdkNativeWindow netscape_xid = None; NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid); if (error != NPERR_NO_ERROR) return error; if (netscape_xid == None) return NPERR_GENERIC_ERROR; plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid); if (plugin->browser_toplevel == NULL) return NPERR_GENERIC_ERROR; } *((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel); break; #if ALLOW_WINDOWLESS_PLUGINS case NPNVSupportsWindowless: #endif case NPNVSupportsXEmbedBool: case NPNVWindowNPObject: case NPNVPluginElementNPObject: case NPNVprivateModeBool: case NPNVsupportsAdvancedKeyHandling: return g_NPN_GetValue_real(instance, variable, value); default: switch (variable & 0xff) { case 13: /* NPNVToolkit */ if (NPW_TOOLKIT == NPNVGtk2) { *(NPNToolkitType *)value = NPW_TOOLKIT; return NPERR_NO_ERROR; } break; } D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable))); return NPERR_INVALID_PARAM; } return NPERR_NO_ERROR; }
165,864
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool CrossesExtensionProcessBoundary( const ExtensionSet& extensions, const GURL& old_url, const GURL& new_url, bool should_consider_workaround) { const extensions::Extension* old_url_extension = GetNonBookmarkAppExtension( extensions, old_url); const extensions::Extension* new_url_extension = GetNonBookmarkAppExtension( extensions, new_url); if (should_consider_workaround) { bool old_url_is_hosted_app = old_url_extension && !old_url_extension->web_extent().is_empty() && !AppIsolationInfo::HasIsolatedStorage(old_url_extension); bool new_url_is_normal_or_hosted = !new_url_extension || (!new_url_extension->web_extent().is_empty() && !AppIsolationInfo::HasIsolatedStorage(new_url_extension)); bool either_is_web_store = (old_url_extension && old_url_extension->id() == extensions::kWebStoreAppId) || (new_url_extension && new_url_extension->id() == extensions::kWebStoreAppId); if (old_url_is_hosted_app && new_url_is_normal_or_hosted && !either_is_web_store) return false; } return old_url_extension != new_url_extension; } Commit Message: [Extensions] Update navigations across hypothetical extension extents Update code to treat navigations across hypothetical extension extents (e.g. for nonexistent extensions) the same as we do for navigations crossing installed extension extents. Bug: 598265 Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b Reviewed-on: https://chromium-review.googlesource.com/617180 Commit-Queue: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#495779} CWE ID:
bool CrossesExtensionProcessBoundary( const ExtensionSet& extensions, const GURL& old_url, const GURL& new_url, bool should_consider_workaround) { const extensions::Extension* old_url_extension = GetNonBookmarkAppExtension( extensions, old_url); const extensions::Extension* new_url_extension = GetNonBookmarkAppExtension( extensions, new_url); if (should_consider_workaround) { bool old_url_is_hosted_app = old_url_extension && !old_url_extension->web_extent().is_empty() && !AppIsolationInfo::HasIsolatedStorage(old_url_extension); bool new_url_is_normal_or_hosted = !new_url_extension || (!new_url_extension->web_extent().is_empty() && !AppIsolationInfo::HasIsolatedStorage(new_url_extension)); bool either_is_web_store = (old_url_extension && old_url_extension->id() == extensions::kWebStoreAppId) || (new_url_extension && new_url_extension->id() == extensions::kWebStoreAppId); if (old_url_is_hosted_app && new_url_is_normal_or_hosted && !either_is_web_store) return false; } // If there are no extensions associated with either url, we check if the new // url points to an extension origin. If it does, fork - extension // installation should not be a factor. if (!old_url_extension && !new_url_extension) { // Hypothetically, we could also do an origin check here to make sure that // the two urls point two different extensions, but it's not really // necesary since we know there wasn't an associated extension with the old // url. return new_url.SchemeIs(kExtensionScheme); } return old_url_extension != new_url_extension; }
172,959
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ComponentControllerImpl::ComponentControllerImpl(WebContentRunner* runner) : runner_(runner), controller_binding_(this), frame_observer_binding_(this) { DCHECK(runner); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
ComponentControllerImpl::ComponentControllerImpl(WebContentRunner* runner) : runner_(runner), controller_binding_(this) { DCHECK(runner); }
172,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void * calloc(size_t n, size_t lb) { if (lb && n > GC_SIZE_MAX / lb) return NULL; # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); } Commit Message: Speedup calloc size overflow check by preventing division if small values * malloc.c (GC_SQRT_SIZE_MAX): New macro. * malloc.c (calloc): Add fast initial size overflow check to avoid integer division for reasonably small values passed. CWE ID: CWE-189
void * calloc(size_t n, size_t lb) { if ((lb | n) > GC_SQRT_SIZE_MAX /* fast initial test */ && lb && n > GC_SIZE_MAX / lb) return NULL; # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); }
169,881
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; if (ps_stream->u4_offset < ps_stream->u4_max_offset) { FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) } return; } Commit Message: Fixed out of bound read in flush_bits Bug: 28168413 Change-Id: I3db5432a08daf665e160c0dab2d1928a576418b4 CWE ID: CWE-200
INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; if ((ps_stream->u4_offset + 64) < ps_stream->u4_max_offset) { FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) } else { UWORD32 u4_temp; if (((ps_stream->u4_offset & 0x1f) + u4_no_of_bits) >= 32) { ps_stream->u4_buf = ps_stream->u4_buf_nxt; ps_stream->u4_buf_nxt = 0; } ps_stream->u4_offset += u4_no_of_bits; } return; }
173,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data) { memset(task, 0, sizeof(*task)); atomic_set(&task->tk_count, 1); task->tk_flags = task_setup_data->flags; task->tk_ops = task_setup_data->callback_ops; task->tk_calldata = task_setup_data->callback_data; INIT_LIST_HEAD(&task->tk_task); /* Initialize retry counters */ task->tk_garb_retry = 2; task->tk_cred_retry = 2; task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW; task->tk_owner = current->tgid; /* Initialize workqueue for async tasks */ task->tk_workqueue = task_setup_data->workqueue; if (task->tk_ops->rpc_call_prepare != NULL) task->tk_action = rpc_prepare_task; /* starting timestamp */ task->tk_start = ktime_get(); dprintk("RPC: new task initialized, procpid %u\n", task_pid_nr(current)); } Commit Message: NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> Cc: [email protected] CWE ID: CWE-399
static void rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data) { memset(task, 0, sizeof(*task)); atomic_set(&task->tk_count, 1); task->tk_flags = task_setup_data->flags; task->tk_ops = task_setup_data->callback_ops; task->tk_calldata = task_setup_data->callback_data; INIT_LIST_HEAD(&task->tk_task); /* Initialize retry counters */ task->tk_garb_retry = 2; task->tk_cred_retry = 2; task->tk_rebind_retry = 2; task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW; task->tk_owner = current->tgid; /* Initialize workqueue for async tasks */ task->tk_workqueue = task_setup_data->workqueue; if (task->tk_ops->rpc_call_prepare != NULL) task->tk_action = rpc_prepare_task; /* starting timestamp */ task->tk_start = ktime_get(); dprintk("RPC: new task initialized, procpid %u\n", task_pid_nr(current)); }
166,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long AudioTrack::Parse(Segment* pSegment, const Info& info, long long element_start, long long element_size, AudioTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kAudio) return -1; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; double rate = 8000.0; // MKV default long long channels = 1; long long bit_depth = 0; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x35) { // Sample Rate status = UnserializeFloat(pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x1F) { // Channel Count channels = UnserializeUInt(pReader, pos, size); if (channels <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x2264) { // Bit Depth bit_depth = UnserializeUInt(pReader, pos, size); if (bit_depth <= 0) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); AudioTrack* const pTrack = new (std::nothrow) AudioTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; // generic error const int status = info.Copy(pTrack->m_info); if (status) { delete pTrack; return status; } pTrack->m_rate = rate; pTrack->m_channels = channels; pTrack->m_bitDepth = bit_depth; pResult = pTrack; return 0; // success } 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
long AudioTrack::Parse(Segment* pSegment, const Info& info, long long element_start, long long element_size, AudioTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kAudio) return -1; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; double rate = 8000.0; // MKV default long long channels = 1; long long bit_depth = 0; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x35) { // Sample Rate status = UnserializeFloat(pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x1F) { // Channel Count channels = UnserializeUInt(pReader, pos, size); if (channels <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x2264) { // Bit Depth bit_depth = UnserializeUInt(pReader, pos, size); if (bit_depth <= 0) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; AudioTrack* const pTrack = new (std::nothrow) AudioTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; // generic error const int status = info.Copy(pTrack->m_info); if (status) { delete pTrack; return status; } pTrack->m_rate = rate; pTrack->m_channels = channels; pTrack->m_bitDepth = bit_depth; pResult = pTrack; return 0; // success }
173,844
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SetupConnectedStreams() { CallbackRunLoop run_loop(runner()); ASSERT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished()); ASSERT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished()); client_peer_->CreateStreamWithDelegate(); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); base::RepeatingCallback<void()> callback = run_loop.CreateCallback(); QuicPeerForTest* server_peer_ptr = server_peer_.get(); MockP2PQuicStreamDelegate* stream_delegate = new MockP2PQuicStreamDelegate(); P2PQuicStream* server_stream; EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnStream(_)) .WillOnce(Invoke([&callback, &server_stream, &stream_delegate](P2PQuicStream* stream) { stream->SetDelegate(stream_delegate); server_stream = stream; callback.Run(); })); client_peer_->stream()->WriteOrBufferData(kTriggerRemoteStreamPhrase, /*fin=*/false, nullptr); run_loop.RunUntilCallbacksFired(); server_peer_ptr->SetStreamAndDelegate( static_cast<P2PQuicStreamImpl*>(server_stream), std::unique_ptr<MockP2PQuicStreamDelegate>(stream_delegate)); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void SetupConnectedStreams() { CallbackRunLoop run_loop(runner()); ASSERT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished()); ASSERT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished()); client_peer_->CreateStreamWithDelegate(); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); base::RepeatingCallback<void()> callback = run_loop.CreateCallback(); QuicPeerForTest* server_peer_ptr = server_peer_.get(); MockP2PQuicStreamDelegate* stream_delegate = new MockP2PQuicStreamDelegate(); P2PQuicStream* server_stream; EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnStream(_)) .WillOnce(Invoke([&callback, &server_stream, &stream_delegate](P2PQuicStream* stream) { stream->SetDelegate(stream_delegate); server_stream = stream; callback.Run(); })); client_peer_->stream()->WriteData( std::vector<uint8_t>(kTriggerRemoteStreamPhrase.begin(), kTriggerRemoteStreamPhrase.end()), /*fin=*/false); run_loop.RunUntilCallbacksFired(); server_peer_ptr->SetStreamAndDelegate( static_cast<P2PQuicStreamImpl*>(server_stream), std::unique_ptr<MockP2PQuicStreamDelegate>(stream_delegate)); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); }
172,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebsiteSettings* website_settings() { if (!website_settings_.get()) { website_settings_.reset(new WebsiteSettings( mock_ui(), profile(), tab_specific_content_settings(), infobar_service(), url(), ssl(), cert_store())); } return website_settings_.get(); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
WebsiteSettings* website_settings() { if (!website_settings_.get()) { website_settings_.reset(new WebsiteSettings( mock_ui(), profile(), tab_specific_content_settings(), web_contents(), url(), ssl(), cert_store())); } return website_settings_.get(); }
171,782
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Handle<v8::Value> V8WebSocket::sendCallback(const v8::Arguments& args) { INC_STATS("DOM.WebSocket.send()"); if (!args.Length()) return V8Proxy::throwNotEnoughArgumentsError(); WebSocket* webSocket = V8WebSocket::toNative(args.Holder()); v8::Handle<v8::Value> message = args[0]; ExceptionCode ec = 0; bool result; if (V8ArrayBuffer::HasInstance(message)) { ArrayBuffer* arrayBuffer = V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(message)); ASSERT(arrayBuffer); result = webSocket->send(arrayBuffer, ec); } else if (V8Blob::HasInstance(message)) { Blob* blob = V8Blob::toNative(v8::Handle<v8::Object>::Cast(message)); ASSERT(blob); result = webSocket->send(blob, ec); } else { v8::TryCatch tryCatch; v8::Handle<v8::String> stringMessage = message->ToString(); if (tryCatch.HasCaught()) return throwError(tryCatch.Exception(), args.GetIsolate()); result = webSocket->send(toWebCoreString(stringMessage), ec); } if (ec) return throwError(ec, args.GetIsolate()); return v8Boolean(result); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
v8::Handle<v8::Value> V8WebSocket::sendCallback(const v8::Arguments& args) { INC_STATS("DOM.WebSocket.send()"); if (!args.Length()) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); WebSocket* webSocket = V8WebSocket::toNative(args.Holder()); v8::Handle<v8::Value> message = args[0]; ExceptionCode ec = 0; bool result; if (V8ArrayBuffer::HasInstance(message)) { ArrayBuffer* arrayBuffer = V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(message)); ASSERT(arrayBuffer); result = webSocket->send(arrayBuffer, ec); } else if (V8Blob::HasInstance(message)) { Blob* blob = V8Blob::toNative(v8::Handle<v8::Object>::Cast(message)); ASSERT(blob); result = webSocket->send(blob, ec); } else { v8::TryCatch tryCatch; v8::Handle<v8::String> stringMessage = message->ToString(); if (tryCatch.HasCaught()) return throwError(tryCatch.Exception(), args.GetIsolate()); result = webSocket->send(toWebCoreString(stringMessage), ec); } if (ec) return throwError(ec, args.GetIsolate()); return v8Boolean(result); }
171,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AsyncPixelTransfersCompletedQuery::End( base::subtle::Atomic32 submit_count) { AsyncMemoryParams mem_params; Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id()); if (!buffer.shared_memory) return false; mem_params.shared_memory = buffer.shared_memory; mem_params.shm_size = buffer.size; mem_params.shm_data_offset = shm_offset(); mem_params.shm_data_size = sizeof(QuerySync); observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count); manager()->decoder()->GetAsyncPixelTransferManager() ->AsyncNotifyCompletion(mem_params, observer_); return AddToPendingTransferQueue(submit_count); } Commit Message: Add bounds validation to AsyncPixelTransfersCompletedQuery::End BUG=351852 [email protected], [email protected] Review URL: https://codereview.chromium.org/198253002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@256723 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool AsyncPixelTransfersCompletedQuery::End( base::subtle::Atomic32 submit_count) { AsyncMemoryParams mem_params; Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id()); if (!buffer.shared_memory) return false; mem_params.shared_memory = buffer.shared_memory; mem_params.shm_size = buffer.size; mem_params.shm_data_offset = shm_offset(); mem_params.shm_data_size = sizeof(QuerySync); uint32 end = mem_params.shm_data_offset + mem_params.shm_data_size; if (end > mem_params.shm_size || end < mem_params.shm_data_offset) return false; observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count); manager()->decoder()->GetAsyncPixelTransferManager() ->AsyncNotifyCompletion(mem_params, observer_); return AddToPendingTransferQueue(submit_count); }
171,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t alphaBits, x, y; unsigned short color; alphaBits=0; if (dds_info->pixelformat.rgb_bitcount == 16) { if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000)) alphaBits=1; else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00)) { alphaBits=2; (void) SetImageType(image,GrayscaleMatteType); } else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000)) alphaBits=4; else ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); } for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); if (alphaBits == 1) { SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 1) >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 6) >> 11)/31.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else if (alphaBits == 2) { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (color >> 8))); SetPixelGray(q,ScaleCharToQuantum((unsigned char)color)); } else { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (((color >> 12)/15.0)*255))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 4) >> 12)/15.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 8) >> 12)/15.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 12) >> 12)/15.0)*255))); } } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } SkipRGBMipmaps(image, dds_info, 4); return MagickTrue; } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t alphaBits, x, y; unsigned short color; alphaBits=0; if (dds_info->pixelformat.rgb_bitcount == 16) { if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000)) alphaBits=1; else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00)) { alphaBits=2; (void) SetImageType(image,GrayscaleMatteType); } else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000)) alphaBits=4; else ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); } for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); if (alphaBits == 1) { SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 1) >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 6) >> 11)/31.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else if (alphaBits == 2) { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (color >> 8))); SetPixelGray(q,ScaleCharToQuantum((unsigned char)color)); } else { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (((color >> 12)/15.0)*255))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 4) >> 12)/15.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 8) >> 12)/15.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 12) >> 12)/15.0)*255))); } } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } return(SkipRGBMipmaps(image,dds_info,4,exception)); }
168,903
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int UDPSocketWin::InternalConnect(const IPEndPoint& address) { DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; rv = connect(socket_, storage.addr, storage.addr_len); if (rv < 0) { int result = MapSystemError(WSAGetLastError()); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; } Commit Message: Map posix error codes in bind better, and fix one windows mapping. r=wtc BUG=330233 Review URL: https://codereview.chromium.org/101193008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
int UDPSocketWin::InternalConnect(const IPEndPoint& address) { DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", -rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; rv = connect(socket_, storage.addr, storage.addr_len); if (rv < 0) { int result = MapSystemError(WSAGetLastError()); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; }
171,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfsd_dispatch(struct svc_rqst *rqstp, __be32 *statp) { struct svc_procedure *proc; kxdrproc_t xdr; __be32 nfserr; __be32 *nfserrp; dprintk("nfsd_dispatch: vers %d proc %d\n", rqstp->rq_vers, rqstp->rq_proc); proc = rqstp->rq_procinfo; /* * Give the xdr decoder a chance to change this if it wants * (necessary in the NFSv4.0 compound case) */ rqstp->rq_cachetype = proc->pc_cachetype; /* Decode arguments */ xdr = proc->pc_decode; if (xdr && !xdr(rqstp, (__be32*)rqstp->rq_arg.head[0].iov_base, rqstp->rq_argp)) { dprintk("nfsd: failed to decode arguments!\n"); *statp = rpc_garbage_args; return 1; } /* Check whether we have this call in the cache. */ switch (nfsd_cache_lookup(rqstp)) { case RC_DROPIT: return 0; case RC_REPLY: return 1; case RC_DOIT:; /* do it */ } /* need to grab the location to store the status, as * nfsv4 does some encoding while processing */ nfserrp = rqstp->rq_res.head[0].iov_base + rqstp->rq_res.head[0].iov_len; rqstp->rq_res.head[0].iov_len += sizeof(__be32); /* Now call the procedure handler, and encode NFS status. */ nfserr = proc->pc_func(rqstp, rqstp->rq_argp, rqstp->rq_resp); nfserr = map_new_errors(rqstp->rq_vers, nfserr); if (nfserr == nfserr_dropit || test_bit(RQ_DROPME, &rqstp->rq_flags)) { dprintk("nfsd: Dropping request; may be revisited later\n"); nfsd_cache_update(rqstp, RC_NOCACHE, NULL); return 0; } if (rqstp->rq_proc != 0) *nfserrp++ = nfserr; /* Encode result. * For NFSv2, additional info is never returned in case of an error. */ if (!(nfserr && rqstp->rq_vers == 2)) { xdr = proc->pc_encode; if (xdr && !xdr(rqstp, nfserrp, rqstp->rq_resp)) { /* Failed to encode result. Release cache entry */ dprintk("nfsd: failed to encode result!\n"); nfsd_cache_update(rqstp, RC_NOCACHE, NULL); *statp = rpc_system_err; return 1; } } /* Store reply in cache. */ nfsd_cache_update(rqstp, rqstp->rq_cachetype, statp + 1); return 1; } Commit Message: nfsd: check for oversized NFSv2/v3 arguments A client can append random data to the end of an NFSv2 or NFSv3 RPC call without our complaining; we'll just stop parsing at the end of the expected data and ignore the rest. Encoded arguments and replies are stored together in an array of pages, and if a call is too large it could leave inadequate space for the reply. This is normally OK because NFS RPC's typically have either short arguments and long replies (like READ) or long arguments and short replies (like WRITE). But a client that sends an incorrectly long reply can violate those assumptions. This was observed to cause crashes. Also, several operations increment rq_next_page in the decode routine before checking the argument size, which can leave rq_next_page pointing well past the end of the page array, causing trouble later in svc_free_pages. So, following a suggestion from Neil Brown, add a central check to enforce our expectation that no NFSv2/v3 call has both a large call and a large reply. As followup we may also want to rewrite the encoding routines to check more carefully that they aren't running off the end of the page array. We may also consider rejecting calls that have any extra garbage appended. That would be safer, and within our rights by spec, but given the age of our server and the NFS protocol, and the fact that we've never enforced this before, we may need to balance that against the possibility of breaking some oddball client. Reported-by: Tuomas Haanpää <[email protected]> Reported-by: Ari Kauppi <[email protected]> Cc: [email protected] Reviewed-by: NeilBrown <[email protected]> Signed-off-by: J. Bruce Fields <[email protected]> CWE ID: CWE-20
nfsd_dispatch(struct svc_rqst *rqstp, __be32 *statp) { struct svc_procedure *proc; kxdrproc_t xdr; __be32 nfserr; __be32 *nfserrp; dprintk("nfsd_dispatch: vers %d proc %d\n", rqstp->rq_vers, rqstp->rq_proc); proc = rqstp->rq_procinfo; if (nfs_request_too_big(rqstp, proc)) { dprintk("nfsd: NFSv%d argument too large\n", rqstp->rq_vers); *statp = rpc_garbage_args; return 1; } /* * Give the xdr decoder a chance to change this if it wants * (necessary in the NFSv4.0 compound case) */ rqstp->rq_cachetype = proc->pc_cachetype; /* Decode arguments */ xdr = proc->pc_decode; if (xdr && !xdr(rqstp, (__be32*)rqstp->rq_arg.head[0].iov_base, rqstp->rq_argp)) { dprintk("nfsd: failed to decode arguments!\n"); *statp = rpc_garbage_args; return 1; } /* Check whether we have this call in the cache. */ switch (nfsd_cache_lookup(rqstp)) { case RC_DROPIT: return 0; case RC_REPLY: return 1; case RC_DOIT:; /* do it */ } /* need to grab the location to store the status, as * nfsv4 does some encoding while processing */ nfserrp = rqstp->rq_res.head[0].iov_base + rqstp->rq_res.head[0].iov_len; rqstp->rq_res.head[0].iov_len += sizeof(__be32); /* Now call the procedure handler, and encode NFS status. */ nfserr = proc->pc_func(rqstp, rqstp->rq_argp, rqstp->rq_resp); nfserr = map_new_errors(rqstp->rq_vers, nfserr); if (nfserr == nfserr_dropit || test_bit(RQ_DROPME, &rqstp->rq_flags)) { dprintk("nfsd: Dropping request; may be revisited later\n"); nfsd_cache_update(rqstp, RC_NOCACHE, NULL); return 0; } if (rqstp->rq_proc != 0) *nfserrp++ = nfserr; /* Encode result. * For NFSv2, additional info is never returned in case of an error. */ if (!(nfserr && rqstp->rq_vers == 2)) { xdr = proc->pc_encode; if (xdr && !xdr(rqstp, nfserrp, rqstp->rq_resp)) { /* Failed to encode result. Release cache entry */ dprintk("nfsd: failed to encode result!\n"); nfsd_cache_update(rqstp, RC_NOCACHE, NULL); *statp = rpc_system_err; return 1; } } /* Store reply in cache. */ nfsd_cache_update(rqstp, rqstp->rq_cachetype, statp + 1); return 1; }
168,256
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception) { char format[MaxTextExtent], keyword[MaxTextExtent], tag[MaxTextExtent], value[MaxTextExtent]; double gamma; Image *image; int c; MagickBooleanType status, value_expected; register PixelPacket *q; register unsigned char *p; register ssize_t i, x; ssize_t count, y; unsigned char *end, pixel[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ image->columns=0; image->rows=0; *format='\0'; c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } while (isgraph(c) && (image->columns == 0) && (image->rows == 0)) { if (c == (int) '#') { char *comment; register char *p; size_t length; /* Read comment-- any text between # and end-of-line. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '\n')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) == MagickFalse) c=ReadBlobByte(image); else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); } if (LocaleCompare(keyword,"Y") == 0) value_expected=MagickTrue; if (value_expected == MagickFalse) continue; p=value; while ((c != '\n') && (c != '\0')) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"format") == 0) { (void) CopyMagickString(format,value,MaxTextExtent); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(value,(char **) NULL); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"primaries") == 0) { float chromaticity[6], white_point[2]; (void) sscanf(value,"%g %g %g %g %g %g %g %g", &chromaticity[0],&chromaticity[1],&chromaticity[2], &chromaticity[3],&chromaticity[4],&chromaticity[5], &white_point[0],&white_point[1]); image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; image->chromaticity.white_point.x=white_point[0], image->chromaticity.white_point.y=white_point[1]; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } case 'Y': case 'y': { if (strcmp(keyword,"Y") == 0) { int height, width; (void) sscanf(value,"%d +X %d",&height,&width); image->columns=(size_t) width; image->rows=(size_t) height; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } default: { (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } } } if ((image->columns == 0) && (image->rows == 0)) while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) && (LocaleCompare(format,"32-bit_rle_xyze") != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) SetImageColorspace(image,RGBColorspace); if (LocaleCompare(format,"32-bit_rle_xyze") == 0) (void) SetImageColorspace(image,XYZColorspace); image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ? NoCompression : RLECompression; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read RGBE (red+green+blue+exponent) pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { if (image->compression != RLECompression) { count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } else { count=ReadBlob(image,4*sizeof(*pixel),pixel); if (count != 4) break; if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns) { (void) memcpy(pixels,pixel,4*sizeof(*pixel)); count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4); image->compression=NoCompression; } else { p=pixels; for (i=0; i < 4; i++) { end=&pixels[(i+1)*image->columns]; while (p < end) { count=ReadBlob(image,2*sizeof(*pixel),pixel); if (count < 1) break; if (pixel[0] > 128) { count=(ssize_t) pixel[0]-128; if ((count == 0) || (count > (ssize_t) (end-p))) break; while (count-- > 0) *p++=pixel[1]; } else { count=(ssize_t) pixel[0]; if ((count == 0) || (count > (ssize_t) (end-p))) break; *p++=pixel[1]; if (--count > 0) { count=ReadBlob(image,(size_t) count*sizeof(*p),p); if (count < 1) break; p+=count; } } } } } } q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; i=0; for (x=0; x < (ssize_t) image->columns; x++) { if (image->compression == RLECompression) { pixel[0]=pixels[x]; pixel[1]=pixels[x+image->columns]; pixel[2]=pixels[x+2*image->columns]; pixel[3]=pixels[x+3*image->columns]; } else { pixel[0]=pixels[i++]; pixel[1]=pixels[i++]; pixel[2]=pixels[i++]; pixel[3]=pixels[i++]; } SetPixelRed(q,0); SetPixelGreen(q,0); SetPixelBlue(q,0); if (pixel[3] != 0) { gamma=pow(2.0,pixel[3]-(128.0+8.0)); SetPixelRed(q,ClampToQuantum(QuantumRange*gamma*pixel[0])); SetPixelGreen(q,ClampToQuantum(QuantumRange*gamma*pixel[1])); SetPixelBlue(q,ClampToQuantum(QuantumRange*gamma*pixel[2])); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception) { char format[MaxTextExtent], keyword[MaxTextExtent], tag[MaxTextExtent], value[MaxTextExtent]; double gamma; Image *image; int c; MagickBooleanType status, value_expected; register PixelPacket *q; register unsigned char *p; register ssize_t i, x; ssize_t count, y; unsigned char *end, pixel[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ image->columns=0; image->rows=0; *format='\0'; c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } while (isgraph(c) && (image->columns == 0) && (image->rows == 0)) { if (c == (int) '#') { char *comment; register char *p; size_t length; /* Read comment-- any text between # and end-of-line. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '\n')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) == MagickFalse) c=ReadBlobByte(image); else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); } if (LocaleCompare(keyword,"Y") == 0) value_expected=MagickTrue; if (value_expected == MagickFalse) continue; p=value; while ((c != '\n') && (c != '\0')) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"format") == 0) { (void) CopyMagickString(format,value,MaxTextExtent); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(value,(char **) NULL); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"primaries") == 0) { float chromaticity[6], white_point[2]; (void) sscanf(value,"%g %g %g %g %g %g %g %g", &chromaticity[0],&chromaticity[1],&chromaticity[2], &chromaticity[3],&chromaticity[4],&chromaticity[5], &white_point[0],&white_point[1]); image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; image->chromaticity.white_point.x=white_point[0], image->chromaticity.white_point.y=white_point[1]; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } case 'Y': case 'y': { if (strcmp(keyword,"Y") == 0) { int height, width; (void) sscanf(value,"%d +X %d",&height,&width); image->columns=(size_t) width; image->rows=(size_t) height; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } default: { (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value); break; } } } if ((image->columns == 0) && (image->rows == 0)) while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) && (LocaleCompare(format,"32-bit_rle_xyze") != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) SetImageColorspace(image,RGBColorspace); if (LocaleCompare(format,"32-bit_rle_xyze") == 0) (void) SetImageColorspace(image,XYZColorspace); image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ? NoCompression : RLECompression; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Read RGBE (red+green+blue+exponent) pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { if (image->compression != RLECompression) { count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } else { count=ReadBlob(image,4*sizeof(*pixel),pixel); if (count != 4) break; if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns) { (void) memcpy(pixels,pixel,4*sizeof(*pixel)); count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4); image->compression=NoCompression; } else { p=pixels; for (i=0; i < 4; i++) { end=&pixels[(i+1)*image->columns]; while (p < end) { count=ReadBlob(image,2*sizeof(*pixel),pixel); if (count < 1) break; if (pixel[0] > 128) { count=(ssize_t) pixel[0]-128; if ((count == 0) || (count > (ssize_t) (end-p))) break; while (count-- > 0) *p++=pixel[1]; } else { count=(ssize_t) pixel[0]; if ((count == 0) || (count > (ssize_t) (end-p))) break; *p++=pixel[1]; if (--count > 0) { count=ReadBlob(image,(size_t) count*sizeof(*p),p); if (count < 1) break; p+=count; } } } } } } q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; i=0; for (x=0; x < (ssize_t) image->columns; x++) { if (image->compression == RLECompression) { pixel[0]=pixels[x]; pixel[1]=pixels[x+image->columns]; pixel[2]=pixels[x+2*image->columns]; pixel[3]=pixels[x+3*image->columns]; } else { pixel[0]=pixels[i++]; pixel[1]=pixels[i++]; pixel[2]=pixels[i++]; pixel[3]=pixels[i++]; } SetPixelRed(q,0); SetPixelGreen(q,0); SetPixelBlue(q,0); if (pixel[3] != 0) { gamma=pow(2.0,pixel[3]-(128.0+8.0)); SetPixelRed(q,ClampToQuantum(QuantumRange*gamma*pixel[0])); SetPixelGreen(q,ClampToQuantum(QuantumRange*gamma*pixel[1])); SetPixelBlue(q,ClampToQuantum(QuantumRange*gamma*pixel[2])); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: KioskNextHomeInterfaceBrokerImpl::KioskNextHomeInterfaceBrokerImpl( content::BrowserContext* context) : connector_(content::BrowserContext::GetConnectorFor(context)->Clone()), app_controller_(std::make_unique<AppControllerImpl>( Profile::FromBrowserContext(context))) {} Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
KioskNextHomeInterfaceBrokerImpl::KioskNextHomeInterfaceBrokerImpl( content::BrowserContext* context)
172,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) { Commit Message: CWE ID: CWE-400
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx, int depth); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx, int depth); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) {
165,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); perf_event_enable(event); return 0; } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
int perf_event_refresh(struct perf_event *event, int refresh) static int _perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); _perf_event_enable(event); return 0; }
166,987
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateNull( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_NULL; return item; } 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
cJSON *cJSON_CreateNull( void )
167,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } Commit Message: issue #30 issue #31 issue #32: no multiple format chunks in WAV or W64 CWE ID: CWE-119
int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; int format_chunk = 0; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; if (format_chunk++) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
169,253
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AviaryScheddPlugin::processJob(const char *key, const char *, int ) { PROC_ID id; ClassAd *jobAd; if (!IS_JOB(key)) return false; id = getProcByString(key); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Failed to parse key: %s - skipping\n", key); return false; } if (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) { dprintf(D_ALWAYS, "NOTICE: Failed to lookup ad for %s - maybe deleted\n", key); return false; } MyString submissionName; if (GetAttributeString(id.cluster, id.proc, ATTR_JOB_SUBMISSION, submissionName) < 0) { PROC_ID dagman; if (GetAttributeInt(id.cluster, id.proc, ATTR_DAGMAN_JOB_ID, &dagman.cluster) >= 0) { dagman.proc = 0; if (GetAttributeString(dagman.cluster, dagman.proc, ATTR_JOB_SUBMISSION, submissionName) < 0) { submissionName.sprintf("%s#%d", Name, dagman.cluster); } } else { submissionName.sprintf("%s#%d", Name, id.cluster); } MyString tmp; tmp += "\""; tmp += submissionName; tmp += "\""; SetAttribute(id.cluster, id.proc, ATTR_JOB_SUBMISSION, tmp.Value()); } return true; } Commit Message: CWE ID: CWE-20
AviaryScheddPlugin::processJob(const char *key, const char *, int ) { PROC_ID id; ClassAd *jobAd; if (!IS_JOB(key)) return false; id = getProcByString(key); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Failed to parse key: %s - skipping\n", key); return false; } if (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) { dprintf(D_ALWAYS, "NOTICE: Failed to lookup ad for %s - maybe deleted\n", key); return false; } MyString submissionName; if (GetAttributeString(id.cluster, id.proc, ATTR_JOB_SUBMISSION, submissionName) < 0) { PROC_ID dagman; if (GetAttributeInt(id.cluster, id.proc, ATTR_DAGMAN_JOB_ID, &dagman.cluster) >= 0) { dagman.proc = 0; if (GetAttributeString(dagman.cluster, dagman.proc, ATTR_JOB_SUBMISSION, submissionName) < 0) { submissionName.sprintf("%s#%d", Name, dagman.cluster); } } else { submissionName.sprintf("%s#%d", Name, id.cluster); } MyString tmp; tmp += "\""; tmp += submissionName; tmp += "\""; SetAttribute(id.cluster, id.proc, ATTR_JOB_SUBMISSION, tmp.Value()); } return true; }
164,830
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __inline__ int scm_check_creds(struct ucred *creds) { const struct cred *cred = current_cred(); kuid_t uid = make_kuid(cred->user_ns, creds->uid); kgid_t gid = make_kgid(cred->user_ns, creds->gid); if (!uid_valid(uid) || !gid_valid(gid)) return -EINVAL; if ((creds->pid == task_tgid_vnr(current) || nsown_capable(CAP_SYS_ADMIN)) && ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) || uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) && ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) || gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) { return 0; } return -EPERM; } Commit Message: scm: Require CAP_SYS_ADMIN over the current pidns to spoof pids. Don't allow spoofing pids over unix domain sockets in the corner cases where a user has created a user namespace but has not yet created a pid namespace. Cc: [email protected] Reported-by: Andy Lutomirski <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-264
static __inline__ int scm_check_creds(struct ucred *creds) { const struct cred *cred = current_cred(); kuid_t uid = make_kuid(cred->user_ns, creds->uid); kgid_t gid = make_kgid(cred->user_ns, creds->gid); if (!uid_valid(uid) || !gid_valid(gid)) return -EINVAL; if ((creds->pid == task_tgid_vnr(current) || ns_capable(current->nsproxy->pid_ns->user_ns, CAP_SYS_ADMIN)) && ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) || uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) && ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) || gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) { return 0; } return -EPERM; }
166,093
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: smb_flush_file(struct smb_request *sr, struct smb_ofile *ofile) { sr->user_cr = smb_ofile_getcred(ofile); if ((ofile->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0) (void) smb_fsop_commit(sr, sr->user_cr, ofile->f_node); } Commit Message: 7483 SMB flush on pipe triggers NULL pointer dereference in module smbsrv Reviewed by: Gordon Ross <[email protected]> Reviewed by: Matt Barden <[email protected]> Reviewed by: Evan Layton <[email protected]> Reviewed by: Dan McDonald <[email protected]> Approved by: Gordon Ross <[email protected]> CWE ID: CWE-476
smb_flush_file(struct smb_request *sr, struct smb_ofile *ofile)
168,827
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Local<v8::Value> V8ValueConverterImpl::ToV8Object( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::DictionaryValue* val) const { v8::Local<v8::Object> result(v8::Object::New(isolate)); for (base::DictionaryValue::Iterator iter(*val); !iter.IsAtEnd(); iter.Advance()) { const std::string& key = iter.key(); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, &iter.value()); CHECK(!child_v8.IsEmpty()); v8::TryCatch try_catch(isolate); result->Set( v8::String::NewFromUtf8( isolate, key.c_str(), v8::String::kNormalString, key.length()), child_v8); if (try_catch.HasCaught()) { LOG(ERROR) << "Setter for property " << key.c_str() << " threw an " << "exception."; } } return result; } Commit Message: V8ValueConverter::ToV8Value should not trigger setters BUG=606390 Review URL: https://codereview.chromium.org/1918793003 Cr-Commit-Position: refs/heads/master@{#390045} CWE ID:
v8::Local<v8::Value> V8ValueConverterImpl::ToV8Object( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::DictionaryValue* val) const { v8::Local<v8::Object> result(v8::Object::New(isolate)); // TODO(robwu): Callers should pass in the context. v8::Local<v8::Context> context = isolate->GetCurrentContext(); for (base::DictionaryValue::Iterator iter(*val); !iter.IsAtEnd(); iter.Advance()) { const std::string& key = iter.key(); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, &iter.value()); CHECK(!child_v8.IsEmpty()); v8::Maybe<bool> maybe = result->CreateDataProperty( context, v8::String::NewFromUtf8(isolate, key.c_str(), v8::String::kNormalString, key.length()), child_v8); if (!maybe.IsJust() || !maybe.FromJust()) LOG(ERROR) << "Failed to set property with key " << key; } return result; }
173,284
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StyleResolver::matchUARules(ElementRuleCollector& collector) { collector.setMatchingUARules(true); if (CSSDefaultStyleSheets::simpleDefaultStyleSheet) collector.matchedResult().isCacheable = false; RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print") ? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle; matchUARules(collector, userAgentStyleSheet); if (document().inQuirksMode()) matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle); if (document().isViewSource()) matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle()); collector.setMatchingUARules(false); matchWatchSelectorRules(collector); } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void StyleResolver::matchUARules(ElementRuleCollector& collector) { collector.setMatchingUARules(true); RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print") ? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle; matchUARules(collector, userAgentStyleSheet); if (document().inQuirksMode()) matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle); if (document().isViewSource()) matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle()); collector.setMatchingUARules(false); matchWatchSelectorRules(collector); }
171,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len) { while (!iov->iov_len) iov++; while (len > 0) { unsigned long this_len; this_len = min_t(unsigned long, len, iov->iov_len); fault_in_pages_readable(iov->iov_base, this_len); len -= this_len; iov++; } } Commit Message: new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len)
166,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Initialized(mojo::ScopedSharedBufferHandle shared_buffer, mojo::ScopedHandle socket_handle) { ASSERT_TRUE(shared_buffer.is_valid()); ASSERT_TRUE(socket_handle.is_valid()); base::PlatformFile fd; mojo::UnwrapPlatformFile(std::move(socket_handle), &fd); socket_ = std::make_unique<base::CancelableSyncSocket>(fd); EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle); size_t memory_length; base::SharedMemoryHandle shmem_handle; bool read_only; EXPECT_EQ( mojo::UnwrapSharedMemoryHandle(std::move(shared_buffer), &shmem_handle, &memory_length, &read_only), MOJO_RESULT_OK); EXPECT_FALSE(read_only); buffer_ = std::make_unique<base::SharedMemory>(shmem_handle, read_only); GotNotification(); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787
void Initialized(mojo::ScopedSharedBufferHandle shared_buffer, mojo::ScopedHandle socket_handle) { ASSERT_TRUE(shared_buffer.is_valid()); ASSERT_TRUE(socket_handle.is_valid()); base::PlatformFile fd; mojo::UnwrapPlatformFile(std::move(socket_handle), &fd); socket_ = std::make_unique<base::CancelableSyncSocket>(fd); EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle); size_t memory_length; base::SharedMemoryHandle shmem_handle; mojo::UnwrappedSharedMemoryHandleProtection protection; EXPECT_EQ( mojo::UnwrapSharedMemoryHandle(std::move(shared_buffer), &shmem_handle, &memory_length, &protection), MOJO_RESULT_OK); EXPECT_EQ(protection, mojo::UnwrappedSharedMemoryHandleProtection::kReadWrite); buffer_ = std::make_unique<base::SharedMemory>(shmem_handle, false /* read_only */); GotNotification(); }
172,880
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(GlobIterator, count) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL)); } else { /* should not happen */ php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state"); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(GlobIterator, count) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL)); } else { /* should not happen */ php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state"); } }
167,048
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Verify_StoreExistingGroupExistingCache(base::Time expected_update_time) { EXPECT_TRUE(delegate()->stored_group_success_); EXPECT_EQ(cache_.get(), group_->newest_complete_cache()); AppCacheDatabase::CacheRecord cache_record; EXPECT_TRUE(database()->FindCache(1, &cache_record)); EXPECT_EQ(1, cache_record.cache_id); EXPECT_EQ(1, cache_record.group_id); EXPECT_FALSE(cache_record.online_wildcard); EXPECT_TRUE(expected_update_time == cache_record.update_time); EXPECT_EQ(100 + kDefaultEntrySize, cache_record.cache_size); std::vector<AppCacheDatabase::EntryRecord> entry_records; EXPECT_TRUE(database()->FindEntriesForCache(1, &entry_records)); EXPECT_EQ(2U, entry_records.size()); if (entry_records[0].url == kDefaultEntryUrl) entry_records.erase(entry_records.begin()); EXPECT_EQ(1, entry_records[0].cache_id); EXPECT_EQ(kEntryUrl, entry_records[0].url); EXPECT_EQ(AppCacheEntry::MASTER, entry_records[0].flags); EXPECT_EQ(1, entry_records[0].response_id); EXPECT_EQ(100, entry_records[0].response_size); EXPECT_EQ(100 + kDefaultEntrySize, storage()->usage_map_[kOrigin]); EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_); EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_); EXPECT_EQ(100, mock_quota_manager_proxy_->last_delta_); TestFinished(); } 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
void Verify_StoreExistingGroupExistingCache(base::Time expected_update_time) { EXPECT_TRUE(delegate()->stored_group_success_); EXPECT_EQ(cache_.get(), group_->newest_complete_cache()); AppCacheDatabase::CacheRecord cache_record; EXPECT_TRUE(database()->FindCache(1, &cache_record)); EXPECT_EQ(1, cache_record.cache_id); EXPECT_EQ(1, cache_record.group_id); EXPECT_FALSE(cache_record.online_wildcard); EXPECT_TRUE(expected_update_time == cache_record.update_time); EXPECT_EQ(100 + kDefaultEntrySize, cache_record.cache_size); EXPECT_EQ(10 + kDefaultEntryPadding, cache_record.padding_size); std::vector<AppCacheDatabase::EntryRecord> entry_records; EXPECT_TRUE(database()->FindEntriesForCache(1, &entry_records)); EXPECT_EQ(2U, entry_records.size()); if (entry_records[0].url == kDefaultEntryUrl) entry_records.erase(entry_records.begin()); EXPECT_EQ(1, entry_records[0].cache_id); EXPECT_EQ(kEntryUrl, entry_records[0].url); EXPECT_EQ(AppCacheEntry::EXPLICIT, entry_records[0].flags); EXPECT_EQ(1, entry_records[0].response_id); EXPECT_EQ(100, entry_records[0].response_size); EXPECT_EQ(10, entry_records[0].padding_size); EXPECT_EQ(100 + 10 + kDefaultEntrySize + kDefaultEntryPadding, storage()->usage_map_[kOrigin]); EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_); EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_); EXPECT_EQ(100 + 10, mock_quota_manager_proxy_->last_delta_); TestFinished(); }
172,994
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameFetchContext::DispatchDidBlockRequest( const ResourceRequest& resource_request, const FetchInitiatorInfo& fetch_initiator_info, ResourceRequestBlockedReason blocked_reason) const { if (IsDetached()) return; probe::didBlockRequest(GetFrame()->GetDocument(), resource_request, MasterDocumentLoader(), fetch_initiator_info, blocked_reason); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void FrameFetchContext::DispatchDidBlockRequest( const ResourceRequest& resource_request, const FetchInitiatorInfo& fetch_initiator_info, ResourceRequestBlockedReason blocked_reason, Resource::Type resource_type) const { if (IsDetached()) return; probe::didBlockRequest(GetFrame()->GetDocument(), resource_request, MasterDocumentLoader(), fetch_initiator_info, blocked_reason, resource_type); }
172,473
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void logi_dj_recv_add_djhid_device(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { /* Called in delayed work context */ struct hid_device *djrcv_hdev = djrcv_dev->hdev; struct usb_interface *intf = to_usb_interface(djrcv_hdev->dev.parent); struct usb_device *usbdev = interface_to_usbdev(intf); struct hid_device *dj_hiddev; struct dj_device *dj_dev; /* Device index goes from 1 to 6, we need 3 bytes to store the * semicolon, the index, and a null terminator */ unsigned char tmpstr[3]; if (dj_report->report_params[DEVICE_PAIRED_PARAM_SPFUNCTION] & SPFUNCTION_DEVICE_LIST_EMPTY) { dbg_hid("%s: device list is empty\n", __func__); djrcv_dev->querying_devices = false; return; } if ((dj_report->device_index < DJ_DEVICE_INDEX_MIN) || (dj_report->device_index > DJ_DEVICE_INDEX_MAX)) { dev_err(&djrcv_hdev->dev, "%s: invalid device index:%d\n", __func__, dj_report->device_index); return; } if (djrcv_dev->paired_dj_devices[dj_report->device_index]) { /* The device is already known. No need to reallocate it. */ dbg_hid("%s: device is already known\n", __func__); return; } dj_hiddev = hid_allocate_device(); if (IS_ERR(dj_hiddev)) { dev_err(&djrcv_hdev->dev, "%s: hid_allocate_device failed\n", __func__); return; } dj_hiddev->ll_driver = &logi_dj_ll_driver; dj_hiddev->dev.parent = &djrcv_hdev->dev; dj_hiddev->bus = BUS_USB; dj_hiddev->vendor = le16_to_cpu(usbdev->descriptor.idVendor); dj_hiddev->product = le16_to_cpu(usbdev->descriptor.idProduct); snprintf(dj_hiddev->name, sizeof(dj_hiddev->name), "Logitech Unifying Device. Wireless PID:%02x%02x", dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_MSB], dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_LSB]); usb_make_path(usbdev, dj_hiddev->phys, sizeof(dj_hiddev->phys)); snprintf(tmpstr, sizeof(tmpstr), ":%d", dj_report->device_index); strlcat(dj_hiddev->phys, tmpstr, sizeof(dj_hiddev->phys)); dj_dev = kzalloc(sizeof(struct dj_device), GFP_KERNEL); if (!dj_dev) { dev_err(&djrcv_hdev->dev, "%s: failed allocating dj_device\n", __func__); goto dj_device_allocate_fail; } dj_dev->reports_supported = get_unaligned_le32( dj_report->report_params + DEVICE_PAIRED_RF_REPORT_TYPE); dj_dev->hdev = dj_hiddev; dj_dev->dj_receiver_dev = djrcv_dev; dj_dev->device_index = dj_report->device_index; dj_hiddev->driver_data = dj_dev; djrcv_dev->paired_dj_devices[dj_report->device_index] = dj_dev; if (hid_add_device(dj_hiddev)) { dev_err(&djrcv_hdev->dev, "%s: failed adding dj_device\n", __func__); goto hid_add_device_fail; } return; hid_add_device_fail: djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL; kfree(dj_dev); dj_device_allocate_fail: hid_destroy_device(dj_hiddev); } Commit Message: HID: logitech: perform bounds checking on device_id early enough device_index is a char type and the size of paired_dj_deivces is 7 elements, therefore proper bounds checking has to be applied to device_index before it is used. We are currently performing the bounds checking in logi_dj_recv_add_djhid_device(), which is too late, as malicious device could send REPORT_TYPE_NOTIF_DEVICE_UNPAIRED early enough and trigger the problem in one of the report forwarding functions called from logi_dj_raw_event(). Fix this by performing the check at the earliest possible ocasion in logi_dj_raw_event(). Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static void logi_dj_recv_add_djhid_device(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { /* Called in delayed work context */ struct hid_device *djrcv_hdev = djrcv_dev->hdev; struct usb_interface *intf = to_usb_interface(djrcv_hdev->dev.parent); struct usb_device *usbdev = interface_to_usbdev(intf); struct hid_device *dj_hiddev; struct dj_device *dj_dev; /* Device index goes from 1 to 6, we need 3 bytes to store the * semicolon, the index, and a null terminator */ unsigned char tmpstr[3]; if (dj_report->report_params[DEVICE_PAIRED_PARAM_SPFUNCTION] & SPFUNCTION_DEVICE_LIST_EMPTY) { dbg_hid("%s: device list is empty\n", __func__); djrcv_dev->querying_devices = false; return; } if (djrcv_dev->paired_dj_devices[dj_report->device_index]) { /* The device is already known. No need to reallocate it. */ dbg_hid("%s: device is already known\n", __func__); return; } dj_hiddev = hid_allocate_device(); if (IS_ERR(dj_hiddev)) { dev_err(&djrcv_hdev->dev, "%s: hid_allocate_device failed\n", __func__); return; } dj_hiddev->ll_driver = &logi_dj_ll_driver; dj_hiddev->dev.parent = &djrcv_hdev->dev; dj_hiddev->bus = BUS_USB; dj_hiddev->vendor = le16_to_cpu(usbdev->descriptor.idVendor); dj_hiddev->product = le16_to_cpu(usbdev->descriptor.idProduct); snprintf(dj_hiddev->name, sizeof(dj_hiddev->name), "Logitech Unifying Device. Wireless PID:%02x%02x", dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_MSB], dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_LSB]); usb_make_path(usbdev, dj_hiddev->phys, sizeof(dj_hiddev->phys)); snprintf(tmpstr, sizeof(tmpstr), ":%d", dj_report->device_index); strlcat(dj_hiddev->phys, tmpstr, sizeof(dj_hiddev->phys)); dj_dev = kzalloc(sizeof(struct dj_device), GFP_KERNEL); if (!dj_dev) { dev_err(&djrcv_hdev->dev, "%s: failed allocating dj_device\n", __func__); goto dj_device_allocate_fail; } dj_dev->reports_supported = get_unaligned_le32( dj_report->report_params + DEVICE_PAIRED_RF_REPORT_TYPE); dj_dev->hdev = dj_hiddev; dj_dev->dj_receiver_dev = djrcv_dev; dj_dev->device_index = dj_report->device_index; dj_hiddev->driver_data = dj_dev; djrcv_dev->paired_dj_devices[dj_report->device_index] = dj_dev; if (hid_add_device(dj_hiddev)) { dev_err(&djrcv_hdev->dev, "%s: failed adding dj_device\n", __func__); goto hid_add_device_fail; } return; hid_add_device_fail: djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL; kfree(dj_dev); dj_device_allocate_fail: hid_destroy_device(dj_hiddev); }
166,378
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() { WebContentsImpl* old_contents = GetFocusedWebContents(); if (old_contents == this) return; GetOutermostWebContents()->node_.SetFocusedWebContents(this); if (!GuestMode::IsCrossProcessFrameGuest(this) && browser_plugin_guest_) return; if (old_contents) old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false); if (GetRenderManager()->GetProxyToOuterDelegate()) GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame(); if (ShowingInterstitialPage()) { static_cast<RenderFrameHostImpl*>( GetRenderManager()->interstitial_page()->GetMainFrame()) ->GetRenderWidgetHost() ->SetPageFocus(true); } else { GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true); } } 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
void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() { WebContentsImpl* old_contents = GetFocusedWebContents(); if (old_contents == this) return; GetOutermostWebContents()->node_.SetFocusedWebContents(this); if (!GuestMode::IsCrossProcessFrameGuest(this) && browser_plugin_guest_) return; if (old_contents) old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false); if (GetRenderManager()->GetProxyToOuterDelegate()) GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame(); if (ShowingInterstitialPage()) { static_cast<RenderFrameHostImpl*>(interstitial_page_->GetMainFrame()) ->GetRenderWidgetHost() ->SetPageFocus(true); } else { GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true); } }
172,333
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void QuotaTask::DeleteSoon() { MessageLoop::current()->DeleteSoon(FROM_HERE, this); } Commit Message: Quota double-delete fix BUG=142310 Review URL: https://chromiumcodereview.appspot.com/10832407 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152532 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void QuotaTask::DeleteSoon() { DCHECK(original_task_runner_->BelongsToCurrentThread()); if (delete_scheduled_) return; delete_scheduled_ = true; MessageLoop::current()->DeleteSoon(FROM_HERE, this); }
170,803
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void read_boot(DOS_FS * fs) { struct boot_sector b; unsigned total_sectors; unsigned short logical_sector_size, sectors; unsigned fat_length; unsigned total_fat_entries; off_t data_size; fs_read(0, sizeof(b), &b); logical_sector_size = GET_UNALIGNED_W(b.sector_size); if (!logical_sector_size) die("Logical sector size is zero."); /* This was moved up because it's the first thing that will fail */ /* if the platform needs special handling of unaligned multibyte accesses */ /* but such handling isn't being provided. See GET_UNALIGNED_W() above. */ if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); fs->cluster_size = b.cluster_size * logical_sector_size; if (!fs->cluster_size) die("Cluster size is zero."); if (b.fats != 2 && b.fats != 1) die("Currently, only 1 or 2 FATs are supported, not %d.\n", b.fats); fs->nfats = b.fats; sectors = GET_UNALIGNED_W(b.sectors); total_sectors = sectors ? sectors : le32toh(b.total_sect); if (verbose) printf("Checking we can access the last sector of the filesystem\n"); /* Can't access last odd sector anyway, so round down */ fs_test((off_t)((total_sectors & ~1) - 1) * logical_sector_size, logical_sector_size); fat_length = le16toh(b.fat_length) ? le16toh(b.fat_length) : le32toh(b.fat32_length); fs->fat_start = (off_t)le16toh(b.reserved) * logical_sector_size; fs->root_start = ((off_t)le16toh(b.reserved) + b.fats * fat_length) * logical_sector_size; fs->root_entries = GET_UNALIGNED_W(b.dir_entries); fs->data_start = fs->root_start + ROUND_TO_MULTIPLE(fs->root_entries << MSDOS_DIR_BITS, logical_sector_size); data_size = (off_t)total_sectors * logical_sector_size - fs->data_start; fs->data_clusters = data_size / fs->cluster_size; fs->root_cluster = 0; /* indicates standard, pre-FAT32 root dir */ fs->fsinfo_start = 0; /* no FSINFO structure */ fs->free_clusters = -1; /* unknown */ if (!b.fat_length && b.fat32_length) { fs->fat_bits = 32; fs->root_cluster = le32toh(b.root_cluster); if (!fs->root_cluster && fs->root_entries) /* M$ hasn't specified this, but it looks reasonable: If * root_cluster is 0 but there is a separate root dir * (root_entries != 0), we handle the root dir the old way. Give a * warning, but convertig to a root dir in a cluster chain seems * to complex for now... */ printf("Warning: FAT32 root dir not in cluster chain! " "Compatibility mode...\n"); else if (!fs->root_cluster && !fs->root_entries) die("No root directory!"); else if (fs->root_cluster && fs->root_entries) printf("Warning: FAT32 root dir is in a cluster chain, but " "a separate root dir\n" " area is defined. Cannot fix this easily.\n"); if (fs->data_clusters < FAT16_THRESHOLD) printf("Warning: Filesystem is FAT32 according to fat_length " "and fat32_length fields,\n" " but has only %lu clusters, less than the required " "minimum of %d.\n" " This may lead to problems on some systems.\n", (unsigned long)fs->data_clusters, FAT16_THRESHOLD); check_fat_state_bit(fs, &b); fs->backupboot_start = le16toh(b.backup_boot) * logical_sector_size; check_backup_boot(fs, &b, logical_sector_size); read_fsinfo(fs, &b, logical_sector_size); } else if (!atari_format) { /* On real MS-DOS, a 16 bit FAT is used whenever there would be too * much clusers otherwise. */ fs->fat_bits = (fs->data_clusters >= FAT12_THRESHOLD) ? 16 : 12; if (fs->data_clusters >= FAT16_THRESHOLD) die("Too many clusters (%lu) for FAT16 filesystem.", fs->data_clusters); check_fat_state_bit(fs, &b); } else { /* On Atari, things are more difficult: GEMDOS always uses 12bit FATs * on floppies, and always 16 bit on harddisks. */ fs->fat_bits = 16; /* assume 16 bit FAT for now */ /* If more clusters than fat entries in 16-bit fat, we assume * it's a real MSDOS FS with 12-bit fat. */ if (fs->data_clusters + 2 > fat_length * logical_sector_size * 8 / 16 || /* if it has one of the usual floppy sizes -> 12bit FAT */ (total_sectors == 720 || total_sectors == 1440 || total_sectors == 2880)) fs->fat_bits = 12; } /* On FAT32, the high 4 bits of a FAT entry are reserved */ fs->eff_fat_bits = (fs->fat_bits == 32) ? 28 : fs->fat_bits; fs->fat_size = fat_length * logical_sector_size; fs->label = calloc(12, sizeof(uint8_t)); if (fs->fat_bits == 12 || fs->fat_bits == 16) { struct boot_sector_16 *b16 = (struct boot_sector_16 *)&b; if (b16->extended_sig == 0x29) memmove(fs->label, b16->label, 11); else fs->label = NULL; } else if (fs->fat_bits == 32) { if (b.extended_sig == 0x29) memmove(fs->label, &b.label, 11); else fs->label = NULL; } total_fat_entries = (uint64_t)fs->fat_size * 8 / fs->fat_bits; if (fs->data_clusters > total_fat_entries - 2) die("Filesystem has %u clusters but only space for %u FAT entries.", fs->data_clusters, total_fat_entries - 2); if (!fs->root_entries && !fs->root_cluster) die("Root directory has zero size."); if (fs->root_entries & (MSDOS_DPS - 1)) die("Root directory (%d entries) doesn't span an integral number of " "sectors.", fs->root_entries); if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); #if 0 /* linux kernel doesn't check that either */ /* ++roman: On Atari, these two fields are often left uninitialized */ if (!atari_format && (!b.secs_track || !b.heads)) die("Invalid disk format in boot sector."); #endif if (verbose) dump_boot(fs, &b, logical_sector_size); } Commit Message: read_boot(): Handle excessive FAT size specifications The variable used for storing the FAT size (in bytes) was an unsigned int. Since the size in sectors read from the BPB was not sufficiently checked, this could end up being zero after multiplying it with the sector size while some offsets still stayed excessive. Ultimately it would cause segfaults when accessing FAT entries for which no memory was allocated. Make it more robust by changing the types used to store FAT size to off_t and abort if there is no room for data clusters. Additionally check that FAT size is not specified as zero. Fixes #25 and fixes #26. Reported-by: Hanno Böck Signed-off-by: Andreas Bombe <[email protected]> CWE ID: CWE-119
void read_boot(DOS_FS * fs) { struct boot_sector b; unsigned total_sectors; unsigned short logical_sector_size, sectors; off_t fat_length; unsigned total_fat_entries; off_t data_size; fs_read(0, sizeof(b), &b); logical_sector_size = GET_UNALIGNED_W(b.sector_size); if (!logical_sector_size) die("Logical sector size is zero."); /* This was moved up because it's the first thing that will fail */ /* if the platform needs special handling of unaligned multibyte accesses */ /* but such handling isn't being provided. See GET_UNALIGNED_W() above. */ if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); fs->cluster_size = b.cluster_size * logical_sector_size; if (!fs->cluster_size) die("Cluster size is zero."); if (b.fats != 2 && b.fats != 1) die("Currently, only 1 or 2 FATs are supported, not %d.\n", b.fats); fs->nfats = b.fats; sectors = GET_UNALIGNED_W(b.sectors); total_sectors = sectors ? sectors : le32toh(b.total_sect); if (verbose) printf("Checking we can access the last sector of the filesystem\n"); /* Can't access last odd sector anyway, so round down */ fs_test((off_t)((total_sectors & ~1) - 1) * logical_sector_size, logical_sector_size); fat_length = le16toh(b.fat_length) ? le16toh(b.fat_length) : le32toh(b.fat32_length); if (!fat_length) die("FAT size is zero."); fs->fat_start = (off_t)le16toh(b.reserved) * logical_sector_size; fs->root_start = ((off_t)le16toh(b.reserved) + b.fats * fat_length) * logical_sector_size; fs->root_entries = GET_UNALIGNED_W(b.dir_entries); fs->data_start = fs->root_start + ROUND_TO_MULTIPLE(fs->root_entries << MSDOS_DIR_BITS, logical_sector_size); data_size = (off_t)total_sectors * logical_sector_size - fs->data_start; if (data_size < fs->cluster_size) die("Filesystem has no space for any data clusters"); fs->data_clusters = data_size / fs->cluster_size; fs->root_cluster = 0; /* indicates standard, pre-FAT32 root dir */ fs->fsinfo_start = 0; /* no FSINFO structure */ fs->free_clusters = -1; /* unknown */ if (!b.fat_length && b.fat32_length) { fs->fat_bits = 32; fs->root_cluster = le32toh(b.root_cluster); if (!fs->root_cluster && fs->root_entries) /* M$ hasn't specified this, but it looks reasonable: If * root_cluster is 0 but there is a separate root dir * (root_entries != 0), we handle the root dir the old way. Give a * warning, but convertig to a root dir in a cluster chain seems * to complex for now... */ printf("Warning: FAT32 root dir not in cluster chain! " "Compatibility mode...\n"); else if (!fs->root_cluster && !fs->root_entries) die("No root directory!"); else if (fs->root_cluster && fs->root_entries) printf("Warning: FAT32 root dir is in a cluster chain, but " "a separate root dir\n" " area is defined. Cannot fix this easily.\n"); if (fs->data_clusters < FAT16_THRESHOLD) printf("Warning: Filesystem is FAT32 according to fat_length " "and fat32_length fields,\n" " but has only %lu clusters, less than the required " "minimum of %d.\n" " This may lead to problems on some systems.\n", (unsigned long)fs->data_clusters, FAT16_THRESHOLD); check_fat_state_bit(fs, &b); fs->backupboot_start = le16toh(b.backup_boot) * logical_sector_size; check_backup_boot(fs, &b, logical_sector_size); read_fsinfo(fs, &b, logical_sector_size); } else if (!atari_format) { /* On real MS-DOS, a 16 bit FAT is used whenever there would be too * much clusers otherwise. */ fs->fat_bits = (fs->data_clusters >= FAT12_THRESHOLD) ? 16 : 12; if (fs->data_clusters >= FAT16_THRESHOLD) die("Too many clusters (%lu) for FAT16 filesystem.", fs->data_clusters); check_fat_state_bit(fs, &b); } else { /* On Atari, things are more difficult: GEMDOS always uses 12bit FATs * on floppies, and always 16 bit on harddisks. */ fs->fat_bits = 16; /* assume 16 bit FAT for now */ /* If more clusters than fat entries in 16-bit fat, we assume * it's a real MSDOS FS with 12-bit fat. */ if (fs->data_clusters + 2 > fat_length * logical_sector_size * 8 / 16 || /* if it has one of the usual floppy sizes -> 12bit FAT */ (total_sectors == 720 || total_sectors == 1440 || total_sectors == 2880)) fs->fat_bits = 12; } /* On FAT32, the high 4 bits of a FAT entry are reserved */ fs->eff_fat_bits = (fs->fat_bits == 32) ? 28 : fs->fat_bits; fs->fat_size = fat_length * logical_sector_size; fs->label = calloc(12, sizeof(uint8_t)); if (fs->fat_bits == 12 || fs->fat_bits == 16) { struct boot_sector_16 *b16 = (struct boot_sector_16 *)&b; if (b16->extended_sig == 0x29) memmove(fs->label, b16->label, 11); else fs->label = NULL; } else if (fs->fat_bits == 32) { if (b.extended_sig == 0x29) memmove(fs->label, &b.label, 11); else fs->label = NULL; } total_fat_entries = (uint64_t)fs->fat_size * 8 / fs->fat_bits; if (fs->data_clusters > total_fat_entries - 2) die("Filesystem has %u clusters but only space for %u FAT entries.", fs->data_clusters, total_fat_entries - 2); if (!fs->root_entries && !fs->root_cluster) die("Root directory has zero size."); if (fs->root_entries & (MSDOS_DPS - 1)) die("Root directory (%d entries) doesn't span an integral number of " "sectors.", fs->root_entries); if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); #if 0 /* linux kernel doesn't check that either */ /* ++roman: On Atari, these two fields are often left uninitialized */ if (!atari_format && (!b.secs_track || !b.heads)) die("Invalid disk format in boot sector."); #endif if (verbose) dump_boot(fs, &b, logical_sector_size); }
167,232
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t BnHDCP::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case HDCP_SET_OBSERVER: { CHECK_INTERFACE(IHDCP, data, reply); sp<IHDCPObserver> observer = interface_cast<IHDCPObserver>(data.readStrongBinder()); reply->writeInt32(setObserver(observer)); return OK; } case HDCP_INIT_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); const char *host = data.readCString(); unsigned port = data.readInt32(); reply->writeInt32(initAsync(host, port)); return OK; } case HDCP_SHUTDOWN_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(shutdownAsync()); return OK; } case HDCP_GET_CAPS: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(getCaps()); return OK; } case HDCP_ENCRYPT: { size_t size = data.readInt32(); void *inData = malloc(2 * size); void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR; status_t err = encrypt(inData, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } case HDCP_ENCRYPT_NATIVE: { CHECK_INTERFACE(IHDCP, data, reply); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); size_t offset = data.readInt32(); size_t size = data.readInt32(); uint32_t streamCTR = data.readInt32(); void *outData = malloc(size); uint64_t inputCTR; status_t err = encryptNative(graphicBuffer, offset, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(outData); outData = NULL; return OK; } case HDCP_DECRYPT: { size_t size = data.readInt32(); void *inData = malloc(2 * size); void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR = data.readInt64(); status_t err = decrypt(inData, size, streamCTR, inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } default: return BBinder::onTransact(code, data, reply, flags); } } Commit Message: HDCP: buffer over flow check -- DO NOT MERGE bug: 20222489 Change-Id: I3a64a5999d68ea243d187f12ec7717b7f26d93a3 (cherry picked from commit 532cd7b86a5fdc7b9a30a45d8ae2d16ef7660a72) CWE ID: CWE-189
status_t BnHDCP::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case HDCP_SET_OBSERVER: { CHECK_INTERFACE(IHDCP, data, reply); sp<IHDCPObserver> observer = interface_cast<IHDCPObserver>(data.readStrongBinder()); reply->writeInt32(setObserver(observer)); return OK; } case HDCP_INIT_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); const char *host = data.readCString(); unsigned port = data.readInt32(); reply->writeInt32(initAsync(host, port)); return OK; } case HDCP_SHUTDOWN_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(shutdownAsync()); return OK; } case HDCP_GET_CAPS: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(getCaps()); return OK; } case HDCP_ENCRYPT: { size_t size = data.readInt32(); size_t bufSize = 2 * size; // watch out for overflow void *inData = NULL; if (bufSize > size) { inData = malloc(bufSize); } if (inData == NULL) { reply->writeInt32(ERROR_OUT_OF_RANGE); return OK; } void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR; status_t err = encrypt(inData, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } case HDCP_ENCRYPT_NATIVE: { CHECK_INTERFACE(IHDCP, data, reply); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); size_t offset = data.readInt32(); size_t size = data.readInt32(); uint32_t streamCTR = data.readInt32(); void *outData = malloc(size); uint64_t inputCTR; status_t err = encryptNative(graphicBuffer, offset, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(outData); outData = NULL; return OK; } case HDCP_DECRYPT: { size_t size = data.readInt32(); size_t bufSize = 2 * size; // watch out for overflow void *inData = NULL; if (bufSize > size) { inData = malloc(bufSize); } if (inData == NULL) { reply->writeInt32(ERROR_OUT_OF_RANGE); return OK; } void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR = data.readInt64(); status_t err = decrypt(inData, size, streamCTR, inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } default: return BBinder::onTransact(code, data, reply, flags); } }
173,361
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _rsvg_io_get_file_path (const gchar * filename, const gchar * base_uri) { gchar *absolute_filename; if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) { absolute_filename = g_strdup (filename); } else { gchar *tmpcdir; gchar *base_filename; if (base_uri) { base_filename = g_filename_from_uri (base_uri, NULL, NULL); if (base_filename != NULL) { tmpcdir = g_path_get_dirname (base_filename); g_free (base_filename); } else return NULL; } else tmpcdir = g_get_current_dir (); absolute_filename = g_build_filename (tmpcdir, filename, NULL); g_free (tmpcdir); } return absolute_filename; } Commit Message: Fixed possible credentials leaking reported by Alex Birsan. CWE ID:
_rsvg_io_get_file_path (const gchar * filename, const gchar * base_uri) { gchar *absolute_filename; if (g_path_is_absolute (filename)) { absolute_filename = g_strdup (filename); } else { gchar *tmpcdir; gchar *base_filename; if (base_uri) { base_filename = g_filename_from_uri (base_uri, NULL, NULL); if (base_filename != NULL) { tmpcdir = g_path_get_dirname (base_filename); g_free (base_filename); } else return NULL; } else tmpcdir = g_get_current_dir (); absolute_filename = g_build_filename (tmpcdir, filename, NULL); g_free (tmpcdir); } return absolute_filename; }
170,157
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dispatch_cmd(conn c) { int r, i, timeout = -1; size_t z; unsigned int count; job j; unsigned char type; char *size_buf, *delay_buf, *ttr_buf, *pri_buf, *end_buf, *name; unsigned int pri, body_size; usec delay, ttr; uint64_t id; tube t = NULL; /* NUL-terminate this string so we can use strtol and friends */ c->cmd[c->cmd_len - 2] = '\0'; /* check for possible maliciousness */ if (strlen(c->cmd) != c->cmd_len - 2) { return reply_msg(c, MSG_BAD_FORMAT); } type = which_cmd(c); dprintf("got %s command: \"%s\"\n", op_names[(int) type], c->cmd); switch (type) { case OP_PUT: r = read_pri(&pri, c->cmd + 4, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, &ttr_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_ttr(&ttr, ttr_buf, &size_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); errno = 0; body_size = strtoul(size_buf, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); if (body_size > job_data_size_limit) { return reply_msg(c, MSG_JOB_TOO_BIG); } /* don't allow trailing garbage */ if (end_buf[0] != '\0') return reply_msg(c, MSG_BAD_FORMAT); conn_set_producer(c); c->in_job = make_job(pri, delay, ttr ? : 1, body_size + 2, c->use); /* OOM? */ if (!c->in_job) { /* throw away the job body and respond with OUT_OF_MEMORY */ twarnx("server error: " MSG_OUT_OF_MEMORY); return skip(c, body_size + 2, MSG_OUT_OF_MEMORY); } fill_extra_data(c); /* it's possible we already have a complete job */ maybe_enqueue_incoming_job(c); break; case OP_PEEK_READY: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_READY_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(pq_peek(&c->use->ready)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEK_DELAYED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_DELAYED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(pq_peek(&c->use->delay)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEK_BURIED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_BURIED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(buried_job_p(c->use)? j = c->use->buried.next : NULL); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEKJOB: errno = 0; id = strtoull(c->cmd + CMD_PEEKJOB_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; /* So, peek is annoying, because some other connection might free the * job while we are still trying to write it out. So we copy it and * then free the copy when it's done sending. */ j = job_copy(peek_job(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_RESERVE_TIMEOUT: errno = 0; timeout = strtol(c->cmd + CMD_RESERVE_TIMEOUT_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); case OP_RESERVE: /* FALLTHROUGH */ /* don't allow trailing garbage */ if (type == OP_RESERVE && c->cmd_len != CMD_RESERVE_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; conn_set_worker(c); if (conn_has_close_deadline(c) && !conn_ready(c)) { return reply_msg(c, MSG_DEADLINE_SOON); } /* try to get a new job for this guy */ wait_for_job(c, timeout); process_queue(); break; case OP_DELETE: errno = 0; id = strtoull(c->cmd + CMD_DELETE_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = job_find(id); j = remove_reserved_job(c, j) ? : remove_ready_job(j) ? : remove_buried_job(j); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); j->state = JOB_STATE_INVALID; r = binlog_write_job(j); job_free(j); if (!r) return reply_serr(c, MSG_INTERNAL_ERROR); reply(c, MSG_DELETED, MSG_DELETED_LEN, STATE_SENDWORD); break; case OP_RELEASE: errno = 0; id = strtoull(c->cmd + CMD_RELEASE_LEN, &pri_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); r = read_pri(&pri, pri_buf, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = remove_reserved_job(c, job_find(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); /* We want to update the delay deadline on disk, so reserve space for * that. */ if (delay) { z = binlog_reserve_space_update(j); if (!z) return reply_serr(c, MSG_OUT_OF_MEMORY); j->reserved_binlog_space += z; } j->pri = pri; j->delay = delay; j->release_ct++; r = enqueue_job(j, delay, !!delay); if (r < 0) return reply_serr(c, MSG_INTERNAL_ERROR); if (r == 1) { return reply(c, MSG_RELEASED, MSG_RELEASED_LEN, STATE_SENDWORD); } /* out of memory trying to grow the queue, so it gets buried */ bury_job(j, 0); reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD); break; case OP_BURY: errno = 0; id = strtoull(c->cmd + CMD_BURY_LEN, &pri_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); r = read_pri(&pri, pri_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = remove_reserved_job(c, job_find(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); j->pri = pri; r = bury_job(j, 1); if (!r) return reply_serr(c, MSG_INTERNAL_ERROR); reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD); break; case OP_KICK: errno = 0; count = strtoul(c->cmd + CMD_KICK_LEN, &end_buf, 10); if (end_buf == c->cmd + CMD_KICK_LEN) { return reply_msg(c, MSG_BAD_FORMAT); } if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; i = kick_jobs(c->use, count); return reply_line(c, STATE_SENDWORD, "KICKED %u\r\n", i); case OP_TOUCH: errno = 0; id = strtoull(c->cmd + CMD_TOUCH_LEN, &end_buf, 10); if (errno) return twarn("strtoull"), reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = touch_job(c, job_find(id)); if (j) { reply(c, MSG_TOUCHED, MSG_TOUCHED_LEN, STATE_SENDWORD); } else { return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); } break; case OP_STATS: /* don't allow trailing garbage */ if (c->cmd_len != CMD_STATS_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_stats(c, fmt_stats, NULL); break; case OP_JOBSTATS: errno = 0; id = strtoull(c->cmd + CMD_JOBSTATS_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = peek_job(id); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); if (!j->tube) return reply_serr(c, MSG_INTERNAL_ERROR); do_stats(c, (fmt_fn) fmt_job_stats, j); break; case OP_STATS_TUBE: name = c->cmd + CMD_STATS_TUBE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; t = tube_find(name); if (!t) return reply_msg(c, MSG_NOTFOUND); do_stats(c, (fmt_fn) fmt_stats_tube, t); t = NULL; break; case OP_LIST_TUBES: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBES_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_list_tubes(c, &tubes); break; case OP_LIST_TUBE_USED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBE_USED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name); break; case OP_LIST_TUBES_WATCHED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBES_WATCHED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_list_tubes(c, &c->watch); break; case OP_USE: name = c->cmd + CMD_USE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; TUBE_ASSIGN(t, tube_find_or_make(name)); if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY); c->use->using_ct--; TUBE_ASSIGN(c->use, t); TUBE_ASSIGN(t, NULL); c->use->using_ct++; reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name); break; case OP_WATCH: name = c->cmd + CMD_WATCH_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; TUBE_ASSIGN(t, tube_find_or_make(name)); if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY); r = 1; if (!ms_contains(&c->watch, t)) r = ms_append(&c->watch, t); TUBE_ASSIGN(t, NULL); if (!r) return reply_serr(c, MSG_OUT_OF_MEMORY); reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used); break; case OP_IGNORE: name = c->cmd + CMD_IGNORE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; t = NULL; for (i = 0; i < c->watch.used; i++) { t = c->watch.items[i]; if (strncmp(t->name, name, MAX_TUBE_NAME_LEN) == 0) break; t = NULL; } if (t && c->watch.used < 2) return reply_msg(c, MSG_NOT_IGNORED); if (t) ms_remove(&c->watch, t); /* may free t if refcount => 0 */ t = NULL; reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used); break; case OP_QUIT: conn_close(c); break; case OP_PAUSE_TUBE: op_ct[type]++; r = read_tube_name(&name, c->cmd + CMD_PAUSE_TUBE_LEN, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); *delay_buf = '\0'; t = tube_find(name); if (!t) return reply_msg(c, MSG_NOTFOUND); t->deadline_at = now_usec() + delay; t->pause = delay; t->stat.pause_ct++; set_main_delay_timeout(); reply_line(c, STATE_SENDWORD, "PAUSED\r\n"); break; default: return reply_msg(c, MSG_UNKNOWN_COMMAND); } } Commit Message: Discard job body bytes if the job is too big. Previously, a malicious user could craft a job payload and inject beanstalk commands without the client application knowing. (An extra-careful client library could check the size of the job body before sending the put command, but most libraries do not do this, nor should they have to.) Reported by Graham Barr. CWE ID:
dispatch_cmd(conn c) { int r, i, timeout = -1; size_t z; unsigned int count; job j; unsigned char type; char *size_buf, *delay_buf, *ttr_buf, *pri_buf, *end_buf, *name; unsigned int pri, body_size; usec delay, ttr; uint64_t id; tube t = NULL; /* NUL-terminate this string so we can use strtol and friends */ c->cmd[c->cmd_len - 2] = '\0'; /* check for possible maliciousness */ if (strlen(c->cmd) != c->cmd_len - 2) { return reply_msg(c, MSG_BAD_FORMAT); } type = which_cmd(c); dprintf("got %s command: \"%s\"\n", op_names[(int) type], c->cmd); switch (type) { case OP_PUT: r = read_pri(&pri, c->cmd + 4, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, &ttr_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_ttr(&ttr, ttr_buf, &size_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); errno = 0; body_size = strtoul(size_buf, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); if (body_size > job_data_size_limit) { /* throw away the job body and respond with JOB_TOO_BIG */ return skip(c, body_size + 2, MSG_JOB_TOO_BIG); } /* don't allow trailing garbage */ if (end_buf[0] != '\0') return reply_msg(c, MSG_BAD_FORMAT); conn_set_producer(c); c->in_job = make_job(pri, delay, ttr ? : 1, body_size + 2, c->use); /* OOM? */ if (!c->in_job) { /* throw away the job body and respond with OUT_OF_MEMORY */ twarnx("server error: " MSG_OUT_OF_MEMORY); return skip(c, body_size + 2, MSG_OUT_OF_MEMORY); } fill_extra_data(c); /* it's possible we already have a complete job */ maybe_enqueue_incoming_job(c); break; case OP_PEEK_READY: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_READY_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(pq_peek(&c->use->ready)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEK_DELAYED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_DELAYED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(pq_peek(&c->use->delay)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEK_BURIED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_BURIED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(buried_job_p(c->use)? j = c->use->buried.next : NULL); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEKJOB: errno = 0; id = strtoull(c->cmd + CMD_PEEKJOB_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; /* So, peek is annoying, because some other connection might free the * job while we are still trying to write it out. So we copy it and * then free the copy when it's done sending. */ j = job_copy(peek_job(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_RESERVE_TIMEOUT: errno = 0; timeout = strtol(c->cmd + CMD_RESERVE_TIMEOUT_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); case OP_RESERVE: /* FALLTHROUGH */ /* don't allow trailing garbage */ if (type == OP_RESERVE && c->cmd_len != CMD_RESERVE_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; conn_set_worker(c); if (conn_has_close_deadline(c) && !conn_ready(c)) { return reply_msg(c, MSG_DEADLINE_SOON); } /* try to get a new job for this guy */ wait_for_job(c, timeout); process_queue(); break; case OP_DELETE: errno = 0; id = strtoull(c->cmd + CMD_DELETE_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = job_find(id); j = remove_reserved_job(c, j) ? : remove_ready_job(j) ? : remove_buried_job(j); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); j->state = JOB_STATE_INVALID; r = binlog_write_job(j); job_free(j); if (!r) return reply_serr(c, MSG_INTERNAL_ERROR); reply(c, MSG_DELETED, MSG_DELETED_LEN, STATE_SENDWORD); break; case OP_RELEASE: errno = 0; id = strtoull(c->cmd + CMD_RELEASE_LEN, &pri_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); r = read_pri(&pri, pri_buf, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = remove_reserved_job(c, job_find(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); /* We want to update the delay deadline on disk, so reserve space for * that. */ if (delay) { z = binlog_reserve_space_update(j); if (!z) return reply_serr(c, MSG_OUT_OF_MEMORY); j->reserved_binlog_space += z; } j->pri = pri; j->delay = delay; j->release_ct++; r = enqueue_job(j, delay, !!delay); if (r < 0) return reply_serr(c, MSG_INTERNAL_ERROR); if (r == 1) { return reply(c, MSG_RELEASED, MSG_RELEASED_LEN, STATE_SENDWORD); } /* out of memory trying to grow the queue, so it gets buried */ bury_job(j, 0); reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD); break; case OP_BURY: errno = 0; id = strtoull(c->cmd + CMD_BURY_LEN, &pri_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); r = read_pri(&pri, pri_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = remove_reserved_job(c, job_find(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); j->pri = pri; r = bury_job(j, 1); if (!r) return reply_serr(c, MSG_INTERNAL_ERROR); reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD); break; case OP_KICK: errno = 0; count = strtoul(c->cmd + CMD_KICK_LEN, &end_buf, 10); if (end_buf == c->cmd + CMD_KICK_LEN) { return reply_msg(c, MSG_BAD_FORMAT); } if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; i = kick_jobs(c->use, count); return reply_line(c, STATE_SENDWORD, "KICKED %u\r\n", i); case OP_TOUCH: errno = 0; id = strtoull(c->cmd + CMD_TOUCH_LEN, &end_buf, 10); if (errno) return twarn("strtoull"), reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = touch_job(c, job_find(id)); if (j) { reply(c, MSG_TOUCHED, MSG_TOUCHED_LEN, STATE_SENDWORD); } else { return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); } break; case OP_STATS: /* don't allow trailing garbage */ if (c->cmd_len != CMD_STATS_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_stats(c, fmt_stats, NULL); break; case OP_JOBSTATS: errno = 0; id = strtoull(c->cmd + CMD_JOBSTATS_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = peek_job(id); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); if (!j->tube) return reply_serr(c, MSG_INTERNAL_ERROR); do_stats(c, (fmt_fn) fmt_job_stats, j); break; case OP_STATS_TUBE: name = c->cmd + CMD_STATS_TUBE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; t = tube_find(name); if (!t) return reply_msg(c, MSG_NOTFOUND); do_stats(c, (fmt_fn) fmt_stats_tube, t); t = NULL; break; case OP_LIST_TUBES: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBES_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_list_tubes(c, &tubes); break; case OP_LIST_TUBE_USED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBE_USED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name); break; case OP_LIST_TUBES_WATCHED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBES_WATCHED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_list_tubes(c, &c->watch); break; case OP_USE: name = c->cmd + CMD_USE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; TUBE_ASSIGN(t, tube_find_or_make(name)); if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY); c->use->using_ct--; TUBE_ASSIGN(c->use, t); TUBE_ASSIGN(t, NULL); c->use->using_ct++; reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name); break; case OP_WATCH: name = c->cmd + CMD_WATCH_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; TUBE_ASSIGN(t, tube_find_or_make(name)); if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY); r = 1; if (!ms_contains(&c->watch, t)) r = ms_append(&c->watch, t); TUBE_ASSIGN(t, NULL); if (!r) return reply_serr(c, MSG_OUT_OF_MEMORY); reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used); break; case OP_IGNORE: name = c->cmd + CMD_IGNORE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; t = NULL; for (i = 0; i < c->watch.used; i++) { t = c->watch.items[i]; if (strncmp(t->name, name, MAX_TUBE_NAME_LEN) == 0) break; t = NULL; } if (t && c->watch.used < 2) return reply_msg(c, MSG_NOT_IGNORED); if (t) ms_remove(&c->watch, t); /* may free t if refcount => 0 */ t = NULL; reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used); break; case OP_QUIT: conn_close(c); break; case OP_PAUSE_TUBE: op_ct[type]++; r = read_tube_name(&name, c->cmd + CMD_PAUSE_TUBE_LEN, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); *delay_buf = '\0'; t = tube_find(name); if (!t) return reply_msg(c, MSG_NOTFOUND); t->deadline_at = now_usec() + delay; t->pause = delay; t->stat.pause_ct++; set_main_delay_timeout(); reply_line(c, STATE_SENDWORD, "PAUSED\r\n"); break; default: return reply_msg(c, MSG_UNKNOWN_COMMAND); } }
165,515
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode, ext4_lblk_t iblock, unsigned int max_blocks, struct ext4_ext_path *path, int flags, unsigned int allocated, struct buffer_head *bh_result, ext4_fsblk_t newblock) { int ret = 0; int err = 0; ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio; ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical" "block %llu, max_blocks %u, flags %d, allocated %u", inode->i_ino, (unsigned long long)iblock, max_blocks, flags, allocated); ext4_ext_show_leaf(inode, path); /* get_block() before submit the IO, split the extent */ if (flags == EXT4_GET_BLOCKS_PRE_IO) { ret = ext4_split_unwritten_extents(handle, inode, path, iblock, max_blocks, flags); /* * Flag the inode(non aio case) or end_io struct (aio case) * that this IO needs to convertion to written when IO is * completed */ if (io) io->flag = EXT4_IO_UNWRITTEN; else ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); goto out; } /* IO end_io complete, convert the filled extent to written */ if (flags == EXT4_GET_BLOCKS_CONVERT) { ret = ext4_convert_unwritten_extents_endio(handle, inode, path); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); goto out2; } /* buffered IO case */ /* * repeat fallocate creation request * we already have an unwritten extent */ if (flags & EXT4_GET_BLOCKS_UNINIT_EXT) goto map_out; /* buffered READ or buffered write_begin() lookup */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * We have blocks reserved already. We * return allocated blocks so that delalloc * won't do block reservation for us. But * the buffer head will be unmapped so that * a read from the block returns 0s. */ set_buffer_unwritten(bh_result); goto out1; } /* buffered write, writepage time, convert*/ ret = ext4_ext_convert_to_initialized(handle, inode, path, iblock, max_blocks); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); out: if (ret <= 0) { err = ret; goto out2; } else allocated = ret; set_buffer_new(bh_result); /* * if we allocated more blocks than requested * we need to make sure we unmap the extra block * allocated. The actual needed block will get * unmapped later when we find the buffer_head marked * new. */ if (allocated > max_blocks) { unmap_underlying_metadata_blocks(inode->i_sb->s_bdev, newblock + max_blocks, allocated - max_blocks); allocated = max_blocks; } /* * If we have done fallocate with the offset that is already * delayed allocated, we would have block reservation * and quota reservation done in the delayed write path. * But fallocate would have already updated quota and block * count for this offset. So cancel these reservation */ if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) ext4_da_update_reserve_space(inode, allocated, 0); map_out: set_buffer_mapped(bh_result); out1: if (allocated > max_blocks) allocated = max_blocks; ext4_ext_show_leaf(inode, path); bh_result->b_bdev = inode->i_sb->s_bdev; bh_result->b_blocknr = newblock; out2: if (path) { ext4_ext_drop_refs(path); kfree(path); } return err ? err : allocated; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode, ext4_lblk_t iblock, unsigned int max_blocks, struct ext4_ext_path *path, int flags, unsigned int allocated, struct buffer_head *bh_result, ext4_fsblk_t newblock) { int ret = 0; int err = 0; ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio; ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical" "block %llu, max_blocks %u, flags %d, allocated %u", inode->i_ino, (unsigned long long)iblock, max_blocks, flags, allocated); ext4_ext_show_leaf(inode, path); /* get_block() before submit the IO, split the extent */ if ((flags & EXT4_GET_BLOCKS_PRE_IO)) { ret = ext4_split_unwritten_extents(handle, inode, path, iblock, max_blocks, flags); /* * Flag the inode(non aio case) or end_io struct (aio case) * that this IO needs to convertion to written when IO is * completed */ if (io) io->flag = EXT4_IO_UNWRITTEN; else ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); if (ext4_should_dioread_nolock(inode)) set_buffer_uninit(bh_result); goto out; } /* IO end_io complete, convert the filled extent to written */ if ((flags & EXT4_GET_BLOCKS_CONVERT)) { ret = ext4_convert_unwritten_extents_endio(handle, inode, path); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); goto out2; } /* buffered IO case */ /* * repeat fallocate creation request * we already have an unwritten extent */ if (flags & EXT4_GET_BLOCKS_UNINIT_EXT) goto map_out; /* buffered READ or buffered write_begin() lookup */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * We have blocks reserved already. We * return allocated blocks so that delalloc * won't do block reservation for us. But * the buffer head will be unmapped so that * a read from the block returns 0s. */ set_buffer_unwritten(bh_result); goto out1; } /* buffered write, writepage time, convert*/ ret = ext4_ext_convert_to_initialized(handle, inode, path, iblock, max_blocks); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); out: if (ret <= 0) { err = ret; goto out2; } else allocated = ret; set_buffer_new(bh_result); /* * if we allocated more blocks than requested * we need to make sure we unmap the extra block * allocated. The actual needed block will get * unmapped later when we find the buffer_head marked * new. */ if (allocated > max_blocks) { unmap_underlying_metadata_blocks(inode->i_sb->s_bdev, newblock + max_blocks, allocated - max_blocks); allocated = max_blocks; } /* * If we have done fallocate with the offset that is already * delayed allocated, we would have block reservation * and quota reservation done in the delayed write path. * But fallocate would have already updated quota and block * count for this offset. So cancel these reservation */ if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) ext4_da_update_reserve_space(inode, allocated, 0); map_out: set_buffer_mapped(bh_result); out1: if (allocated > max_blocks) allocated = max_blocks; ext4_ext_show_leaf(inode, path); bh_result->b_bdev = inode->i_sb->s_bdev; bh_result->b_blocknr = newblock; out2: if (path) { ext4_ext_drop_refs(path); kfree(path); } return err ? err : allocated; }
167,537
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long mkvparser::ParseElementHeader( IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume length of size if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; //success } 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 mkvparser::ParseElementHeader( long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size // pos now designates payload if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; // success }
174,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags, struct rt6_info *rt) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; } err = skb_append_datato_frags(sk,skb, getfrag, from, (length - transhdrlen)); if (!err) { struct frag_hdr fhdr; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr, rt); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); return 0; } /* There is not enough support do UPD LSO, * so follow normal path */ kfree_skb(skb); return err; } Commit Message: ipv6: udp packets following an UFO enqueued packet need also be handled by UFO In the following scenario the socket is corked: If the first UDP packet is larger then the mtu we try to append it to the write queue via ip6_ufo_append_data. A following packet, which is smaller than the mtu would be appended to the already queued up gso-skb via plain ip6_append_data. This causes random memory corruptions. In ip6_ufo_append_data we also have to be careful to not queue up the same skb multiple times. So setup the gso frame only when no first skb is available. This also fixes a shortcoming where we add the current packet's length to cork->length but return early because of a packet > mtu with dontfrag set (instead of sutracting it again). Found with trinity. Cc: YOSHIFUJI Hideaki <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags, struct rt6_info *rt) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { struct frag_hdr fhdr; skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr, rt); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); } return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); }
165,988
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: krb5_ldap_put_principal(krb5_context context, krb5_db_entry *entry, char **db_args) { int l=0, kerberos_principal_object_type=0; unsigned int ntrees=0, tre=0; krb5_error_code st=0, tempst=0; LDAP *ld=NULL; LDAPMessage *result=NULL, *ent=NULL; char **subtreelist = NULL; char *user=NULL, *subtree=NULL, *principal_dn=NULL; char **values=NULL, *strval[10]={NULL}, errbuf[1024]; char *filtuser=NULL; struct berval **bersecretkey=NULL; LDAPMod **mods=NULL; krb5_boolean create_standalone=FALSE; krb5_boolean krb_identity_exists=FALSE, establish_links=FALSE; char *standalone_principal_dn=NULL; krb5_tl_data *tl_data=NULL; krb5_key_data **keys=NULL; kdb5_dal_handle *dal_handle=NULL; krb5_ldap_context *ldap_context=NULL; krb5_ldap_server_handle *ldap_server_handle=NULL; osa_princ_ent_rec princ_ent = {0}; xargs_t xargs = {0}; char *polname = NULL; OPERATION optype; krb5_boolean found_entry = FALSE; /* Clear the global error string */ krb5_clear_error_message(context); SETUP_CONTEXT(); if (ldap_context->lrparams == NULL || ldap_context->container_dn == NULL) return EINVAL; /* get ldap handle */ GET_HANDLE(); if (!is_principal_in_realm(ldap_context, entry->princ)) { st = EINVAL; k5_setmsg(context, st, _("Principal does not belong to the default realm")); goto cleanup; } /* get the principal information to act on */ if (((st=krb5_unparse_name(context, entry->princ, &user)) != 0) || ((st=krb5_ldap_unparse_principal_name(user)) != 0)) goto cleanup; filtuser = ldap_filter_correct(user); if (filtuser == NULL) { st = ENOMEM; goto cleanup; } /* Identity the type of operation, it can be * add principal or modify principal. * hack if the entry->mask has KRB_PRINCIPAL flag set * then it is a add operation */ if (entry->mask & KADM5_PRINCIPAL) optype = ADD_PRINCIPAL; else optype = MODIFY_PRINCIPAL; if (((st=krb5_get_princ_type(context, entry, &kerberos_principal_object_type)) != 0) || ((st=krb5_get_userdn(context, entry, &principal_dn)) != 0)) goto cleanup; if ((st=process_db_args(context, db_args, &xargs, optype)) != 0) goto cleanup; if (entry->mask & KADM5_LOAD) { unsigned int tree = 0; int numlentries = 0; char *filter = NULL; /* A load operation is special, will do a mix-in (add krbprinc * attrs to a non-krb object entry) if an object exists with a * matching krbprincipalname attribute so try to find existing * object and set principal_dn. This assumes that the * krbprincipalname attribute is unique (only one object entry has * a particular krbprincipalname attribute). */ if (asprintf(&filter, FILTER"%s))", filtuser) < 0) { filter = NULL; st = ENOMEM; goto cleanup; } /* get the current subtree list */ if ((st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees)) != 0) goto cleanup; found_entry = FALSE; /* search for entry with matching krbprincipalname attribute */ for (tree = 0; found_entry == FALSE && tree < ntrees; ++tree) { if (principal_dn == NULL) { LDAP_SEARCH_1(subtreelist[tree], ldap_context->lrparams->search_scope, filter, principal_attributes, IGNORE_STATUS); } else { /* just look for entry with principal_dn */ LDAP_SEARCH_1(principal_dn, LDAP_SCOPE_BASE, filter, principal_attributes, IGNORE_STATUS); } if (st == LDAP_SUCCESS) { numlentries = ldap_count_entries(ld, result); if (numlentries > 1) { free(filter); st = EINVAL; k5_setmsg(context, st, _("operation can not continue, more than one " "entry with principal name \"%s\" found"), user); goto cleanup; } else if (numlentries == 1) { found_entry = TRUE; if (principal_dn == NULL) { ent = ldap_first_entry(ld, result); if (ent != NULL) { /* setting principal_dn will cause that entry to be modified further down */ if ((principal_dn = ldap_get_dn(ld, ent)) == NULL) { ldap_get_option (ld, LDAP_OPT_RESULT_CODE, &st); st = set_ldap_error (context, st, 0); free(filter); goto cleanup; } } } } } else if (st != LDAP_NO_SUCH_OBJECT) { /* could not perform search, return with failure */ st = set_ldap_error (context, st, 0); free(filter); goto cleanup; } ldap_msgfree(result); result = NULL; /* * If it isn't found then assume a standalone princ entry is to * be created. */ } /* end for (tree = 0; principal_dn == ... */ free(filter); if (found_entry == FALSE && principal_dn != NULL) { /* * if principal_dn is null then there is code further down to * deal with setting standalone_principal_dn. Also note that * this will set create_standalone true for * non-mix-in entries which is okay if loading from a dump. */ create_standalone = TRUE; standalone_principal_dn = strdup(principal_dn); CHECK_NULL(standalone_principal_dn); } } /* end if (entry->mask & KADM5_LOAD */ /* time to generate the DN information with the help of * containerdn, principalcontainerreference or * realmcontainerdn information */ if (principal_dn == NULL && xargs.dn == NULL) { /* creation of standalone principal */ /* get the subtree information */ if (entry->princ->length == 2 && entry->princ->data[0].length == strlen("krbtgt") && strncmp(entry->princ->data[0].data, "krbtgt", entry->princ->data[0].length) == 0) { /* if the principal is a inter-realm principal, always created in the realm container */ subtree = strdup(ldap_context->lrparams->realmdn); } else if (xargs.containerdn) { if ((st=checkattributevalue(ld, xargs.containerdn, NULL, NULL, NULL)) != 0) { if (st == KRB5_KDB_NOENTRY || st == KRB5_KDB_CONSTRAINT_VIOLATION) { int ost = st; st = EINVAL; k5_wrapmsg(context, ost, st, _("'%s' not found"), xargs.containerdn); } goto cleanup; } subtree = strdup(xargs.containerdn); } else if (ldap_context->lrparams->containerref && strlen(ldap_context->lrparams->containerref) != 0) { /* * Here the subtree should be changed with * principalcontainerreference attribute value */ subtree = strdup(ldap_context->lrparams->containerref); } else { subtree = strdup(ldap_context->lrparams->realmdn); } CHECK_NULL(subtree); if (asprintf(&standalone_principal_dn, "krbprincipalname=%s,%s", filtuser, subtree) < 0) standalone_principal_dn = NULL; CHECK_NULL(standalone_principal_dn); /* * free subtree when you are done using the subtree * set the boolean create_standalone to TRUE */ create_standalone = TRUE; free(subtree); subtree = NULL; } /* * If the DN information is presented by the user, time to * validate the input to ensure that the DN falls under * any of the subtrees */ if (xargs.dn_from_kbd == TRUE) { /* make sure the DN falls in the subtree */ int dnlen=0, subtreelen=0; char *dn=NULL; krb5_boolean outofsubtree=TRUE; if (xargs.dn != NULL) { dn = xargs.dn; } else if (xargs.linkdn != NULL) { dn = xargs.linkdn; } else if (standalone_principal_dn != NULL) { /* * Even though the standalone_principal_dn is constructed * within this function, there is the containerdn input * from the user that can become part of the it. */ dn = standalone_principal_dn; } /* Get the current subtree list if we haven't already done so. */ if (subtreelist == NULL) { st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees); if (st) goto cleanup; } for (tre=0; tre<ntrees; ++tre) { if (subtreelist[tre] == NULL || strlen(subtreelist[tre]) == 0) { outofsubtree = FALSE; break; } else { dnlen = strlen (dn); subtreelen = strlen(subtreelist[tre]); if ((dnlen >= subtreelen) && (strcasecmp((dn + dnlen - subtreelen), subtreelist[tre]) == 0)) { outofsubtree = FALSE; break; } } } if (outofsubtree == TRUE) { st = EINVAL; k5_setmsg(context, st, _("DN is out of the realm subtree")); goto cleanup; } /* * dn value will be set either by dn, linkdn or the standalone_principal_dn * In the first 2 cases, the dn should be existing and in the last case we * are supposed to create the ldap object. so the below should not be * executed for the last case. */ if (standalone_principal_dn == NULL) { /* * If the ldap object is missing, this results in an error. */ /* * Search for krbprincipalname attribute here. * This is to find if a kerberos identity is already present * on the ldap object, in which case adding a kerberos identity * on the ldap object should result in an error. */ char *attributes[]={"krbticketpolicyreference", "krbprincipalname", NULL}; ldap_msgfree(result); result = NULL; LDAP_SEARCH_1(dn, LDAP_SCOPE_BASE, 0, attributes, IGNORE_STATUS); if (st == LDAP_SUCCESS) { ent = ldap_first_entry(ld, result); if (ent != NULL) { if ((values=ldap_get_values(ld, ent, "krbticketpolicyreference")) != NULL) { ldap_value_free(values); } if ((values=ldap_get_values(ld, ent, "krbprincipalname")) != NULL) { krb_identity_exists = TRUE; ldap_value_free(values); } } } else { st = set_ldap_error(context, st, OP_SEARCH); goto cleanup; } } } /* * If xargs.dn is set then the request is to add a * kerberos principal on a ldap object, but if * there is one already on the ldap object this * should result in an error. */ if (xargs.dn != NULL && krb_identity_exists == TRUE) { st = EINVAL; snprintf(errbuf, sizeof(errbuf), _("ldap object is already kerberized")); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } if (xargs.linkdn != NULL) { /* * link information can be changed using modprinc. * However, link information can be changed only on the * standalone kerberos principal objects. A standalone * kerberos principal object is of type krbprincipal * structural objectclass. * * NOTE: kerberos principals on an ldap object can't be * linked to other ldap objects. */ if (optype == MODIFY_PRINCIPAL && kerberos_principal_object_type != KDB_STANDALONE_PRINCIPAL_OBJECT) { st = EINVAL; snprintf(errbuf, sizeof(errbuf), _("link information can not be set/updated as the " "kerberos principal belongs to an ldap object")); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } /* * Check the link information. If there is already a link * existing then this operation is not allowed. */ { char **linkdns=NULL; int j=0; if ((st=krb5_get_linkdn(context, entry, &linkdns)) != 0) { snprintf(errbuf, sizeof(errbuf), _("Failed getting object references")); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } if (linkdns != NULL) { st = EINVAL; snprintf(errbuf, sizeof(errbuf), _("kerberos principal is already linked to a ldap " "object")); k5_setmsg(context, st, "%s", errbuf); for (j=0; linkdns[j] != NULL; ++j) free (linkdns[j]); free (linkdns); goto cleanup; } } establish_links = TRUE; } if (entry->mask & KADM5_LAST_SUCCESS) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->last_success)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastSuccessfulAuth", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_LAST_FAILED) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->last_failed)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastFailedAuth", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free(strval[0]); } if (entry->mask & KADM5_FAIL_AUTH_COUNT) { krb5_kvno fail_auth_count; fail_auth_count = entry->fail_auth_count; if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) fail_auth_count++; st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_REPLACE, fail_auth_count); if (st != 0) goto cleanup; } else if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) { int attr_mask = 0; krb5_boolean has_fail_count; /* Check if the krbLoginFailedCount attribute exists. (Through * krb5 1.8.1, it wasn't set in new entries.) */ st = krb5_get_attributes_mask(context, entry, &attr_mask); if (st != 0) goto cleanup; has_fail_count = ((attr_mask & KDB_FAIL_AUTH_COUNT_ATTR) != 0); /* * If the client library and server supports RFC 4525, * then use it to increment by one the value of the * krbLoginFailedCount attribute. Otherwise, assert the * (provided) old value by deleting it before adding. */ #ifdef LDAP_MOD_INCREMENT if (ldap_server_handle->server_info->modify_increment && has_fail_count) { st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_INCREMENT, 1); if (st != 0) goto cleanup; } else { #endif /* LDAP_MOD_INCREMENT */ if (has_fail_count) { st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_DELETE, entry->fail_auth_count); if (st != 0) goto cleanup; } st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_ADD, entry->fail_auth_count + 1); if (st != 0) goto cleanup; #ifdef LDAP_MOD_INCREMENT } #endif } else if (optype == ADD_PRINCIPAL) { /* Initialize krbLoginFailedCount in new entries to help avoid a * race during the first failed login. */ st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_ADD, 0); } if (entry->mask & KADM5_MAX_LIFE) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxticketlife", LDAP_MOD_REPLACE, entry->max_life)) != 0) goto cleanup; } if (entry->mask & KADM5_MAX_RLIFE) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxrenewableage", LDAP_MOD_REPLACE, entry->max_renewable_life)) != 0) goto cleanup; } if (entry->mask & KADM5_ATTRIBUTES) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbticketflags", LDAP_MOD_REPLACE, entry->attributes)) != 0) goto cleanup; } if (entry->mask & KADM5_PRINCIPAL) { memset(strval, 0, sizeof(strval)); strval[0] = user; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalname", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } if (entry->mask & KADM5_PRINC_EXPIRE_TIME) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_PW_EXPIRATION) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpasswordexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_POLICY || entry->mask & KADM5_KEY_HIST) { memset(&princ_ent, 0, sizeof(princ_ent)); for (tl_data=entry->tl_data; tl_data; tl_data=tl_data->tl_data_next) { if (tl_data->tl_data_type == KRB5_TL_KADM_DATA) { if ((st = krb5_lookup_tl_kadm_data(tl_data, &princ_ent)) != 0) { goto cleanup; } break; } } } if (entry->mask & KADM5_POLICY) { if (princ_ent.aux_attributes & KADM5_POLICY) { memset(strval, 0, sizeof(strval)); if ((st = krb5_ldap_name_to_policydn (context, princ_ent.policy, &polname)) != 0) goto cleanup; strval[0] = polname; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } else { st = EINVAL; k5_setmsg(context, st, "Password policy value null"); goto cleanup; } } else if (entry->mask & KADM5_LOAD && found_entry == TRUE) { /* * a load is special in that existing entries must have attrs that * removed. */ if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, NULL)) != 0) goto cleanup; } if (entry->mask & KADM5_POLICY_CLR) { if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_DELETE, NULL)) != 0) goto cleanup; } if (entry->mask & KADM5_KEY_HIST) { bersecretkey = krb5_encode_histkey(&princ_ent); if (bersecretkey == NULL) { st = ENOMEM; goto cleanup; } st = krb5_add_ber_mem_ldap_mod(&mods, "krbpwdhistory", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, bersecretkey); if (st != 0) goto cleanup; free_berdata(bersecretkey); bersecretkey = NULL; } if (entry->mask & KADM5_KEY_DATA || entry->mask & KADM5_KVNO) { krb5_kvno mkvno; if ((st=krb5_dbe_lookup_mkvno(context, entry, &mkvno)) != 0) goto cleanup; bersecretkey = krb5_encode_krbsecretkey (entry->key_data, entry->n_key_data, mkvno); if (bersecretkey == NULL) { st = ENOMEM; goto cleanup; } /* An empty list of bervals is only accepted for modify operations, * not add operations. */ if (bersecretkey[0] != NULL || !create_standalone) { st = krb5_add_ber_mem_ldap_mod(&mods, "krbprincipalkey", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, bersecretkey); if (st != 0) goto cleanup; } if (!(entry->mask & KADM5_PRINCIPAL)) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpasswordexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } /* Update last password change whenever a new key is set */ { krb5_timestamp last_pw_changed; if ((st=krb5_dbe_lookup_last_pwd_change(context, entry, &last_pw_changed)) != 0) goto cleanup; memset(strval, 0, sizeof(strval)); if ((strval[0] = getstringtime(last_pw_changed)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastPwdChange", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } } /* Modify Key data ends here */ /* Auth indicators will also be stored in krbExtraData when processing * tl_data. */ st = update_ldap_mod_auth_ind(context, entry, &mods); if (st != 0) goto cleanup; /* Set tl_data */ if (entry->tl_data != NULL) { int count = 0; struct berval **ber_tl_data = NULL; krb5_tl_data *ptr; krb5_timestamp unlock_time; for (ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) { if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE #ifdef SECURID || ptr->tl_data_type == KRB5_TL_DB_ARGS #endif || ptr->tl_data_type == KRB5_TL_KADM_DATA || ptr->tl_data_type == KDB_TL_USER_INFO || ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL || ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK) continue; count++; } if (count != 0) { int j; ber_tl_data = (struct berval **) calloc (count + 1, sizeof (struct berval*)); if (ber_tl_data == NULL) { st = ENOMEM; goto cleanup; } for (j = 0, ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) { /* Ignore tl_data that are stored in separate directory * attributes */ if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE #ifdef SECURID || ptr->tl_data_type == KRB5_TL_DB_ARGS #endif || ptr->tl_data_type == KRB5_TL_KADM_DATA || ptr->tl_data_type == KDB_TL_USER_INFO || ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL || ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK) continue; if ((st = tl_data2berval (ptr, &ber_tl_data[j])) != 0) break; j++; } if (st == 0) { ber_tl_data[count] = NULL; st=krb5_add_ber_mem_ldap_mod(&mods, "krbExtraData", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, ber_tl_data); } free_berdata(ber_tl_data); if (st != 0) goto cleanup; } if ((st=krb5_dbe_lookup_last_admin_unlock(context, entry, &unlock_time)) != 0) goto cleanup; if (unlock_time != 0) { /* Update last admin unlock */ memset(strval, 0, sizeof(strval)); if ((strval[0] = getstringtime(unlock_time)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastAdminUnlock", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } } /* Directory specific attribute */ if (xargs.tktpolicydn != NULL) { int tmask=0; if (strlen(xargs.tktpolicydn) != 0) { st = checkattributevalue(ld, xargs.tktpolicydn, "objectclass", policyclass, &tmask); CHECK_CLASS_VALIDITY(st, tmask, _("ticket policy object value: ")); strval[0] = xargs.tktpolicydn; strval[1] = NULL; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } else { /* if xargs.tktpolicydn is a empty string, then delete * already existing krbticketpolicyreference attr */ if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_DELETE, NULL)) != 0) goto cleanup; } } if (establish_links == TRUE) { memset(strval, 0, sizeof(strval)); strval[0] = xargs.linkdn; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbObjectReferences", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } /* * in case mods is NULL then return * not sure but can happen in a modprinc * so no need to return an error * addprinc will at least have the principal name * and the keys passed in */ if (mods == NULL) goto cleanup; if (create_standalone == TRUE) { memset(strval, 0, sizeof(strval)); strval[0] = "krbprincipal"; strval[1] = "krbprincipalaux"; strval[2] = "krbTicketPolicyAux"; if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0) goto cleanup; st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL); if (st == LDAP_ALREADY_EXISTS && entry->mask & KADM5_LOAD) { /* a load operation must replace an existing entry */ st = ldap_delete_ext_s(ld, standalone_principal_dn, NULL, NULL); if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("Principal delete failed (trying to replace " "entry): %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_ADD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } else { st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL); } } if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("Principal add failed: %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_ADD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } } else { /* * Here existing ldap object is modified and can be related * to any attribute, so always ensure that the ldap * object is extended with all the kerberos related * objectclasses so that there are no constraint * violations. */ { char *attrvalues[] = {"krbprincipalaux", "krbTicketPolicyAux", NULL}; int p, q, r=0, amask=0; if ((st=checkattributevalue(ld, (xargs.dn) ? xargs.dn : principal_dn, "objectclass", attrvalues, &amask)) != 0) goto cleanup; memset(strval, 0, sizeof(strval)); for (p=1, q=0; p<=2; p<<=1, ++q) { if ((p & amask) == 0) strval[r++] = attrvalues[q]; } if (r != 0) { if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0) goto cleanup; } } if (xargs.dn != NULL) st=ldap_modify_ext_s(ld, xargs.dn, mods, NULL, NULL); else st = ldap_modify_ext_s(ld, principal_dn, mods, NULL, NULL); if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("User modification failed: %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_MOD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) entry->fail_auth_count++; } cleanup: if (user) free(user); if (filtuser) free(filtuser); free_xargs(xargs); if (standalone_principal_dn) free(standalone_principal_dn); if (principal_dn) free (principal_dn); if (polname != NULL) free(polname); for (tre = 0; tre < ntrees; tre++) free(subtreelist[tre]); free(subtreelist); if (subtree) free (subtree); if (bersecretkey) { for (l=0; bersecretkey[l]; ++l) { if (bersecretkey[l]->bv_val) free (bersecretkey[l]->bv_val); free (bersecretkey[l]); } free (bersecretkey); } if (keys) free (keys); ldap_mods_free(mods, 1); ldap_osa_free_princ_ent(&princ_ent); ldap_msgfree(result); krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle); return(st); } Commit Message: Fix flaws in LDAP DN checking KDB_TL_USER_INFO tl-data is intended to be internal to the LDAP KDB module, and not used in disk or wire principal entries. Prevent kadmin clients from sending KDB_TL_USER_INFO tl-data by giving it a type number less than 256 and filtering out type numbers less than 256 in kadm5_create_principal_3(). (We already filter out low type numbers in kadm5_modify_principal()). In the LDAP KDB module, if containerdn and linkdn are both specified in a put_principal operation, check both linkdn and the computed standalone_principal_dn for container membership. To that end, factor out the checks into helper functions and call them on all applicable client-influenced DNs. CVE-2018-5729: In MIT krb5 1.6 or later, an authenticated kadmin user with permission to add principals to an LDAP Kerberos database can cause a null dereference in kadmind, or circumvent a DN container check, by supplying tagged data intended to be internal to the database module. Thanks to Sharwan Ram and Pooja Anil for discovering the potential null dereference. CVE-2018-5730: In MIT krb5 1.6 or later, an authenticated kadmin user with permission to add principals to an LDAP Kerberos database can circumvent a DN containership check by supplying both a "linkdn" and "containerdn" database argument, or by supplying a DN string which is a left extension of a container DN string but is not hierarchically within the container DN. ticket: 8643 (new) tags: pullup target_version: 1.16-next target_version: 1.15-next CWE ID: CWE-90
krb5_ldap_put_principal(krb5_context context, krb5_db_entry *entry, char **db_args) { int l=0, kerberos_principal_object_type=0; unsigned int ntrees=0, tre=0; krb5_error_code st=0, tempst=0; LDAP *ld=NULL; LDAPMessage *result=NULL, *ent=NULL; char **subtreelist = NULL; char *user=NULL, *subtree=NULL, *principal_dn=NULL; char *strval[10]={NULL}, errbuf[1024]; char *filtuser=NULL; struct berval **bersecretkey=NULL; LDAPMod **mods=NULL; krb5_boolean create_standalone=FALSE; krb5_boolean establish_links=FALSE; char *standalone_principal_dn=NULL; krb5_tl_data *tl_data=NULL; krb5_key_data **keys=NULL; kdb5_dal_handle *dal_handle=NULL; krb5_ldap_context *ldap_context=NULL; krb5_ldap_server_handle *ldap_server_handle=NULL; osa_princ_ent_rec princ_ent = {0}; xargs_t xargs = {0}; char *polname = NULL; OPERATION optype; krb5_boolean found_entry = FALSE; /* Clear the global error string */ krb5_clear_error_message(context); SETUP_CONTEXT(); if (ldap_context->lrparams == NULL || ldap_context->container_dn == NULL) return EINVAL; /* get ldap handle */ GET_HANDLE(); if (!is_principal_in_realm(ldap_context, entry->princ)) { st = EINVAL; k5_setmsg(context, st, _("Principal does not belong to the default realm")); goto cleanup; } /* get the principal information to act on */ if (((st=krb5_unparse_name(context, entry->princ, &user)) != 0) || ((st=krb5_ldap_unparse_principal_name(user)) != 0)) goto cleanup; filtuser = ldap_filter_correct(user); if (filtuser == NULL) { st = ENOMEM; goto cleanup; } /* Identity the type of operation, it can be * add principal or modify principal. * hack if the entry->mask has KRB_PRINCIPAL flag set * then it is a add operation */ if (entry->mask & KADM5_PRINCIPAL) optype = ADD_PRINCIPAL; else optype = MODIFY_PRINCIPAL; if (((st=krb5_get_princ_type(context, entry, &kerberos_principal_object_type)) != 0) || ((st=krb5_get_userdn(context, entry, &principal_dn)) != 0)) goto cleanup; if ((st=process_db_args(context, db_args, &xargs, optype)) != 0) goto cleanup; if (entry->mask & KADM5_LOAD) { unsigned int tree = 0; int numlentries = 0; char *filter = NULL; /* A load operation is special, will do a mix-in (add krbprinc * attrs to a non-krb object entry) if an object exists with a * matching krbprincipalname attribute so try to find existing * object and set principal_dn. This assumes that the * krbprincipalname attribute is unique (only one object entry has * a particular krbprincipalname attribute). */ if (asprintf(&filter, FILTER"%s))", filtuser) < 0) { filter = NULL; st = ENOMEM; goto cleanup; } /* get the current subtree list */ if ((st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees)) != 0) goto cleanup; found_entry = FALSE; /* search for entry with matching krbprincipalname attribute */ for (tree = 0; found_entry == FALSE && tree < ntrees; ++tree) { if (principal_dn == NULL) { LDAP_SEARCH_1(subtreelist[tree], ldap_context->lrparams->search_scope, filter, principal_attributes, IGNORE_STATUS); } else { /* just look for entry with principal_dn */ LDAP_SEARCH_1(principal_dn, LDAP_SCOPE_BASE, filter, principal_attributes, IGNORE_STATUS); } if (st == LDAP_SUCCESS) { numlentries = ldap_count_entries(ld, result); if (numlentries > 1) { free(filter); st = EINVAL; k5_setmsg(context, st, _("operation can not continue, more than one " "entry with principal name \"%s\" found"), user); goto cleanup; } else if (numlentries == 1) { found_entry = TRUE; if (principal_dn == NULL) { ent = ldap_first_entry(ld, result); if (ent != NULL) { /* setting principal_dn will cause that entry to be modified further down */ if ((principal_dn = ldap_get_dn(ld, ent)) == NULL) { ldap_get_option (ld, LDAP_OPT_RESULT_CODE, &st); st = set_ldap_error (context, st, 0); free(filter); goto cleanup; } } } } } else if (st != LDAP_NO_SUCH_OBJECT) { /* could not perform search, return with failure */ st = set_ldap_error (context, st, 0); free(filter); goto cleanup; } ldap_msgfree(result); result = NULL; /* * If it isn't found then assume a standalone princ entry is to * be created. */ } /* end for (tree = 0; principal_dn == ... */ free(filter); if (found_entry == FALSE && principal_dn != NULL) { /* * if principal_dn is null then there is code further down to * deal with setting standalone_principal_dn. Also note that * this will set create_standalone true for * non-mix-in entries which is okay if loading from a dump. */ create_standalone = TRUE; standalone_principal_dn = strdup(principal_dn); CHECK_NULL(standalone_principal_dn); } } /* end if (entry->mask & KADM5_LOAD */ /* time to generate the DN information with the help of * containerdn, principalcontainerreference or * realmcontainerdn information */ if (principal_dn == NULL && xargs.dn == NULL) { /* creation of standalone principal */ /* get the subtree information */ if (entry->princ->length == 2 && entry->princ->data[0].length == strlen("krbtgt") && strncmp(entry->princ->data[0].data, "krbtgt", entry->princ->data[0].length) == 0) { /* if the principal is a inter-realm principal, always created in the realm container */ subtree = strdup(ldap_context->lrparams->realmdn); } else if (xargs.containerdn) { if ((st=checkattributevalue(ld, xargs.containerdn, NULL, NULL, NULL)) != 0) { if (st == KRB5_KDB_NOENTRY || st == KRB5_KDB_CONSTRAINT_VIOLATION) { int ost = st; st = EINVAL; k5_wrapmsg(context, ost, st, _("'%s' not found"), xargs.containerdn); } goto cleanup; } subtree = strdup(xargs.containerdn); } else if (ldap_context->lrparams->containerref && strlen(ldap_context->lrparams->containerref) != 0) { /* * Here the subtree should be changed with * principalcontainerreference attribute value */ subtree = strdup(ldap_context->lrparams->containerref); } else { subtree = strdup(ldap_context->lrparams->realmdn); } CHECK_NULL(subtree); if (asprintf(&standalone_principal_dn, "krbprincipalname=%s,%s", filtuser, subtree) < 0) standalone_principal_dn = NULL; CHECK_NULL(standalone_principal_dn); /* * free subtree when you are done using the subtree * set the boolean create_standalone to TRUE */ create_standalone = TRUE; free(subtree); subtree = NULL; } /* * If the DN information is presented by the user, time to * validate the input to ensure that the DN falls under * any of the subtrees */ if (xargs.dn_from_kbd == TRUE) { /* Get the current subtree list if we haven't already done so. */ if (subtreelist == NULL) { st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees); if (st) goto cleanup; } st = validate_xargs(context, ldap_server_handle, &xargs, standalone_principal_dn, subtreelist, ntrees); if (st) goto cleanup; } if (xargs.linkdn != NULL) { /* * link information can be changed using modprinc. * However, link information can be changed only on the * standalone kerberos principal objects. A standalone * kerberos principal object is of type krbprincipal * structural objectclass. * * NOTE: kerberos principals on an ldap object can't be * linked to other ldap objects. */ if (optype == MODIFY_PRINCIPAL && kerberos_principal_object_type != KDB_STANDALONE_PRINCIPAL_OBJECT) { st = EINVAL; snprintf(errbuf, sizeof(errbuf), _("link information can not be set/updated as the " "kerberos principal belongs to an ldap object")); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } /* * Check the link information. If there is already a link * existing then this operation is not allowed. */ { char **linkdns=NULL; int j=0; if ((st=krb5_get_linkdn(context, entry, &linkdns)) != 0) { snprintf(errbuf, sizeof(errbuf), _("Failed getting object references")); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } if (linkdns != NULL) { st = EINVAL; snprintf(errbuf, sizeof(errbuf), _("kerberos principal is already linked to a ldap " "object")); k5_setmsg(context, st, "%s", errbuf); for (j=0; linkdns[j] != NULL; ++j) free (linkdns[j]); free (linkdns); goto cleanup; } } establish_links = TRUE; } if (entry->mask & KADM5_LAST_SUCCESS) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->last_success)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastSuccessfulAuth", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_LAST_FAILED) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->last_failed)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastFailedAuth", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free(strval[0]); } if (entry->mask & KADM5_FAIL_AUTH_COUNT) { krb5_kvno fail_auth_count; fail_auth_count = entry->fail_auth_count; if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) fail_auth_count++; st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_REPLACE, fail_auth_count); if (st != 0) goto cleanup; } else if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) { int attr_mask = 0; krb5_boolean has_fail_count; /* Check if the krbLoginFailedCount attribute exists. (Through * krb5 1.8.1, it wasn't set in new entries.) */ st = krb5_get_attributes_mask(context, entry, &attr_mask); if (st != 0) goto cleanup; has_fail_count = ((attr_mask & KDB_FAIL_AUTH_COUNT_ATTR) != 0); /* * If the client library and server supports RFC 4525, * then use it to increment by one the value of the * krbLoginFailedCount attribute. Otherwise, assert the * (provided) old value by deleting it before adding. */ #ifdef LDAP_MOD_INCREMENT if (ldap_server_handle->server_info->modify_increment && has_fail_count) { st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_INCREMENT, 1); if (st != 0) goto cleanup; } else { #endif /* LDAP_MOD_INCREMENT */ if (has_fail_count) { st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_DELETE, entry->fail_auth_count); if (st != 0) goto cleanup; } st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_ADD, entry->fail_auth_count + 1); if (st != 0) goto cleanup; #ifdef LDAP_MOD_INCREMENT } #endif } else if (optype == ADD_PRINCIPAL) { /* Initialize krbLoginFailedCount in new entries to help avoid a * race during the first failed login. */ st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_ADD, 0); } if (entry->mask & KADM5_MAX_LIFE) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxticketlife", LDAP_MOD_REPLACE, entry->max_life)) != 0) goto cleanup; } if (entry->mask & KADM5_MAX_RLIFE) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxrenewableage", LDAP_MOD_REPLACE, entry->max_renewable_life)) != 0) goto cleanup; } if (entry->mask & KADM5_ATTRIBUTES) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbticketflags", LDAP_MOD_REPLACE, entry->attributes)) != 0) goto cleanup; } if (entry->mask & KADM5_PRINCIPAL) { memset(strval, 0, sizeof(strval)); strval[0] = user; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalname", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } if (entry->mask & KADM5_PRINC_EXPIRE_TIME) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_PW_EXPIRATION) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpasswordexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_POLICY || entry->mask & KADM5_KEY_HIST) { memset(&princ_ent, 0, sizeof(princ_ent)); for (tl_data=entry->tl_data; tl_data; tl_data=tl_data->tl_data_next) { if (tl_data->tl_data_type == KRB5_TL_KADM_DATA) { if ((st = krb5_lookup_tl_kadm_data(tl_data, &princ_ent)) != 0) { goto cleanup; } break; } } } if (entry->mask & KADM5_POLICY) { if (princ_ent.aux_attributes & KADM5_POLICY) { memset(strval, 0, sizeof(strval)); if ((st = krb5_ldap_name_to_policydn (context, princ_ent.policy, &polname)) != 0) goto cleanup; strval[0] = polname; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } else { st = EINVAL; k5_setmsg(context, st, "Password policy value null"); goto cleanup; } } else if (entry->mask & KADM5_LOAD && found_entry == TRUE) { /* * a load is special in that existing entries must have attrs that * removed. */ if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, NULL)) != 0) goto cleanup; } if (entry->mask & KADM5_POLICY_CLR) { if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_DELETE, NULL)) != 0) goto cleanup; } if (entry->mask & KADM5_KEY_HIST) { bersecretkey = krb5_encode_histkey(&princ_ent); if (bersecretkey == NULL) { st = ENOMEM; goto cleanup; } st = krb5_add_ber_mem_ldap_mod(&mods, "krbpwdhistory", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, bersecretkey); if (st != 0) goto cleanup; free_berdata(bersecretkey); bersecretkey = NULL; } if (entry->mask & KADM5_KEY_DATA || entry->mask & KADM5_KVNO) { krb5_kvno mkvno; if ((st=krb5_dbe_lookup_mkvno(context, entry, &mkvno)) != 0) goto cleanup; bersecretkey = krb5_encode_krbsecretkey (entry->key_data, entry->n_key_data, mkvno); if (bersecretkey == NULL) { st = ENOMEM; goto cleanup; } /* An empty list of bervals is only accepted for modify operations, * not add operations. */ if (bersecretkey[0] != NULL || !create_standalone) { st = krb5_add_ber_mem_ldap_mod(&mods, "krbprincipalkey", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, bersecretkey); if (st != 0) goto cleanup; } if (!(entry->mask & KADM5_PRINCIPAL)) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpasswordexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } /* Update last password change whenever a new key is set */ { krb5_timestamp last_pw_changed; if ((st=krb5_dbe_lookup_last_pwd_change(context, entry, &last_pw_changed)) != 0) goto cleanup; memset(strval, 0, sizeof(strval)); if ((strval[0] = getstringtime(last_pw_changed)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastPwdChange", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } } /* Modify Key data ends here */ /* Auth indicators will also be stored in krbExtraData when processing * tl_data. */ st = update_ldap_mod_auth_ind(context, entry, &mods); if (st != 0) goto cleanup; /* Set tl_data */ if (entry->tl_data != NULL) { int count = 0; struct berval **ber_tl_data = NULL; krb5_tl_data *ptr; krb5_timestamp unlock_time; for (ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) { if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE #ifdef SECURID || ptr->tl_data_type == KRB5_TL_DB_ARGS #endif || ptr->tl_data_type == KRB5_TL_KADM_DATA || ptr->tl_data_type == KDB_TL_USER_INFO || ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL || ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK) continue; count++; } if (count != 0) { int j; ber_tl_data = (struct berval **) calloc (count + 1, sizeof (struct berval*)); if (ber_tl_data == NULL) { st = ENOMEM; goto cleanup; } for (j = 0, ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) { /* Ignore tl_data that are stored in separate directory * attributes */ if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE #ifdef SECURID || ptr->tl_data_type == KRB5_TL_DB_ARGS #endif || ptr->tl_data_type == KRB5_TL_KADM_DATA || ptr->tl_data_type == KDB_TL_USER_INFO || ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL || ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK) continue; if ((st = tl_data2berval (ptr, &ber_tl_data[j])) != 0) break; j++; } if (st == 0) { ber_tl_data[count] = NULL; st=krb5_add_ber_mem_ldap_mod(&mods, "krbExtraData", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, ber_tl_data); } free_berdata(ber_tl_data); if (st != 0) goto cleanup; } if ((st=krb5_dbe_lookup_last_admin_unlock(context, entry, &unlock_time)) != 0) goto cleanup; if (unlock_time != 0) { /* Update last admin unlock */ memset(strval, 0, sizeof(strval)); if ((strval[0] = getstringtime(unlock_time)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastAdminUnlock", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } } /* Directory specific attribute */ if (xargs.tktpolicydn != NULL) { int tmask=0; if (strlen(xargs.tktpolicydn) != 0) { st = checkattributevalue(ld, xargs.tktpolicydn, "objectclass", policyclass, &tmask); CHECK_CLASS_VALIDITY(st, tmask, _("ticket policy object value: ")); strval[0] = xargs.tktpolicydn; strval[1] = NULL; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } else { /* if xargs.tktpolicydn is a empty string, then delete * already existing krbticketpolicyreference attr */ if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_DELETE, NULL)) != 0) goto cleanup; } } if (establish_links == TRUE) { memset(strval, 0, sizeof(strval)); strval[0] = xargs.linkdn; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbObjectReferences", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } /* * in case mods is NULL then return * not sure but can happen in a modprinc * so no need to return an error * addprinc will at least have the principal name * and the keys passed in */ if (mods == NULL) goto cleanup; if (create_standalone == TRUE) { memset(strval, 0, sizeof(strval)); strval[0] = "krbprincipal"; strval[1] = "krbprincipalaux"; strval[2] = "krbTicketPolicyAux"; if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0) goto cleanup; st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL); if (st == LDAP_ALREADY_EXISTS && entry->mask & KADM5_LOAD) { /* a load operation must replace an existing entry */ st = ldap_delete_ext_s(ld, standalone_principal_dn, NULL, NULL); if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("Principal delete failed (trying to replace " "entry): %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_ADD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } else { st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL); } } if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("Principal add failed: %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_ADD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } } else { /* * Here existing ldap object is modified and can be related * to any attribute, so always ensure that the ldap * object is extended with all the kerberos related * objectclasses so that there are no constraint * violations. */ { char *attrvalues[] = {"krbprincipalaux", "krbTicketPolicyAux", NULL}; int p, q, r=0, amask=0; if ((st=checkattributevalue(ld, (xargs.dn) ? xargs.dn : principal_dn, "objectclass", attrvalues, &amask)) != 0) goto cleanup; memset(strval, 0, sizeof(strval)); for (p=1, q=0; p<=2; p<<=1, ++q) { if ((p & amask) == 0) strval[r++] = attrvalues[q]; } if (r != 0) { if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0) goto cleanup; } } if (xargs.dn != NULL) st=ldap_modify_ext_s(ld, xargs.dn, mods, NULL, NULL); else st = ldap_modify_ext_s(ld, principal_dn, mods, NULL, NULL); if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("User modification failed: %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_MOD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) entry->fail_auth_count++; } cleanup: if (user) free(user); if (filtuser) free(filtuser); free_xargs(xargs); if (standalone_principal_dn) free(standalone_principal_dn); if (principal_dn) free (principal_dn); if (polname != NULL) free(polname); for (tre = 0; tre < ntrees; tre++) free(subtreelist[tre]); free(subtreelist); if (subtree) free (subtree); if (bersecretkey) { for (l=0; bersecretkey[l]; ++l) { if (bersecretkey[l]->bv_val) free (bersecretkey[l]->bv_val); free (bersecretkey[l]); } free (bersecretkey); } if (keys) free (keys); ldap_mods_free(mods, 1); ldap_osa_free_princ_ent(&princ_ent); ldap_msgfree(result); krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle); return(st); }
169,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { int id = ctxt->input->id; SKIP(3); SKIP_BLANKS; if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) { SKIP(7); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering INCLUDE Conditional Section\n"); } while ((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || (NXT(2) != '>'))) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving INCLUDE Conditional Section\n"); } } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) { int state; xmlParserInputState instate; int depth = 0; SKIP(6); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering IGNORE Conditional Section\n"); } /* * Parse up to the end of the conditional section * But disable SAX event generating DTD building in the meantime */ state = ctxt->disableSAX; instate = ctxt->instate; if (ctxt->recovery == 0) ctxt->disableSAX = 1; ctxt->instate = XML_PARSER_IGNORE; while ((depth >= 0) && (RAW != 0)) { if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { depth++; SKIP(3); continue; } if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (--depth >= 0) SKIP(3); continue; } NEXT; continue; } ctxt->disableSAX = state; ctxt->instate = instate; if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving IGNORE Conditional Section\n"); } } else { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL); } if (RAW == 0) SHRINK; if (RAW == 0) { xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } SKIP(3); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { int id = ctxt->input->id; SKIP(3); SKIP_BLANKS; if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) { SKIP(7); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering INCLUDE Conditional Section\n"); } while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || (NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving INCLUDE Conditional Section\n"); } } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) { int state; xmlParserInputState instate; int depth = 0; SKIP(6); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering IGNORE Conditional Section\n"); } /* * Parse up to the end of the conditional section * But disable SAX event generating DTD building in the meantime */ state = ctxt->disableSAX; instate = ctxt->instate; if (ctxt->recovery == 0) ctxt->disableSAX = 1; ctxt->instate = XML_PARSER_IGNORE; while (((depth >= 0) && (RAW != 0)) && (ctxt->instate != XML_PARSER_EOF)) { if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { depth++; SKIP(3); continue; } if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (--depth >= 0) SKIP(3); continue; } NEXT; continue; } ctxt->disableSAX = state; ctxt->instate = instate; if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving IGNORE Conditional Section\n"); } } else { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL); } if (RAW == 0) SHRINK; if (RAW == 0) { xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } SKIP(3); } }
171,280
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); pid_t pid = (pid_t)data.readInt32(); reply->writeInt32(livesLocally(node, pid)); return OK; } case LIST_NODES: { CHECK_OMX_INTERFACE(IOMX, data, reply); List<ComponentInfo> list; listNodes(&list); reply->writeInt32(list.size()); for (List<ComponentInfo>::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List<String8>::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp<IOMXObserver> observer = interface_cast<IOMXObserver>(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_COMMANDTYPE cmd = static_cast<OMX_COMMANDTYPE>(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: case SET_INTERNAL_OPTION: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32()); size_t size = data.readInt64(); void *params = malloc(size); data.read(params, size); status_t err; switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; case SET_INTERNAL_OPTION: { InternalOptionType type = (InternalOptionType)data.readInt32(); err = setInternalOption(node, index, type, params, size); break; } default: TRESPASS(); } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } free(params); params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case UPDATE_GRAPHIC_BUFFER_IN_META: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer = (buffer_id)data.readInt32(); status_t err = updateGraphicBufferInMeta( node, port_index, graphicBuffer, buffer); reply->writeInt32(err); return NO_ERROR; } case CREATE_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferProducer> bufferProducer; MetadataBufferType type; status_t err = createInputSurface(node, port_index, &bufferProducer, &type); reply->writeInt32(type); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); } return NO_ERROR; } case CREATE_PERSISTENT_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); sp<IGraphicBufferProducer> bufferProducer; sp<IGraphicBufferConsumer> bufferConsumer; status_t err = createPersistentInputSurface( &bufferProducer, &bufferConsumer); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); reply->writeStrongBinder(IInterface::asBinder(bufferConsumer)); } return NO_ERROR; } case SET_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferConsumer> bufferConsumer = interface_cast<IGraphicBufferConsumer>(data.readStrongBinder()); MetadataBufferType type; status_t err = setInputSurface(node, port_index, bufferConsumer, &type); reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case SIGNAL_END_OF_INPUT_STREAM: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); status_t err = signalEndOfInputStream(node); reply->writeInt32(err); return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); MetadataBufferType type; status_t err = storeMetaDataInBuffers(node, port_index, enable, &type); reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case PREPARE_FOR_ADAPTIVE_PLAYBACK: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); OMX_U32 max_width = data.readInt32(); OMX_U32 max_height = data.readInt32(); status_t err = prepareForAdaptivePlayback( node, port_index, enable, max_width, max_height); reply->writeInt32(err); return NO_ERROR; } case CONFIGURE_VIDEO_TUNNEL_MODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); OMX_U32 audio_hw_sync = data.readInt32(); native_handle_t *sideband_handle = NULL; status_t err = configureVideoTunnelMode( node, port_index, tunneled, audio_hw_sync, &sideband_handle); reply->writeInt32(err); if(err == OK){ reply->writeNativeHandle(sideband_handle); } return NO_ERROR; } case ALLOC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { ALOGE("b/24310423"); reply->writeInt32(INVALID_OPERATION); return NO_ERROR; } size_t size = data.readInt64(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); reply->writeInt64((uintptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(fillBuffer(node, buffer, fenceFd)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp, fenceFd)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } } Commit Message: 3 uninitialized variables in IOMX.cpp Uninitialized MetadataBufferType pointer in case: SET_INPUT_SURFACE STORE_META_DATA_IN_BUFFERS CREATE_INPUT_SURFACE Fix: initialize them to kMetadataBufferTypeInvalid Bug: 26324358 Change-Id: Ib3bcac9bedc98bc65efa39f67cdbffbd90b374c9 CWE ID: CWE-119
status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); pid_t pid = (pid_t)data.readInt32(); reply->writeInt32(livesLocally(node, pid)); return OK; } case LIST_NODES: { CHECK_OMX_INTERFACE(IOMX, data, reply); List<ComponentInfo> list; listNodes(&list); reply->writeInt32(list.size()); for (List<ComponentInfo>::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List<String8>::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp<IOMXObserver> observer = interface_cast<IOMXObserver>(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_COMMANDTYPE cmd = static_cast<OMX_COMMANDTYPE>(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: case SET_INTERNAL_OPTION: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32()); size_t size = data.readInt64(); void *params = malloc(size); data.read(params, size); status_t err; switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; case SET_INTERNAL_OPTION: { InternalOptionType type = (InternalOptionType)data.readInt32(); err = setInternalOption(node, index, type, params, size); break; } default: TRESPASS(); } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } free(params); params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case UPDATE_GRAPHIC_BUFFER_IN_META: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer = (buffer_id)data.readInt32(); status_t err = updateGraphicBufferInMeta( node, port_index, graphicBuffer, buffer); reply->writeInt32(err); return NO_ERROR; } case CREATE_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferProducer> bufferProducer; MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = createInputSurface(node, port_index, &bufferProducer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, "26324358"); } reply->writeInt32(type); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); } return NO_ERROR; } case CREATE_PERSISTENT_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); sp<IGraphicBufferProducer> bufferProducer; sp<IGraphicBufferConsumer> bufferConsumer; status_t err = createPersistentInputSurface( &bufferProducer, &bufferConsumer); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); reply->writeStrongBinder(IInterface::asBinder(bufferConsumer)); } return NO_ERROR; } case SET_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferConsumer> bufferConsumer = interface_cast<IGraphicBufferConsumer>(data.readStrongBinder()); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = setInputSurface(node, port_index, bufferConsumer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, "26324358"); } reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case SIGNAL_END_OF_INPUT_STREAM: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); status_t err = signalEndOfInputStream(node); reply->writeInt32(err); return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = storeMetaDataInBuffers(node, port_index, enable, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, "26324358"); } reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case PREPARE_FOR_ADAPTIVE_PLAYBACK: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); OMX_U32 max_width = data.readInt32(); OMX_U32 max_height = data.readInt32(); status_t err = prepareForAdaptivePlayback( node, port_index, enable, max_width, max_height); reply->writeInt32(err); return NO_ERROR; } case CONFIGURE_VIDEO_TUNNEL_MODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); OMX_U32 audio_hw_sync = data.readInt32(); native_handle_t *sideband_handle = NULL; status_t err = configureVideoTunnelMode( node, port_index, tunneled, audio_hw_sync, &sideband_handle); reply->writeInt32(err); if(err == OK){ reply->writeNativeHandle(sideband_handle); } return NO_ERROR; } case ALLOC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { ALOGE("b/24310423"); reply->writeInt32(INVALID_OPERATION); return NO_ERROR; } size_t size = data.readInt64(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); reply->writeInt64((uintptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(fillBuffer(node, buffer, fenceFd)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp, fenceFd)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } }
173,892
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtr<DrawingBuffer> DrawingBuffer::Create( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, Client* client, const IntSize& size, bool premultiplied_alpha, bool want_alpha_channel, bool want_depth_buffer, bool want_stencil_buffer, bool want_antialiasing, PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) { DCHECK(context_provider); if (g_should_fail_drawing_buffer_creation_for_testing) { g_should_fail_drawing_buffer_creation_for_testing = false; return nullptr; } std::unique_ptr<Extensions3DUtil> extensions_util = Extensions3DUtil::Create(context_provider->ContextGL()); if (!extensions_util->IsValid()) { return nullptr; } DCHECK(extensions_util->SupportsExtension("GL_OES_packed_depth_stencil")); extensions_util->EnsureExtensionEnabled("GL_OES_packed_depth_stencil"); bool multisample_supported = want_antialiasing && (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample") || extensions_util->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) && extensions_util->SupportsExtension("GL_OES_rgb8_rgba8"); if (multisample_supported) { extensions_util->EnsureExtensionEnabled("GL_OES_rgb8_rgba8"); if (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample")) extensions_util->EnsureExtensionEnabled( "GL_CHROMIUM_framebuffer_multisample"); else extensions_util->EnsureExtensionEnabled( "GL_EXT_multisampled_render_to_texture"); } bool discard_framebuffer_supported = extensions_util->SupportsExtension("GL_EXT_discard_framebuffer"); if (discard_framebuffer_supported) extensions_util->EnsureExtensionEnabled("GL_EXT_discard_framebuffer"); RefPtr<DrawingBuffer> drawing_buffer = AdoptRef(new DrawingBuffer( std::move(context_provider), std::move(extensions_util), client, discard_framebuffer_supported, want_alpha_channel, premultiplied_alpha, preserve, web_gl_version, want_depth_buffer, want_stencil_buffer, chromium_image_usage, color_params)); if (!drawing_buffer->Initialize(size, multisample_supported)) { drawing_buffer->BeginDestruction(); return PassRefPtr<DrawingBuffer>(); } return drawing_buffer; } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
PassRefPtr<DrawingBuffer> DrawingBuffer::Create( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, Client* client, const IntSize& size, bool premultiplied_alpha, bool want_alpha_channel, bool want_depth_buffer, bool want_stencil_buffer, bool want_antialiasing, PreserveDrawingBuffer preserve, WebGLVersion webgl_version, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) { DCHECK(context_provider); if (g_should_fail_drawing_buffer_creation_for_testing) { g_should_fail_drawing_buffer_creation_for_testing = false; return nullptr; } std::unique_ptr<Extensions3DUtil> extensions_util = Extensions3DUtil::Create(context_provider->ContextGL()); if (!extensions_util->IsValid()) { return nullptr; } DCHECK(extensions_util->SupportsExtension("GL_OES_packed_depth_stencil")); extensions_util->EnsureExtensionEnabled("GL_OES_packed_depth_stencil"); bool multisample_supported = want_antialiasing && (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample") || extensions_util->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) && extensions_util->SupportsExtension("GL_OES_rgb8_rgba8"); if (multisample_supported) { extensions_util->EnsureExtensionEnabled("GL_OES_rgb8_rgba8"); if (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample")) extensions_util->EnsureExtensionEnabled( "GL_CHROMIUM_framebuffer_multisample"); else extensions_util->EnsureExtensionEnabled( "GL_EXT_multisampled_render_to_texture"); } bool discard_framebuffer_supported = extensions_util->SupportsExtension("GL_EXT_discard_framebuffer"); if (discard_framebuffer_supported) extensions_util->EnsureExtensionEnabled("GL_EXT_discard_framebuffer"); RefPtr<DrawingBuffer> drawing_buffer = AdoptRef(new DrawingBuffer( std::move(context_provider), std::move(extensions_util), client, discard_framebuffer_supported, want_alpha_channel, premultiplied_alpha, preserve, webgl_version, want_depth_buffer, want_stencil_buffer, chromium_image_usage, color_params)); if (!drawing_buffer->Initialize(size, multisample_supported)) { drawing_buffer->BeginDestruction(); return PassRefPtr<DrawingBuffer>(); } return drawing_buffer; }
172,290
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct pipe_inode_info *alloc_pipe_info(void) { struct pipe_inode_info *pipe; pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL); if (pipe) { pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * PIPE_DEF_BUFFERS, GFP_KERNEL); if (pipe->bufs) { init_waitqueue_head(&pipe->wait); pipe->r_counter = pipe->w_counter = 1; pipe->buffers = PIPE_DEF_BUFFERS; mutex_init(&pipe->mutex); return pipe; } kfree(pipe); } return NULL; } Commit Message: pipe: limit the per-user amount of pages allocated in pipes On no-so-small systems, it is possible for a single process to cause an OOM condition by filling large pipes with data that are never read. A typical process filling 4000 pipes with 1 MB of data will use 4 GB of memory. On small systems it may be tricky to set the pipe max size to prevent this from happening. This patch makes it possible to enforce a per-user soft limit above which new pipes will be limited to a single page, effectively limiting them to 4 kB each, as well as a hard limit above which no new pipes may be created for this user. This has the effect of protecting the system against memory abuse without hurting other users, and still allowing pipes to work correctly though with less data at once. The limit are controlled by two new sysctls : pipe-user-pages-soft, and pipe-user-pages-hard. Both may be disabled by setting them to zero. The default soft limit allows the default number of FDs per process (1024) to create pipes of the default size (64kB), thus reaching a limit of 64MB before starting to create only smaller pipes. With 256 processes limited to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB = 1084 MB of memory allocated for a user. The hard limit is disabled by default to avoid breaking existing applications that make intensive use of pipes (eg: for splicing). Reported-by: [email protected] Reported-by: Tetsuo Handa <[email protected]> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Willy Tarreau <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-399
struct pipe_inode_info *alloc_pipe_info(void) { struct pipe_inode_info *pipe; pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL); if (pipe) { unsigned long pipe_bufs = PIPE_DEF_BUFFERS; struct user_struct *user = get_current_user(); if (!too_many_pipe_buffers_hard(user)) { if (too_many_pipe_buffers_soft(user)) pipe_bufs = 1; pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * pipe_bufs, GFP_KERNEL); } if (pipe->bufs) { init_waitqueue_head(&pipe->wait); pipe->r_counter = pipe->w_counter = 1; pipe->buffers = pipe_bufs; pipe->user = user; account_pipe_buffers(pipe, 0, pipe_bufs); mutex_init(&pipe->mutex); return pipe; } free_uid(user); kfree(pipe); } return NULL; }
167,386
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) { #ifdef SAVE_ON_FLASH jsiConsolePrint("Trace unimplemented in this version.\n"); #else int i; for (i=0;i<indent;i++) jsiConsolePrint(" "); if (!var) { jsiConsolePrint("undefined"); return; } jsvTraceLockInfo(var); int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var); if (lowestLevel < level) { jsiConsolePrint("...\n"); return; } if (jsvIsName(var)) jsiConsolePrint("Name "); char endBracket = ' '; if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; } else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; } else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; } else if (jsvIsFunction(var)) { jsiConsolePrint("Function { "); if (jsvIsFunctionReturn(var)) jsiConsolePrint("return "); endBracket = '}'; } else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var)); else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var)); else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false"); else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var)); else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var); else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var)); else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)); // way to get nice name else if (jsvIsString(var)) { size_t blocks = 1; if (jsvGetLastChild(var)) { JsVar *v = jsvLock(jsvGetLastChild(var)); blocks += jsvCountJsVarsUsed(v); jsvUnLock(v); } if (jsvIsFlatString(var)) { blocks += jsvGetFlatStringBlocks(var); } jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var); } else { jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK)); } if (jsvIsNameInt(var)) { jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var)); return; } else if (jsvIsNameIntBool(var)) { jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false"); return; } if (jsvHasSingleChild(var)) { JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0; _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); } else if (jsvHasChildren(var)) { JsvIterator it; jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS); bool first = true; while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) { if (first) jsiConsolePrintf("\n"); first = false; JsVar *child = jsvIteratorGetKey(&it); _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); jsiConsolePrintf("\n"); jsvIteratorNext(&it); } jsvIteratorFree(&it); if (!first) for (i=0;i<indent;i++) jsiConsolePrint(" "); } jsiConsolePrintf("%c", endBracket); #endif } Commit Message: Add sanity check for debug trace print statement (fix #1420) CWE ID: CWE-476
void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) { #ifdef SAVE_ON_FLASH jsiConsolePrint("Trace unimplemented in this version.\n"); #else int i; for (i=0;i<indent;i++) jsiConsolePrint(" "); if (!var) { jsiConsolePrint("undefined"); return; } jsvTraceLockInfo(var); int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var); if (lowestLevel < level) { jsiConsolePrint("...\n"); return; } if (jsvIsName(var)) jsiConsolePrint("Name "); char endBracket = ' '; if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; } else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; } else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; } else if (jsvIsFunction(var)) { jsiConsolePrint("Function { "); if (jsvIsFunctionReturn(var)) jsiConsolePrint("return "); endBracket = '}'; } else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var)); else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var)); else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false"); else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var)); else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var); else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var)); else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)?jswGetBasicObjectName(var):"unknown ArrayBuffer"); // way to get nice name else if (jsvIsString(var)) { size_t blocks = 1; if (jsvGetLastChild(var)) { JsVar *v = jsvLock(jsvGetLastChild(var)); blocks += jsvCountJsVarsUsed(v); jsvUnLock(v); } if (jsvIsFlatString(var)) { blocks += jsvGetFlatStringBlocks(var); } jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var); } else { jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK)); } if (jsvIsNameInt(var)) { jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var)); return; } else if (jsvIsNameIntBool(var)) { jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false"); return; } if (jsvHasSingleChild(var)) { JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0; _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); } else if (jsvHasChildren(var)) { JsvIterator it; jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS); bool first = true; while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) { if (first) jsiConsolePrintf("\n"); first = false; JsVar *child = jsvIteratorGetKey(&it); _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); jsiConsolePrintf("\n"); jsvIteratorNext(&it); } jsvIteratorFree(&it); if (!first) for (i=0;i<indent;i++) jsiConsolePrint(" "); } jsiConsolePrintf("%c", endBracket); #endif }
169,217
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserPluginGuest::SetCompositingBufferData(int gpu_process_id, uint32 client_id, uint32 context_id, uint32 texture_id_0, uint32 texture_id_1, uint32 sync_point) { if (texture_id_0 == 0) { DCHECK(texture_id_1 == 0); return; } DCHECK(texture_id_1 != 0); DCHECK(texture_id_0 != texture_id_1); surface_handle_ = gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true); surface_handle_.parent_gpu_process_id = gpu_process_id; surface_handle_.parent_client_id = client_id; surface_handle_.parent_context_id = context_id; surface_handle_.parent_texture_id[0] = texture_id_0; surface_handle_.parent_texture_id[1] = texture_id_1; surface_handle_.sync_point = sync_point; } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BrowserPluginGuest::SetCompositingBufferData(int gpu_process_id, uint32 client_id, uint32 context_id, uint32 texture_id_0, uint32 texture_id_1, uint32 sync_point) { if (texture_id_0 == 0) { DCHECK(texture_id_1 == 0); return; } DCHECK(texture_id_1 != 0); DCHECK(texture_id_0 != texture_id_1); surface_handle_ = gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true); surface_handle_.parent_gpu_process_id = gpu_process_id; surface_handle_.parent_client_id = client_id; }
171,352
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: FLACParser::FLACParser( const sp<DataSource> &dataSource, const sp<MetaData> &fileMetadata, const sp<MetaData> &trackMetadata) : mDataSource(dataSource), mFileMetadata(fileMetadata), mTrackMetadata(trackMetadata), mInitCheck(false), mMaxBufferSize(0), mGroup(NULL), mCopy(copyTrespass), mDecoder(NULL), mCurrentPos(0LL), mEOF(false), mStreamInfoValid(false), mWriteRequested(false), mWriteCompleted(false), mWriteBuffer(NULL), mErrorStatus((FLAC__StreamDecoderErrorStatus) -1) { ALOGV("FLACParser::FLACParser"); memset(&mStreamInfo, 0, sizeof(mStreamInfo)); memset(&mWriteHeader, 0, sizeof(mWriteHeader)); mInitCheck = init(); } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
FLACParser::FLACParser( const sp<DataSource> &dataSource, const sp<MetaData> &fileMetadata, const sp<MetaData> &trackMetadata) : mDataSource(dataSource), mFileMetadata(fileMetadata), mTrackMetadata(trackMetadata), mInitCheck(false), mMaxBufferSize(0), mGroup(NULL), mCopy(copyTrespass), mDecoder(NULL), mCurrentPos(0LL), mEOF(false), mStreamInfoValid(false), mWriteRequested(false), mWriteCompleted(false), mErrorStatus((FLAC__StreamDecoderErrorStatus) -1) { ALOGV("FLACParser::FLACParser"); memset(&mStreamInfo, 0, sizeof(mStreamInfo)); memset(&mWriteHeader, 0, sizeof(mWriteHeader)); mInitCheck = init(); }
174,014
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long CuePoint::GetTimeCode() const { return m_timecode; } 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 long CuePoint::GetTimeCode() const long long CuePoint::GetTime(const Segment* pSegment) const { assert(pSegment); assert(m_timecode >= 0); const SegmentInfo* const pInfo = pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long time = scale * m_timecode; return time; }
174,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LogErrorEventDescription(Display* dpy, const XErrorEvent& error_event) { char error_str[256]; char request_str[256]; XGetErrorText(dpy, error_event.error_code, error_str, sizeof(error_str)); strncpy(request_str, "Unknown", sizeof(request_str)); if (error_event.request_code < 128) { std::string num = base::UintToString(error_event.request_code); XGetErrorDatabaseText( dpy, "XRequest", num.c_str(), "Unknown", request_str, sizeof(request_str)); } else { int num_ext; char** ext_list = XListExtensions(dpy, &num_ext); for (int i = 0; i < num_ext; i++) { int ext_code, first_event, first_error; XQueryExtension(dpy, ext_list[i], &ext_code, &first_event, &first_error); if (error_event.request_code == ext_code) { std::string msg = StringPrintf( "%s.%d", ext_list[i], error_event.minor_code); XGetErrorDatabaseText( dpy, "XRequest", msg.c_str(), "Unknown", request_str, sizeof(request_str)); break; } } XFreeExtensionList(ext_list); } LOG(ERROR) << "X Error detected: " << "serial " << error_event.serial << ", " << "error_code " << static_cast<int>(error_event.error_code) << " (" << error_str << "), " << "request_code " << static_cast<int>(error_event.request_code) << ", " << "minor_code " << static_cast<int>(error_event.minor_code) << " (" << request_str << ")"; } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void LogErrorEventDescription(Display* dpy, const XErrorEvent& error_event) { char error_str[256]; char request_str[256]; XGetErrorText(dpy, error_event.error_code, error_str, sizeof(error_str)); strncpy(request_str, "Unknown", sizeof(request_str)); if (error_event.request_code < 128) { std::string num = base::UintToString(error_event.request_code); XGetErrorDatabaseText( dpy, "XRequest", num.c_str(), "Unknown", request_str, sizeof(request_str)); } else { int num_ext; char** ext_list = XListExtensions(dpy, &num_ext); for (int i = 0; i < num_ext; i++) { int ext_code, first_event, first_error; XQueryExtension(dpy, ext_list[i], &ext_code, &first_event, &first_error); if (error_event.request_code == ext_code) { std::string msg = StringPrintf( "%s.%d", ext_list[i], error_event.minor_code); XGetErrorDatabaseText( dpy, "XRequest", msg.c_str(), "Unknown", request_str, sizeof(request_str)); break; } } XFreeExtensionList(ext_list); } LOG(ERROR) << "X Error detected: " << "serial " << error_event.serial << ", " << "error_code " << static_cast<int>(error_event.error_code) << " (" << error_str << "), " << "request_code " << static_cast<int>(error_event.request_code) << ", " << "minor_code " << static_cast<int>(error_event.minor_code) << " (" << request_str << ")"; }
171,595
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int _mkp_stage_30(struct plugin *p, struct client_session *cs, struct session_request *sr) { mk_ptr_t referer; (void) p; (void) cs; PLUGIN_TRACE("[FD %i] Mandril validating URL", cs->socket); if (mk_security_check_url(sr->uri) < 0) { PLUGIN_TRACE("[FD %i] Close connection, blocked URL", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } PLUGIN_TRACE("[FD %d] Mandril validating hotlinking", cs->socket); referer = mk_api->header_get(&sr->headers_toc, "Referer", strlen("Referer")); if (mk_security_check_hotlink(sr->uri_processed, sr->host, referer) < 0) { PLUGIN_TRACE("[FD %i] Close connection, deny hotlinking.", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } return MK_PLUGIN_RET_NOT_ME; } Commit Message: Mandril: check decoded URI (fix #92) Signed-off-by: Eduardo Silva <[email protected]> CWE ID: CWE-264
int _mkp_stage_30(struct plugin *p, struct client_session *cs, struct session_request *sr) { mk_ptr_t referer; (void) p; (void) cs; PLUGIN_TRACE("[FD %i] Mandril validating URL", cs->socket); if (mk_security_check_url(sr->uri_processed) < 0) { PLUGIN_TRACE("[FD %i] Close connection, blocked URL", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } PLUGIN_TRACE("[FD %d] Mandril validating hotlinking", cs->socket); referer = mk_api->header_get(&sr->headers_toc, "Referer", strlen("Referer")); if (mk_security_check_hotlink(sr->uri_processed, sr->host, referer) < 0) { PLUGIN_TRACE("[FD %i] Close connection, deny hotlinking.", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } return MK_PLUGIN_RET_NOT_ME; }
166,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_1_6_dummy(kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr) { int i; char *password = *passptr; /* Old-style randkey operations disallowed tickets to start. */ if (!(mask & KADM5_ATTRIBUTES) || !(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)) return; /* The 1.6 dummy password was the octets 1..255. */ for (i = 0; (unsigned char) password[i] == i + 1; i++); if (password[i] != '\0' || i != 255) return; /* This will make the caller use a random password instead. */ *passptr = NULL; } Commit Message: Null pointer deref in kadmind [CVE-2012-1013] The fix for #6626 could cause kadmind to dereference a null pointer if a create-principal request contains no password but does contain the KRB5_KDB_DISALLOW_ALL_TIX flag (e.g. "addprinc -randkey -allow_tix name"). Only clients authorized to create principals can trigger the bug. Fix the bug by testing for a null password in check_1_6_dummy. CVSSv2 vector: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C [[email protected]: Minor style change and commit message] ticket: 7152 target_version: 1.10.2 tags: pullup CWE ID:
check_1_6_dummy(kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr) { int i; char *password = *passptr; /* Old-style randkey operations disallowed tickets to start. */ if (password == NULL || !(mask & KADM5_ATTRIBUTES) || !(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)) return; /* The 1.6 dummy password was the octets 1..255. */ for (i = 0; (unsigned char) password[i] == i + 1; i++); if (password[i] != '\0' || i != 255) return; /* This will make the caller use a random password instead. */ *passptr = NULL; }
165,646
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Block::SetKey(bool bKey) { if (bKey) m_flags |= static_cast<unsigned char>(1 << 7); else m_flags &= 0x7F; } 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
void Block::SetKey(bool bKey) Block::Lacing Block::GetLacing() const { const int value = int(m_flags & 0x06) >> 1; return static_cast<Lacing>(value); }
174,440
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AppCacheDatabase::FindEntry(int64_t cache_id, const GURL& url, EntryRecord* record) { DCHECK(record); if (!LazyOpen(kDontCreate)) return false; static const char kSql[] = "SELECT cache_id, url, flags, response_id, response_size FROM Entries" " WHERE cache_id = ? AND url = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, cache_id); statement.BindString(1, url.spec()); if (!statement.Step()) return false; ReadEntryRecord(statement, record); DCHECK(record->cache_id == cache_id); DCHECK(record->url == url); return true; } 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
bool AppCacheDatabase::FindEntry(int64_t cache_id, const GURL& url, EntryRecord* record) { DCHECK(record); if (!LazyOpen(kDontCreate)) return false; static const char kSql[] = "SELECT cache_id, url, flags, response_id, response_size, padding_size " "FROM Entries" " WHERE cache_id = ? AND url = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, cache_id); statement.BindString(1, url.spec()); if (!statement.Step()) return false; ReadEntryRecord(statement, record); DCHECK(record->cache_id == cache_id); DCHECK(record->url == url); return true; }
172,977
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MyOpusExtractor::readNextPacket(MediaBuffer **out) { if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) { MediaBuffer *mBuf; uint32_t numSamples = 0; uint64_t curGranulePosition = 0; while (true) { status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false); if (err != OK && err != ERROR_END_OF_STREAM) { return err; } if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) { break; } curGranulePosition = mCurrentPage.mGranulePosition; numSamples += getNumSamplesInPacket(mBuf); mBuf->release(); mBuf = NULL; } if (curGranulePosition > numSamples) { mStartGranulePosition = curGranulePosition - numSamples; } else { mStartGranulePosition = 0; } seekToOffset(0); } status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false); if (err != OK) { return err; } int32_t currentPageSamples; if ((*out)->meta_data()->findInt32(kKeyValidSamples, &currentPageSamples)) { if (mOffset == mFirstDataOffset) { currentPageSamples -= mStartGranulePosition; (*out)->meta_data()->setInt32(kKeyValidSamples, currentPageSamples); } mCurGranulePosition = mCurrentPage.mGranulePosition - currentPageSamples; } int64_t timeUs = getTimeUsOfGranule(mCurGranulePosition); (*out)->meta_data()->setInt64(kKeyTime, timeUs); uint32_t frames = getNumSamplesInPacket(*out); mCurGranulePosition += frames; return OK; } Commit Message: Fix memory leak in OggExtractor Test: added a temporal log and run poc Bug: 63581671 Change-Id: I436a08e54d5e831f9fbdb33c26d15397ce1fbeba (cherry picked from commit 63079e7c8e12cda4eb124fbe565213d30b9ea34c) CWE ID: CWE-772
status_t MyOpusExtractor::readNextPacket(MediaBuffer **out) { if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) { MediaBuffer *mBuf; uint32_t numSamples = 0; uint64_t curGranulePosition = 0; while (true) { status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false); if (err != OK && err != ERROR_END_OF_STREAM) { return err; } if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) { if (mBuf != NULL) { mBuf->release(); mBuf = NULL; } break; } curGranulePosition = mCurrentPage.mGranulePosition; numSamples += getNumSamplesInPacket(mBuf); mBuf->release(); mBuf = NULL; } if (curGranulePosition > numSamples) { mStartGranulePosition = curGranulePosition - numSamples; } else { mStartGranulePosition = 0; } seekToOffset(0); } status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false); if (err != OK) { return err; } int32_t currentPageSamples; if ((*out)->meta_data()->findInt32(kKeyValidSamples, &currentPageSamples)) { if (mOffset == mFirstDataOffset) { currentPageSamples -= mStartGranulePosition; (*out)->meta_data()->setInt32(kKeyValidSamples, currentPageSamples); } mCurGranulePosition = mCurrentPage.mGranulePosition - currentPageSamples; } int64_t timeUs = getTimeUsOfGranule(mCurGranulePosition); (*out)->meta_data()->setInt64(kKeyTime, timeUs); uint32_t frames = getNumSamplesInPacket(*out); mCurGranulePosition += frames; return OK; }
173,976
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string TestFlashMessageLoop::TestRunWithoutQuit() { message_loop_ = new pp::flash::MessageLoop(instance_); pp::CompletionCallback callback = callback_factory_.NewCallback( &TestFlashMessageLoop::DestroyMessageLoopResourceTask); pp::Module::Get()->core()->CallOnMainThread(0, callback); int32_t result = message_loop_->Run(); if (message_loop_) { delete message_loop_; message_loop_ = NULL; ASSERT_TRUE(false); } ASSERT_EQ(PP_ERROR_ABORTED, result); PASS(); } Commit Message: Fix PPB_Flash_MessageLoop. This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop. BUG=569496 Review URL: https://codereview.chromium.org/1559113002 Cr-Commit-Position: refs/heads/master@{#374529} CWE ID: CWE-264
std::string TestFlashMessageLoop::TestRunWithoutQuit() { message_loop_ = new pp::flash::MessageLoop(instance_); pp::CompletionCallback callback = callback_factory_.NewCallback( &TestFlashMessageLoop::DestroyMessageLoopResourceTask); pp::Module::Get()->core()->CallOnMainThread(0, callback); int32_t result = message_loop_->Run(); if (message_loop_) { delete message_loop_; message_loop_ = nullptr; ASSERT_TRUE(false); } ASSERT_EQ(PP_ERROR_ABORTED, result); PASS(); }
172,128
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static boolean ReadICCProfile(j_decompress_ptr jpeg_info) { char magick[12]; ErrorManager *error_manager; ExceptionInfo *exception; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *icc_profile, *profile; /* Read color profile. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } for (i=0; i < 12; i++) magick[i]=(char) GetCharacter(jpeg_info); if (LocaleCompare(magick,ICC_PROFILE) != 0) { /* Not a ICC profile, return. */ for (i=0; i < (ssize_t) (length-12); i++) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } (void) GetCharacter(jpeg_info); /* id */ (void) GetCharacter(jpeg_info); /* markers */ length-=14; error_manager=(ErrorManager *) jpeg_info->client_data; exception=error_manager->exception; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) { int c; c=GetCharacter(jpeg_info); if (c == EOF) break; *p++=(unsigned char) c; } if (i != (ssize_t) length) { profile=DestroyStringInfo(profile); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"InsufficientImageDataInFile","`%s'", image->filename); return(FALSE); } error_manager->profile=NULL; icc_profile=(StringInfo *) GetImageProfile(image,"icc"); if (icc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(icc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %.20g bytes",(double) length); return(TRUE); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641 CWE ID:
static boolean ReadICCProfile(j_decompress_ptr jpeg_info) { char magick[12]; ErrorManager *error_manager; ExceptionInfo *exception; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *icc_profile, *profile; /* Read color profile. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } for (i=0; i < 12; i++) magick[i]=(char) GetCharacter(jpeg_info); if (LocaleCompare(magick,ICC_PROFILE) != 0) { /* Not a ICC profile, return. */ for (i=0; i < (ssize_t) (length-12); i++) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } (void) GetCharacter(jpeg_info); /* id */ (void) GetCharacter(jpeg_info); /* markers */ length-=14; error_manager=(ErrorManager *) jpeg_info->client_data; exception=error_manager->exception; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) { int c; c=GetCharacter(jpeg_info); if (c == EOF) break; *p++=(unsigned char) c; } error_manager->profile=NULL; if (i != (ssize_t) length) { profile=DestroyStringInfo(profile); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"InsufficientImageDataInFile","`%s'", image->filename); return(FALSE); } icc_profile=(StringInfo *) GetImageProfile(image,"icc"); if (icc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(icc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %.20g bytes",(double) length); return(TRUE); }
169,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: inline HTMLIFrameElement::HTMLIFrameElement(Document& document) : HTMLFrameElementBase(iframeTag, document), did_load_non_empty_document_(false), collapsed_by_client_(false), sandbox_(HTMLIFrameElementSandbox::Create(this)), referrer_policy_(kReferrerPolicyDefault) {} Commit Message: Resource Timing: Do not report subsequent navigations within subframes We only want to record resource timing for the load that was initiated by parent document. We filter out subsequent navigations for <iframe>, but we should do it for other types of subframes too. Bug: 780312 Change-Id: I3a7b9e1a365c99e24bb8dac190e88c7099fc3da5 Reviewed-on: https://chromium-review.googlesource.com/750487 Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Kunihiko Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#513665} CWE ID: CWE-601
inline HTMLIFrameElement::HTMLIFrameElement(Document& document) : HTMLFrameElementBase(iframeTag, document), collapsed_by_client_(false), sandbox_(HTMLIFrameElementSandbox::Create(this)), referrer_policy_(kReferrerPolicyDefault) {}
172,929
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool CreateIpcChannel( const std::string& channel_name, const std::string& pipe_security_descriptor, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, IPC::Listener* delegate, scoped_ptr<IPC::ChannelProxy>* channel_out) { SECURITY_ATTRIBUTES security_attributes; security_attributes.nLength = sizeof(security_attributes); security_attributes.bInheritHandle = FALSE; ULONG security_descriptor_length = 0; if (!ConvertStringSecurityDescriptorToSecurityDescriptor( UTF8ToUTF16(pipe_security_descriptor).c_str(), SDDL_REVISION_1, reinterpret_cast<PSECURITY_DESCRIPTOR*>( &security_attributes.lpSecurityDescriptor), &security_descriptor_length)) { LOG_GETLASTERROR(ERROR) << "Failed to create a security descriptor for the Chromoting IPC channel"; return false; } std::string pipe_name(kChromePipeNamePrefix); pipe_name.append(channel_name); base::win::ScopedHandle pipe; pipe.Set(CreateNamedPipe( UTF8ToUTF16(pipe_name).c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, IPC::Channel::kReadBufferSize, IPC::Channel::kReadBufferSize, 5000, &security_attributes)); if (!pipe.IsValid()) { LOG_GETLASTERROR(ERROR) << "Failed to create the server end of the Chromoting IPC channel"; LocalFree(security_attributes.lpSecurityDescriptor); return false; } LocalFree(security_attributes.lpSecurityDescriptor); channel_out->reset(new IPC::ChannelProxy( IPC::ChannelHandle(pipe), IPC::Channel::MODE_SERVER, delegate, io_task_runner)); return true; } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool CreateIpcChannel( const std::string& channel_name, const std::string& pipe_security_descriptor, base::win::ScopedHandle* pipe_out) { SECURITY_ATTRIBUTES security_attributes; security_attributes.nLength = sizeof(security_attributes); security_attributes.bInheritHandle = FALSE; ULONG security_descriptor_length = 0; if (!ConvertStringSecurityDescriptorToSecurityDescriptor( UTF8ToUTF16(pipe_security_descriptor).c_str(), SDDL_REVISION_1, reinterpret_cast<PSECURITY_DESCRIPTOR*>( &security_attributes.lpSecurityDescriptor), &security_descriptor_length)) { LOG_GETLASTERROR(ERROR) << "Failed to create a security descriptor for the Chromoting IPC channel"; return false; } std::string pipe_name(kChromePipeNamePrefix); pipe_name.append(channel_name); base::win::ScopedHandle pipe; pipe.Set(CreateNamedPipe( UTF8ToUTF16(pipe_name).c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, IPC::Channel::kReadBufferSize, IPC::Channel::kReadBufferSize, 5000, &security_attributes)); if (!pipe.IsValid()) { LOG_GETLASTERROR(ERROR) << "Failed to create the server end of the Chromoting IPC channel"; LocalFree(security_attributes.lpSecurityDescriptor); return false; } LocalFree(security_attributes.lpSecurityDescriptor); *pipe_out = pipe.Pass(); return true; }
171,543
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dn_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; switch (sock->type) { case SOCK_SEQPACKET: if (protocol != DNPROTO_NSP) return -EPROTONOSUPPORT; break; case SOCK_STREAM: break; default: return -ESOCKTNOSUPPORT; } if ((sk = dn_alloc_sock(net, sock, GFP_KERNEL, kern)) == NULL) return -ENOBUFS; sk->sk_protocol = protocol; return 0; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int dn_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; if (protocol < 0 || protocol > SK_PROTOCOL_MAX) return -EINVAL; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; switch (sock->type) { case SOCK_SEQPACKET: if (protocol != DNPROTO_NSP) return -EPROTONOSUPPORT; break; case SOCK_STREAM: break; default: return -ESOCKTNOSUPPORT; } if ((sk = dn_alloc_sock(net, sock, GFP_KERNEL, kern)) == NULL) return -ENOBUFS; sk->sk_protocol = protocol; return 0; }
166,563
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int udpv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct ipv6_txoptions opt_space; struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name); struct in6_addr *daddr, *final_p, final; struct ipv6_txoptions *opt = NULL; struct ip6_flowlabel *flowlabel = NULL; struct flowi6 fl6; struct dst_entry *dst; int addr_len = msg->msg_namelen; int ulen = len; int hlimit = -1; int tclass = -1; int dontfrag = -1; int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; int err; int connected = 0; int is_udplite = IS_UDPLITE(sk); int (*getfrag)(void *, char *, int, int, int, struct sk_buff *); /* destination address check */ if (sin6) { if (addr_len < offsetof(struct sockaddr, sa_data)) return -EINVAL; switch (sin6->sin6_family) { case AF_INET6: if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; daddr = &sin6->sin6_addr; break; case AF_INET: goto do_udp_sendmsg; case AF_UNSPEC: msg->msg_name = sin6 = NULL; msg->msg_namelen = addr_len = 0; daddr = NULL; break; default: return -EINVAL; } } else if (!up->pending) { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = &sk->sk_v6_daddr; } else daddr = NULL; if (daddr) { if (ipv6_addr_v4mapped(daddr)) { struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = sin6 ? sin6->sin6_port : inet->inet_dport; sin.sin_addr.s_addr = daddr->s6_addr32[3]; msg->msg_name = &sin; msg->msg_namelen = sizeof(sin); do_udp_sendmsg: if (__ipv6_only_sock(sk)) return -ENETUNREACH; return udp_sendmsg(sk, msg, len); } } if (up->pending == AF_INET) return udp_sendmsg(sk, msg, len); /* Rough check on arithmetic overflow, better check is made in ip6_append_data(). */ if (len > INT_MAX - sizeof(struct udphdr)) return -EMSGSIZE; getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag; if (up->pending) { /* * There are pending frames. * The socket lock must be held while it's corked. */ lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET6)) { release_sock(sk); return -EAFNOSUPPORT; } dst = NULL; goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); memset(&fl6, 0, sizeof(fl6)); if (sin6) { if (sin6->sin6_port == 0) return -EINVAL; fl6.fl6_dport = sin6->sin6_port; daddr = &sin6->sin6_addr; if (np->sndflow) { fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } } /* * Otherwise it will be difficult to maintain * sk->sk_dst_cache. */ if (sk->sk_state == TCP_ESTABLISHED && ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) daddr = &sk->sk_v6_daddr; if (addr_len >= sizeof(struct sockaddr_in6) && sin6->sin6_scope_id && __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr))) fl6.flowi6_oif = sin6->sin6_scope_id; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; fl6.fl6_dport = inet->inet_dport; daddr = &sk->sk_v6_daddr; fl6.flowlabel = np->flow_label; connected = 1; } if (!fl6.flowi6_oif) fl6.flowi6_oif = sk->sk_bound_dev_if; if (!fl6.flowi6_oif) fl6.flowi6_oif = np->sticky_pktinfo.ipi6_ifindex; fl6.flowi6_mark = sk->sk_mark; if (msg->msg_controllen) { opt = &opt_space; memset(opt, 0, sizeof(struct ipv6_txoptions)); opt->tot_len = sizeof(*opt); err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, &hlimit, &tclass, &dontfrag); if (err < 0) { fl6_sock_release(flowlabel); return err; } if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } if (!(opt->opt_nflen|opt->opt_flen)) opt = NULL; connected = 0; } if (!opt) opt = np->opt; if (flowlabel) opt = fl6_merge_options(&opt_space, flowlabel, opt); opt = ipv6_fixup_options(&opt_space, opt); fl6.flowi6_proto = sk->sk_protocol; if (!ipv6_addr_any(daddr)) fl6.daddr = *daddr; else fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) fl6.saddr = np->saddr; fl6.fl6_sport = inet->inet_sport; final_p = fl6_update_dst(&fl6, opt, &final); if (final_p) connected = 0; if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) { fl6.flowi6_oif = np->mcast_oif; connected = 0; } else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); dst = ip6_sk_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); dst = NULL; goto out; } if (hlimit < 0) hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); if (tclass < 0) tclass = np->tclass; if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: /* Lockless fast path for the non-corking case */ if (!corkreq) { struct sk_buff *skb; skb = ip6_make_skb(sk, getfrag, msg, ulen, sizeof(struct udphdr), hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, msg->msg_flags, dontfrag); err = PTR_ERR(skb); if (!IS_ERR_OR_NULL(skb)) err = udp_v6_send_skb(skb, &fl6); goto release_dst; } lock_sock(sk); if (unlikely(up->pending)) { /* The socket is already corked while preparing it. */ /* ... which is an evident application bug. --ANK */ release_sock(sk); net_dbg_ratelimited("udp cork app bug 2\n"); err = -EINVAL; goto out; } up->pending = AF_INET6; do_append_data: if (dontfrag < 0) dontfrag = np->dontfrag; up->len += ulen; err = ip6_append_data(sk, getfrag, msg, ulen, sizeof(struct udphdr), hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags, dontfrag); if (err) udp_v6_flush_pending_frames(sk); else if (!corkreq) err = udp_v6_push_pending_frames(sk); else if (unlikely(skb_queue_empty(&sk->sk_write_queue))) up->pending = 0; if (err > 0) err = np->recverr ? net_xmit_errno(err) : 0; release_sock(sk); release_dst: if (dst) { if (connected) { ip6_dst_store(sk, dst, ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ? &sk->sk_v6_daddr : NULL, #ifdef CONFIG_IPV6_SUBTREES ipv6_addr_equal(&fl6.saddr, &np->saddr) ? &np->saddr : #endif NULL); } else { dst_release(dst); } dst = NULL; } out: dst_release(dst); fl6_sock_release(flowlabel); if (!err) return len; /* * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting * ENOBUFS might not be good (it's not tunable per se), but otherwise * we don't have a good statistic (IpOutDiscards but it can be too many * things). We could add another new stat but at least for now that * seems like overkill. */ if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); } return err; do_confirm: dst_confirm(dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; } 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 udpv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct ipv6_txoptions opt_space; struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name); struct in6_addr *daddr, *final_p, final; struct ipv6_txoptions *opt = NULL; struct ipv6_txoptions *opt_to_free = NULL; struct ip6_flowlabel *flowlabel = NULL; struct flowi6 fl6; struct dst_entry *dst; int addr_len = msg->msg_namelen; int ulen = len; int hlimit = -1; int tclass = -1; int dontfrag = -1; int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; int err; int connected = 0; int is_udplite = IS_UDPLITE(sk); int (*getfrag)(void *, char *, int, int, int, struct sk_buff *); /* destination address check */ if (sin6) { if (addr_len < offsetof(struct sockaddr, sa_data)) return -EINVAL; switch (sin6->sin6_family) { case AF_INET6: if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; daddr = &sin6->sin6_addr; break; case AF_INET: goto do_udp_sendmsg; case AF_UNSPEC: msg->msg_name = sin6 = NULL; msg->msg_namelen = addr_len = 0; daddr = NULL; break; default: return -EINVAL; } } else if (!up->pending) { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = &sk->sk_v6_daddr; } else daddr = NULL; if (daddr) { if (ipv6_addr_v4mapped(daddr)) { struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = sin6 ? sin6->sin6_port : inet->inet_dport; sin.sin_addr.s_addr = daddr->s6_addr32[3]; msg->msg_name = &sin; msg->msg_namelen = sizeof(sin); do_udp_sendmsg: if (__ipv6_only_sock(sk)) return -ENETUNREACH; return udp_sendmsg(sk, msg, len); } } if (up->pending == AF_INET) return udp_sendmsg(sk, msg, len); /* Rough check on arithmetic overflow, better check is made in ip6_append_data(). */ if (len > INT_MAX - sizeof(struct udphdr)) return -EMSGSIZE; getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag; if (up->pending) { /* * There are pending frames. * The socket lock must be held while it's corked. */ lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET6)) { release_sock(sk); return -EAFNOSUPPORT; } dst = NULL; goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); memset(&fl6, 0, sizeof(fl6)); if (sin6) { if (sin6->sin6_port == 0) return -EINVAL; fl6.fl6_dport = sin6->sin6_port; daddr = &sin6->sin6_addr; if (np->sndflow) { fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } } /* * Otherwise it will be difficult to maintain * sk->sk_dst_cache. */ if (sk->sk_state == TCP_ESTABLISHED && ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) daddr = &sk->sk_v6_daddr; if (addr_len >= sizeof(struct sockaddr_in6) && sin6->sin6_scope_id && __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr))) fl6.flowi6_oif = sin6->sin6_scope_id; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; fl6.fl6_dport = inet->inet_dport; daddr = &sk->sk_v6_daddr; fl6.flowlabel = np->flow_label; connected = 1; } if (!fl6.flowi6_oif) fl6.flowi6_oif = sk->sk_bound_dev_if; if (!fl6.flowi6_oif) fl6.flowi6_oif = np->sticky_pktinfo.ipi6_ifindex; fl6.flowi6_mark = sk->sk_mark; if (msg->msg_controllen) { opt = &opt_space; memset(opt, 0, sizeof(struct ipv6_txoptions)); opt->tot_len = sizeof(*opt); err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, &hlimit, &tclass, &dontfrag); if (err < 0) { fl6_sock_release(flowlabel); return err; } if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } if (!(opt->opt_nflen|opt->opt_flen)) opt = NULL; connected = 0; } if (!opt) { opt = txopt_get(np); opt_to_free = opt; } if (flowlabel) opt = fl6_merge_options(&opt_space, flowlabel, opt); opt = ipv6_fixup_options(&opt_space, opt); fl6.flowi6_proto = sk->sk_protocol; if (!ipv6_addr_any(daddr)) fl6.daddr = *daddr; else fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) fl6.saddr = np->saddr; fl6.fl6_sport = inet->inet_sport; final_p = fl6_update_dst(&fl6, opt, &final); if (final_p) connected = 0; if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) { fl6.flowi6_oif = np->mcast_oif; connected = 0; } else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); dst = ip6_sk_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); dst = NULL; goto out; } if (hlimit < 0) hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); if (tclass < 0) tclass = np->tclass; if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: /* Lockless fast path for the non-corking case */ if (!corkreq) { struct sk_buff *skb; skb = ip6_make_skb(sk, getfrag, msg, ulen, sizeof(struct udphdr), hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, msg->msg_flags, dontfrag); err = PTR_ERR(skb); if (!IS_ERR_OR_NULL(skb)) err = udp_v6_send_skb(skb, &fl6); goto release_dst; } lock_sock(sk); if (unlikely(up->pending)) { /* The socket is already corked while preparing it. */ /* ... which is an evident application bug. --ANK */ release_sock(sk); net_dbg_ratelimited("udp cork app bug 2\n"); err = -EINVAL; goto out; } up->pending = AF_INET6; do_append_data: if (dontfrag < 0) dontfrag = np->dontfrag; up->len += ulen; err = ip6_append_data(sk, getfrag, msg, ulen, sizeof(struct udphdr), hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags, dontfrag); if (err) udp_v6_flush_pending_frames(sk); else if (!corkreq) err = udp_v6_push_pending_frames(sk); else if (unlikely(skb_queue_empty(&sk->sk_write_queue))) up->pending = 0; if (err > 0) err = np->recverr ? net_xmit_errno(err) : 0; release_sock(sk); release_dst: if (dst) { if (connected) { ip6_dst_store(sk, dst, ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ? &sk->sk_v6_daddr : NULL, #ifdef CONFIG_IPV6_SUBTREES ipv6_addr_equal(&fl6.saddr, &np->saddr) ? &np->saddr : #endif NULL); } else { dst_release(dst); } dst = NULL; } out: dst_release(dst); fl6_sock_release(flowlabel); txopt_put(opt_to_free); if (!err) return len; /* * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting * ENOBUFS might not be good (it's not tunable per se), but otherwise * we don't have a good statistic (IpOutDiscards but it can be too many * things). We could add another new stat but at least for now that * seems like overkill. */ if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); } return err; do_confirm: dst_confirm(dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; }
167,343
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int rndis_query_response(USBNetState *s, rndis_query_msg_type *buf, unsigned int length) { rndis_query_cmplt_type *resp; /* oid_supported_list is the largest data reply */ uint8_t infobuf[sizeof(oid_supported_list)]; uint32_t bufoffs, buflen; int infobuflen; unsigned int resplen; bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8; buflen = le32_to_cpu(buf->InformationBufferLength); if (bufoffs + buflen > length) return USB_RET_STALL; infobuflen = ndis_query(s, le32_to_cpu(buf->OID), bufoffs + (uint8_t *) buf, buflen, infobuf, resplen = sizeof(rndis_query_cmplt_type) + ((infobuflen < 0) ? 0 : infobuflen); resp = rndis_queue_response(s, resplen); if (!resp) return USB_RET_STALL; resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT); resp->RequestID = buf->RequestID; /* Still LE in msg buffer */ resp->MessageLength = cpu_to_le32(resplen); if (infobuflen < 0) { /* OID not supported */ resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); resp->InformationBufferLength = cpu_to_le32(0); resp->InformationBufferOffset = cpu_to_le32(0); return 0; } resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); resp->InformationBufferOffset = cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0); resp->InformationBufferLength = cpu_to_le32(infobuflen); memcpy(resp + 1, infobuf, infobuflen); return 0; } Commit Message: CWE ID: CWE-189
static int rndis_query_response(USBNetState *s, rndis_query_msg_type *buf, unsigned int length) { rndis_query_cmplt_type *resp; /* oid_supported_list is the largest data reply */ uint8_t infobuf[sizeof(oid_supported_list)]; uint32_t bufoffs, buflen; int infobuflen; unsigned int resplen; bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8; buflen = le32_to_cpu(buf->InformationBufferLength); if (buflen > length || bufoffs >= length || bufoffs + buflen > length) { return USB_RET_STALL; } infobuflen = ndis_query(s, le32_to_cpu(buf->OID), bufoffs + (uint8_t *) buf, buflen, infobuf, resplen = sizeof(rndis_query_cmplt_type) + ((infobuflen < 0) ? 0 : infobuflen); resp = rndis_queue_response(s, resplen); if (!resp) return USB_RET_STALL; resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT); resp->RequestID = buf->RequestID; /* Still LE in msg buffer */ resp->MessageLength = cpu_to_le32(resplen); if (infobuflen < 0) { /* OID not supported */ resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); resp->InformationBufferLength = cpu_to_le32(0); resp->InformationBufferOffset = cpu_to_le32(0); return 0; } resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); resp->InformationBufferOffset = cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0); resp->InformationBufferLength = cpu_to_le32(infobuflen); memcpy(resp + 1, infobuf, infobuflen); return 0; }
165,185
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void unqueue_me_pi(struct futex_q *q) { WARN_ON(plist_node_empty(&q->list)); plist_del(&q->list, &q->list.plist); BUG_ON(!q->pi_state); free_pi_state(q->pi_state); q->pi_state = NULL; spin_unlock(q->lock_ptr); drop_futex_key_refs(&q->key); } Commit Message: futex: Fix errors in nested key ref-counting futex_wait() is leaking key references due to futex_wait_setup() acquiring an additional reference via the queue_lock() routine. The nested key ref-counting has been masking bugs and complicating code analysis. queue_lock() is only called with a previously ref-counted key, so remove the additional ref-counting from the queue_(un)lock() functions. Also futex_wait_requeue_pi() drops one key reference too many in unqueue_me_pi(). Remove the key reference handling from unqueue_me_pi(). This was paired with a queue_lock() in futex_lock_pi(), so the count remains unchanged. Document remaining nested key ref-counting sites. Signed-off-by: Darren Hart <[email protected]> Reported-and-tested-by: Matthieu Fertré<[email protected]> Reported-by: Louis Rilling<[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Eric Dumazet <[email protected]> Cc: John Kacur <[email protected]> Cc: Rusty Russell <[email protected]> LKML-Reference: <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Cc: [email protected] CWE ID: CWE-119
static void unqueue_me_pi(struct futex_q *q) { WARN_ON(plist_node_empty(&q->list)); plist_del(&q->list, &q->list.plist); BUG_ON(!q->pi_state); free_pi_state(q->pi_state); q->pi_state = NULL; spin_unlock(q->lock_ptr); }
166,453
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SVGStyleElement::DidNotifySubtreeInsertionsToDocument() { if (StyleElement::ProcessStyleSheet(GetDocument(), *this) == StyleElement::kProcessingFatalError) NotifyLoadedSheetAndAllCriticalSubresources( kErrorOccurredLoadingSubresource); } Commit Message: Do not crash while reentrantly appending to style element. When a node is inserted into a container, it is notified via ::InsertedInto. However, a node may request a second notification via DidNotifySubtreeInsertionsToDocument, which occurs after all the children have been notified as well. *StyleElement is currently using this second notification. This causes a problem, because *ScriptElement is using the same mechanism, which in turn means that scripts can execute before the state of *StyleElements are properly updated. This patch avoids ::DidNotifySubtreeInsertionsToDocument, and instead processes the stylesheet in ::InsertedInto. The original reason for using ::DidNotifySubtreeInsertionsToDocument in the first place appears to be invalid now, as the test case is still passing. [email protected], [email protected] Bug: 853709, 847570 Cq-Include-Trybots: luci.chromium.try:linux_layout_tests_slimming_paint_v2;master.tryserver.blink:linux_trusty_blink_rel Change-Id: Ic0b5fa611044c78c5745cf26870a747f88920a14 Reviewed-on: https://chromium-review.googlesource.com/1104347 Commit-Queue: Anders Ruud <[email protected]> Reviewed-by: Rune Lillesveen <[email protected]> Cr-Commit-Position: refs/heads/master@{#568368} CWE ID: CWE-416
void SVGStyleElement::DidNotifySubtreeInsertionsToDocument() { if (isConnected()) { if (StyleElement::ProcessStyleSheet(GetDocument(), *this) == StyleElement::kProcessingFatalError) { NotifyLoadedSheetAndAllCriticalSubresources( kErrorOccurredLoadingSubresource); } } return kInsertionDone; }
173,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned paravirt_patch_call(void *insnbuf, const void *target, u16 tgt_clobbers, unsigned long addr, u16 site_clobbers, unsigned len) { struct branch *b = insnbuf; unsigned long delta = (unsigned long)target - (addr+5); if (tgt_clobbers & ~site_clobbers) return len; /* target would clobber too much for this site */ if (len < 5) return len; /* call too long for patch site */ b->opcode = 0xe8; /* call */ b->delta = delta; BUILD_BUG_ON(sizeof(*b) != 5); return 5; } Commit Message: x86/paravirt: Fix spectre-v2 mitigations for paravirt guests Nadav reported that on guests we're failing to rewrite the indirect calls to CALLEE_SAVE paravirt functions. In particular the pv_queued_spin_unlock() call is left unpatched and that is all over the place. This obviously wrecks Spectre-v2 mitigation (for paravirt guests) which relies on not actually having indirect calls around. The reason is an incorrect clobber test in paravirt_patch_call(); this function rewrites an indirect call with a direct call to the _SAME_ function, there is no possible way the clobbers can be different because of this. Therefore remove this clobber check. Also put WARNs on the other patch failure case (not enough room for the instruction) which I've not seen trigger in my (limited) testing. Three live kernel image disassemblies for lock_sock_nested (as a small function that illustrates the problem nicely). PRE is the current situation for guests, POST is with this patch applied and NATIVE is with or without the patch for !guests. PRE: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: callq *0xffffffff822299e8 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. POST: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: callq 0xffffffff810a0c20 <__raw_callee_save___pv_queued_spin_unlock> 0xffffffff817be9a5 <+53>: xchg %ax,%ax 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063aa0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. NATIVE: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: movb $0x0,(%rdi) 0xffffffff817be9a3 <+51>: nopl 0x0(%rax) 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. Fixes: 63f70270ccd9 ("[PATCH] i386: PARAVIRT: add common patching machinery") Fixes: 3010a0663fd9 ("x86/paravirt, objtool: Annotate indirect calls") Reported-by: Nadav Amit <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Juergen Gross <[email protected]> Cc: Konrad Rzeszutek Wilk <[email protected]> Cc: Boris Ostrovsky <[email protected]> Cc: David Woodhouse <[email protected]> Cc: [email protected] CWE ID: CWE-200
unsigned paravirt_patch_call(void *insnbuf, const void *target, u16 tgt_clobbers, unsigned long addr, u16 site_clobbers, unsigned len) { struct branch *b = insnbuf; unsigned long delta = (unsigned long)target - (addr+5); if (len < 5) { #ifdef CONFIG_RETPOLINE WARN_ONCE("Failing to patch indirect CALL in %ps\n", (void *)addr); #endif return len; /* call too long for patch site */ } b->opcode = 0xe8; /* call */ b->delta = delta; BUILD_BUG_ON(sizeof(*b) != 5); return 5; }
169,099
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: LayerTreeHostQt::LayerTreeHostQt(WebPage* webPage) : LayerTreeHost(webPage) , m_notifyAfterScheduledLayerFlush(false) , m_isValid(true) #if USE(TILED_BACKING_STORE) , m_waitingForUIProcess(false) , m_isSuspended(false) , m_contentsScale(1) #endif , m_shouldSyncFrame(false) , m_shouldSyncRootLayer(true) , m_layerFlushTimer(this, &LayerTreeHostQt::layerFlushTimerFired) , m_layerFlushSchedulingEnabled(true) { m_rootLayer = GraphicsLayer::create(this); WebGraphicsLayer* webRootLayer = toWebGraphicsLayer(m_rootLayer.get()); webRootLayer->setRootLayer(true); #ifndef NDEBUG m_rootLayer->setName("LayerTreeHostQt root layer"); #endif m_rootLayer->setDrawsContent(false); m_rootLayer->setSize(m_webPage->size()); m_layerTreeContext.webLayerID = toWebGraphicsLayer(webRootLayer)->id(); m_nonCompositedContentLayer = GraphicsLayer::create(this); #if USE(TILED_BACKING_STORE) toWebGraphicsLayer(m_rootLayer.get())->setWebGraphicsLayerClient(this); #endif #ifndef NDEBUG m_nonCompositedContentLayer->setName("LayerTreeHostQt non-composited content"); #endif m_nonCompositedContentLayer->setDrawsContent(true); m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground()); m_nonCompositedContentLayer->setSize(m_webPage->size()); m_rootLayer->addChild(m_nonCompositedContentLayer.get()); if (m_webPage->hasPageOverlay()) createPageOverlayLayer(); scheduleLayerFlush(); } Commit Message: [Qt][WK2] Allow transparent WebViews https://bugs.webkit.org/show_bug.cgi?id=80608 Reviewed by Tor Arne Vestbø. Added support for transparentBackground in QQuickWebViewExperimental. This uses the existing drawsTransparentBackground property in WebKit2. Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes, otherwise the change doesn't take effect. A new API test was added. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::setTransparentBackground): (QQuickWebViewPrivate::transparentBackground): (QQuickWebViewExperimental::transparentBackground): (QQuickWebViewExperimental::setTransparentBackground): * UIProcess/API/qt/qquickwebview_p.h: * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): * UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp: (tst_QQuickWebView): (tst_QQuickWebView::transparentWebViews): * WebProcess/WebPage/qt/LayerTreeHostQt.cpp: (WebKit::LayerTreeHostQt::LayerTreeHostQt): (WebKit::LayerTreeHostQt::setRootCompositingLayer): git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-189
LayerTreeHostQt::LayerTreeHostQt(WebPage* webPage) : LayerTreeHost(webPage) , m_notifyAfterScheduledLayerFlush(false) , m_isValid(true) #if USE(TILED_BACKING_STORE) , m_waitingForUIProcess(false) , m_isSuspended(false) , m_contentsScale(1) #endif , m_shouldSyncFrame(false) , m_shouldSyncRootLayer(true) , m_layerFlushTimer(this, &LayerTreeHostQt::layerFlushTimerFired) , m_layerFlushSchedulingEnabled(true) { m_rootLayer = GraphicsLayer::create(this); WebGraphicsLayer* webRootLayer = toWebGraphicsLayer(m_rootLayer.get()); webRootLayer->setRootLayer(true); #ifndef NDEBUG m_rootLayer->setName("LayerTreeHostQt root layer"); #endif m_rootLayer->setDrawsContent(false); m_rootLayer->setSize(m_webPage->size()); m_layerTreeContext.webLayerID = toWebGraphicsLayer(webRootLayer)->id(); m_nonCompositedContentLayer = GraphicsLayer::create(this); #if USE(TILED_BACKING_STORE) toWebGraphicsLayer(m_rootLayer.get())->setWebGraphicsLayerClient(this); #endif #ifndef NDEBUG m_nonCompositedContentLayer->setName("LayerTreeHostQt non-composited content"); #endif m_nonCompositedContentLayer->setDrawsContent(true); m_nonCompositedContentLayer->setSize(m_webPage->size()); m_rootLayer->addChild(m_nonCompositedContentLayer.get()); if (m_webPage->hasPageOverlay()) createPageOverlayLayer(); scheduleLayerFlush(); }
170,618
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServiceWorkerHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; if (!process_host) { ClearForceUpdate(); context_ = nullptr; return; } StoragePartition* partition = process_host->GetStoragePartition(); DCHECK(partition); context_ = static_cast<ServiceWorkerContextWrapper*>( partition->GetServiceWorkerContext()); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void ServiceWorkerHandler::SetRenderer(RenderProcessHost* process_host, void ServiceWorkerHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { RenderProcessHost* process_host = RenderProcessHost::FromID(process_host_id); if (!process_host) { ClearForceUpdate(); context_ = nullptr; return; } storage_partition_ = static_cast<StoragePartitionImpl*>(process_host->GetStoragePartition()); DCHECK(storage_partition_); context_ = static_cast<ServiceWorkerContextWrapper*>( storage_partition_->GetServiceWorkerContext()); }
172,769
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppModalDialog::CompleteDialog() { AppModalDialogQueue::GetInstance()->ShowNextDialog(); } Commit Message: Fix a Windows crash bug with javascript alerts from extension popups. BUG=137707 Review URL: https://chromiumcodereview.appspot.com/10828423 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void AppModalDialog::CompleteDialog() { if (!completed_) { completed_ = true; AppModalDialogQueue::GetInstance()->ShowNextDialog(); } }
170,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, Packet *p, Flow * const pflow) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP); /* cleanup pkt specific part of the patternmatcher */ PacketPatternCleanup(det_ctx); if (pflow != NULL) { /* update inspected tracker for raw reassembly */ if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) { StreamReassembleRawUpdateProgress(pflow->protoctx, p, det_ctx->raw_stream_progress); DetectEngineCleanHCBDBuffers(det_ctx); } } PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP); SCReturn; } Commit Message: stream: fix false negative on bad RST If a bad RST was received the stream inspection would not happen for that packet, but it would still move the 'raw progress' tracker forward. Following good packets would then fail to detect anything before the 'raw progress' position. Bug #2770 Reported-by: Alexey Vishnyakov CWE ID: CWE-347
static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, Packet *p, Flow * const pflow) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP); /* cleanup pkt specific part of the patternmatcher */ PacketPatternCleanup(det_ctx); if (pflow != NULL) { /* update inspected tracker for raw reassembly */ if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL && (p->flags & PKT_STREAM_EST)) { StreamReassembleRawUpdateProgress(pflow->protoctx, p, det_ctx->raw_stream_progress); DetectEngineCleanHCBDBuffers(det_ctx); } } PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP); SCReturn; }
169,475
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int wrmsr_interception(struct vcpu_svm *svm) { struct msr_data msr; u32 ecx = svm->vcpu.arch.regs[VCPU_REGS_RCX]; u64 data = (svm->vcpu.arch.regs[VCPU_REGS_RAX] & -1u) | ((u64)(svm->vcpu.arch.regs[VCPU_REGS_RDX] & -1u) << 32); msr.data = data; msr.index = ecx; msr.host_initiated = false; svm->next_rip = kvm_rip_read(&svm->vcpu) + 2; if (svm_set_msr(&svm->vcpu, &msr)) { trace_kvm_msr_write_ex(ecx, data); kvm_inject_gp(&svm->vcpu, 0); } else { trace_kvm_msr_write(ecx, data); skip_emulated_instruction(&svm->vcpu); } return 1; } Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is written to certain MSRs. The behavior is "almost" identical for AMD and Intel (ignoring MSRs that are not implemented in either architecture since they would anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if non-canonical address is written on Intel but not on AMD (which ignores the top 32-bits). Accordingly, this patch injects a #GP on the MSRs which behave identically on Intel and AMD. To eliminate the differences between the architecutres, the value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to canonical value before writing instead of injecting a #GP. Some references from Intel and AMD manuals: According to Intel SDM description of WRMSR instruction #GP is expected on WRMSR "If the source register contains a non-canonical address and ECX specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE, IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP." According to AMD manual instruction manual: LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical form, a general-protection exception (#GP) occurs." IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the base field must be in canonical form or a #GP fault will occur." IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must be in canonical form." This patch fixes CVE-2014-3610. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static int wrmsr_interception(struct vcpu_svm *svm) { struct msr_data msr; u32 ecx = svm->vcpu.arch.regs[VCPU_REGS_RCX]; u64 data = (svm->vcpu.arch.regs[VCPU_REGS_RAX] & -1u) | ((u64)(svm->vcpu.arch.regs[VCPU_REGS_RDX] & -1u) << 32); msr.data = data; msr.index = ecx; msr.host_initiated = false; svm->next_rip = kvm_rip_read(&svm->vcpu) + 2; if (kvm_set_msr(&svm->vcpu, &msr)) { trace_kvm_msr_write_ex(ecx, data); kvm_inject_gp(&svm->vcpu, 0); } else { trace_kvm_msr_write(ecx, data); skip_emulated_instruction(&svm->vcpu); } return 1; }
166,348
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_video::get_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_INOUT OMX_PTR configData) { (void)hComp; if (configData == NULL) { DEBUG_PRINT_ERROR("ERROR: param is null"); return OMX_ErrorBadParameter; } if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: can't be in invalid state"); return OMX_ErrorIncorrectStateOperation; } switch ((int)configIndex) { case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData); memcpy(pParam, &m_sConfigBitrate, sizeof(m_sConfigBitrate)); break; } case OMX_IndexConfigVideoFramerate: { OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData); memcpy(pParam, &m_sConfigFramerate, sizeof(m_sConfigFramerate)); break; } case OMX_IndexConfigCommonRotate: { OMX_CONFIG_ROTATIONTYPE* pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData); memcpy(pParam, &m_sConfigFrameRotation, sizeof(m_sConfigFrameRotation)); break; } case QOMX_IndexConfigVideoIntraperiod: { DEBUG_PRINT_LOW("get_config:QOMX_IndexConfigVideoIntraperiod"); QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData); memcpy(pParam, &m_sIntraperiod, sizeof(m_sIntraperiod)); break; } case OMX_IndexConfigVideoAVCIntraPeriod: { OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam = reinterpret_cast<OMX_VIDEO_CONFIG_AVCINTRAPERIOD*>(configData); DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoAVCIntraPeriod"); memcpy(pParam, &m_sConfigAVCIDRPeriod, sizeof(m_sConfigAVCIDRPeriod)); break; } case OMX_IndexConfigCommonDeinterlace: { OMX_VIDEO_CONFIG_DEINTERLACE *pParam = reinterpret_cast<OMX_VIDEO_CONFIG_DEINTERLACE*>(configData); DEBUG_PRINT_LOW("get_config: OMX_IndexConfigCommonDeinterlace"); memcpy(pParam, &m_sConfigDeinterlace, sizeof(m_sConfigDeinterlace)); break; } case OMX_IndexConfigVideoVp8ReferenceFrame: { OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam = reinterpret_cast<OMX_VIDEO_VP8REFERENCEFRAMETYPE*>(configData); DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoVp8ReferenceFrame"); memcpy(pParam, &m_sConfigVp8ReferenceFrame, sizeof(m_sConfigVp8ReferenceFrame)); break; } case OMX_QcomIndexConfigPerfLevel: { OMX_U32 perflevel; OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *pParam = reinterpret_cast<OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL*>(configData); DEBUG_PRINT_LOW("get_config: OMX_QcomIndexConfigPerfLevel"); if (!dev_get_performance_level(&perflevel)) { DEBUG_PRINT_ERROR("Invalid entry returned from get_performance_level %d", pParam->ePerfLevel); } else { pParam->ePerfLevel = (QOMX_VIDEO_PERF_LEVEL)perflevel; } break; } default: DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex); return OMX_ErrorUnsupportedIndex; } return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
OMX_ERRORTYPE omx_video::get_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_INOUT OMX_PTR configData) { (void)hComp; if (configData == NULL) { DEBUG_PRINT_ERROR("ERROR: param is null"); return OMX_ErrorBadParameter; } if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: can't be in invalid state"); return OMX_ErrorIncorrectStateOperation; } switch ((int)configIndex) { case OMX_IndexConfigVideoBitrate: { VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_BITRATETYPE); OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData); memcpy(pParam, &m_sConfigBitrate, sizeof(m_sConfigBitrate)); break; } case OMX_IndexConfigVideoFramerate: { VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_FRAMERATETYPE); OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData); memcpy(pParam, &m_sConfigFramerate, sizeof(m_sConfigFramerate)); break; } case OMX_IndexConfigCommonRotate: { VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_ROTATIONTYPE); OMX_CONFIG_ROTATIONTYPE* pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData); memcpy(pParam, &m_sConfigFrameRotation, sizeof(m_sConfigFrameRotation)); break; } case QOMX_IndexConfigVideoIntraperiod: { DEBUG_PRINT_LOW("get_config:QOMX_IndexConfigVideoIntraperiod"); VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_INTRAPERIODTYPE); QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData); memcpy(pParam, &m_sIntraperiod, sizeof(m_sIntraperiod)); break; } case OMX_IndexConfigVideoAVCIntraPeriod: { VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_AVCINTRAPERIOD); OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam = reinterpret_cast<OMX_VIDEO_CONFIG_AVCINTRAPERIOD*>(configData); DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoAVCIntraPeriod"); memcpy(pParam, &m_sConfigAVCIDRPeriod, sizeof(m_sConfigAVCIDRPeriod)); break; } case OMX_IndexConfigCommonDeinterlace: { VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_DEINTERLACE); OMX_VIDEO_CONFIG_DEINTERLACE *pParam = reinterpret_cast<OMX_VIDEO_CONFIG_DEINTERLACE*>(configData); DEBUG_PRINT_LOW("get_config: OMX_IndexConfigCommonDeinterlace"); memcpy(pParam, &m_sConfigDeinterlace, sizeof(m_sConfigDeinterlace)); break; } case OMX_IndexConfigVideoVp8ReferenceFrame: { VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_VP8REFERENCEFRAMETYPE); OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam = reinterpret_cast<OMX_VIDEO_VP8REFERENCEFRAMETYPE*>(configData); DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoVp8ReferenceFrame"); memcpy(pParam, &m_sConfigVp8ReferenceFrame, sizeof(m_sConfigVp8ReferenceFrame)); break; } case OMX_QcomIndexConfigPerfLevel: { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL); OMX_U32 perflevel; OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *pParam = reinterpret_cast<OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL*>(configData); DEBUG_PRINT_LOW("get_config: OMX_QcomIndexConfigPerfLevel"); if (!dev_get_performance_level(&perflevel)) { DEBUG_PRINT_ERROR("Invalid entry returned from get_performance_level %d", pParam->ePerfLevel); } else { pParam->ePerfLevel = (QOMX_VIDEO_PERF_LEVEL)perflevel; } break; } default: DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex); return OMX_ErrorUnsupportedIndex; } return OMX_ErrorNone; }
173,793
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TouchEventHandler::handleTouchPoint(Platform::TouchPoint& point, unsigned modifiers) { m_webPage->m_inputHandler->setInputModeEnabled(); bool shiftActive = modifiers & KEYMOD_SHIFT; bool altActive = modifiers & KEYMOD_ALT; bool ctrlActive = modifiers & KEYMOD_CTRL; switch (point.m_state) { case Platform::TouchPoint::TouchPressed: { m_webPage->m_inputHandler->clearDidSpellCheckState(); if (!m_lastFatFingersResult.isValid()) doFatFingers(point); Element* elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable(); if (m_lastFatFingersResult.isTextInput()) { elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable(FatFingersResult::ShadowContentNotAllowed, true /* shouldUseRootEditableElement */); m_shouldRequestSpellCheckOptions = m_webPage->m_inputHandler->shouldRequestSpellCheckingOptionsForPoint(point.m_pos, elementUnderFatFinger, m_spellCheckOptionRequest); } handleFatFingerPressed(shiftActive, altActive, ctrlActive); break; } case Platform::TouchPoint::TouchReleased: { if (!m_shouldRequestSpellCheckOptions) m_webPage->m_inputHandler->processPendingKeyboardVisibilityChange(); if (m_webPage->m_inputHandler->isInputMode()) m_webPage->m_inputHandler->notifyClientOfKeyboardVisibilityChange(true); m_webPage->m_tapHighlight->hide(); IntPoint adjustedPoint = m_webPage->mapFromContentsToViewport(m_lastFatFingersResult.adjustedPosition()); PlatformMouseEvent mouseEvent(adjustedPoint, m_lastScreenPoint, PlatformEvent::MouseReleased, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen); m_webPage->handleMouseEvent(mouseEvent); if (m_shouldRequestSpellCheckOptions) { IntPoint pixelPositionRelativeToViewport = m_webPage->mapToTransformed(adjustedPoint); IntSize screenOffset(m_lastScreenPoint - pixelPositionRelativeToViewport); m_webPage->m_inputHandler->requestSpellingCheckingOptions(m_spellCheckOptionRequest, screenOffset); m_shouldRequestSpellCheckOptions = false; } m_lastFatFingersResult.reset(); // Reset the fat finger result as its no longer valid when a user's finger is not on the screen. break; } case Platform::TouchPoint::TouchMoved: { m_webPage->m_inputHandler->clearDidSpellCheckState(); PlatformMouseEvent mouseEvent(point.m_pos, m_lastScreenPoint, PlatformEvent::MouseMoved, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen); m_lastScreenPoint = point.m_screenPos; m_webPage->handleMouseEvent(mouseEvent); break; } default: break; } } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void TouchEventHandler::handleTouchPoint(Platform::TouchPoint& point, unsigned modifiers) void TouchEventHandler::handleTouchPoint(const Platform::TouchPoint& point, unsigned modifiers) { m_webPage->m_inputHandler->setInputModeEnabled(); bool shiftActive = modifiers & KEYMOD_SHIFT; bool altActive = modifiers & KEYMOD_ALT; bool ctrlActive = modifiers & KEYMOD_CTRL; switch (point.state()) { case Platform::TouchPoint::TouchPressed: { m_webPage->m_inputHandler->clearDidSpellCheckState(); if (!m_lastFatFingersResult.isValid()) doFatFingers(point); Element* elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable(); if (m_lastFatFingersResult.isTextInput()) { elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable(FatFingersResult::ShadowContentNotAllowed, true /* shouldUseRootEditableElement */); m_shouldRequestSpellCheckOptions = m_webPage->m_inputHandler->shouldRequestSpellCheckingOptionsForPoint(point.documentContentPosition(), elementUnderFatFinger, m_spellCheckOptionRequest); } handleFatFingerPressed(shiftActive, altActive, ctrlActive); break; } case Platform::TouchPoint::TouchReleased: { if (!m_shouldRequestSpellCheckOptions) m_webPage->m_inputHandler->processPendingKeyboardVisibilityChange(); if (m_webPage->m_inputHandler->isInputMode()) m_webPage->m_inputHandler->notifyClientOfKeyboardVisibilityChange(true); m_webPage->m_tapHighlight->hide(); IntPoint adjustedPoint = m_webPage->mapFromContentsToViewport(m_lastFatFingersResult.adjustedPosition()); PlatformMouseEvent mouseEvent(adjustedPoint, m_lastScreenPoint, PlatformEvent::MouseReleased, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen); m_webPage->handleMouseEvent(mouseEvent); if (m_shouldRequestSpellCheckOptions) { IntPoint pixelPositionRelativeToViewport = m_webPage->mapToTransformed(adjustedPoint); IntSize screenOffset(m_lastScreenPoint - pixelPositionRelativeToViewport); m_webPage->m_inputHandler->requestSpellingCheckingOptions(m_spellCheckOptionRequest, screenOffset); m_shouldRequestSpellCheckOptions = false; } m_lastFatFingersResult.reset(); // Reset the fat finger result as its no longer valid when a user's finger is not on the screen. break; } case Platform::TouchPoint::TouchMoved: { m_webPage->m_inputHandler->clearDidSpellCheckState(); PlatformMouseEvent mouseEvent(point.documentViewportPosition(), m_lastScreenPoint, PlatformEvent::MouseMoved, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen); m_lastScreenPoint = point.screenPosition(); m_webPage->handleMouseEvent(mouseEvent); break; } default: break; } }
170,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_hrtimer_stop(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); return 0; } Commit Message: ALSA: hrtimer: Fix stall by hrtimer_cancel() hrtimer_cancel() waits for the completion from the callback, thus it must not be called inside the callback itself. This was already a problem in the past with ALSA hrtimer driver, and the early commit [fcfdebe70759: ALSA: hrtimer - Fix lock-up] tried to address it. However, the previous fix is still insufficient: it may still cause a lockup when the ALSA timer instance reprograms itself in its callback. Then it invokes the start function even in snd_timer_interrupt() that is called in hrtimer callback itself, results in a CPU stall. This is no hypothetical problem but actually triggered by syzkaller fuzzer. This patch tries to fix the issue again. Now we call hrtimer_try_to_cancel() at both start and stop functions so that it won't fall into a deadlock, yet giving some chance to cancel the queue if the functions have been called outside the callback. The proper hrtimer_cancel() is called in anyway at closing, so this should be enough. Reported-and-tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-20
static int snd_hrtimer_stop(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); hrtimer_try_to_cancel(&stime->hrt); return 0; }
167,399
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void CopyTransportDIBHandleForMessage( const TransportDIB::Handle& handle_in, TransportDIB::Handle* handle_out) { #if defined(OS_MACOSX) if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) { PLOG(ERROR) << "dup()"; return; } handle_out->auto_close = true; #else *handle_out = handle_in; #endif } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
static void CopyTransportDIBHandleForMessage( const TransportDIB::Handle& handle_in, TransportDIB::Handle* handle_out, base::ProcessId peer_pid) { #if defined(OS_MACOSX) if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) { PLOG(ERROR) << "dup()"; return; } handle_out->auto_close = true; #elif defined(OS_WIN) // On Windows we need to duplicate the handle for the plugin process. *handle_out = NULL; sandbox::BrokerDuplicateHandle(handle_in, peer_pid, handle_out, FILE_MAP_READ | FILE_MAP_WRITE, 0); CHECK(*handle_out != NULL); #else *handle_out = handle_in; #endif }
170,955
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ ) { int rc = 0; gnutls_session *session = gnutls_malloc(sizeof(gnutls_session)); gnutls_init(session, type); # ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT /* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */ gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL); /* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */ # else gnutls_set_default_priority(*session); gnutls_kx_set_priority(*session, tls_kx_order); # endif gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock)); switch (type) { case GNUTLS_SERVER: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_s); break; case GNUTLS_CLIENT: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_c); break; } do { rc = gnutls_handshake(*session); } while (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN); if (rc < 0) { crm_err("Handshake failed: %s", gnutls_strerror(rc)); gnutls_deinit(*session); gnutls_free(session); return NULL; } return session; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ ) void * crm_create_anon_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */, void *credentials) { gnutls_session *session = gnutls_malloc(sizeof(gnutls_session)); gnutls_init(session, type); # ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT /* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */ gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL); /* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */ # else gnutls_set_default_priority(*session); gnutls_kx_set_priority(*session, anon_tls_kx_order); # endif gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock)); switch (type) { case GNUTLS_SERVER: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, (gnutls_anon_server_credentials_t) credentials); break; case GNUTLS_CLIENT: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, (gnutls_anon_client_credentials_t) credentials); break; } return session; }
166,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static BT_HDR *create_pbuf(UINT16 len, UINT8 *data) { BT_HDR* p_buf = GKI_getbuf((UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR))); if (p_buf) { UINT8* pbuf_data; p_buf->len = len; p_buf->offset = BTA_HH_MIN_OFFSET; pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset; memcpy(pbuf_data, data, len); } return p_buf; } Commit Message: DO NOT MERGE btif: check overflow on create_pbuf size Bug: 27930580 Change-Id: Ieb1f23f9a8a937b21f7c5eca92da3b0b821400e6 CWE ID: CWE-119
static BT_HDR *create_pbuf(UINT16 len, UINT8 *data) { UINT16 buflen = (UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR)); if (buflen < len) { android_errorWriteWithInfoLog(0x534e4554, "28672558", -1, NULL, 0); return NULL; } BT_HDR* p_buf = GKI_getbuf(buflen); if (p_buf) { UINT8* pbuf_data; p_buf->len = len; p_buf->offset = BTA_HH_MIN_OFFSET; pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset; memcpy(pbuf_data, data, len); } return p_buf; }
173,757
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int uas_switch_interface(struct usb_device *udev, struct usb_interface *intf) { int alt; alt = uas_find_uas_alt_setting(intf); if (alt < 0) return alt; return usb_set_interface(udev, intf->altsetting[0].desc.bInterfaceNumber, alt); } Commit Message: USB: uas: fix bug in handling of alternate settings The uas driver has a subtle bug in the way it handles alternate settings. The uas_find_uas_alt_setting() routine returns an altsetting value (the bAlternateSetting number in the descriptor), but uas_use_uas_driver() then treats that value as an index to the intf->altsetting array, which it isn't. Normally this doesn't cause any problems because the various alternate settings have bAlternateSetting values 0, 1, 2, ..., so the value is equal to the index in the array. But this is not guaranteed, and Andrey Konovalov used the syzkaller fuzzer with KASAN to get a slab-out-of-bounds error by violating this assumption. This patch fixes the bug by making uas_find_uas_alt_setting() return a pointer to the altsetting entry rather than either the value or the index. Pointers are less subject to misinterpretation. Signed-off-by: Alan Stern <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> CC: Oliver Neukum <[email protected]> CC: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-125
static int uas_switch_interface(struct usb_device *udev, struct usb_interface *intf) { struct usb_host_interface *alt; alt = uas_find_uas_alt_setting(intf); if (!alt) return -ENODEV; return usb_set_interface(udev, alt->desc.bInterfaceNumber, alt->desc.bAlternateSetting); }
167,680
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GURL DevToolsWindow::GetDevToolsURL(Profile* profile, const GURL& base_url, bool shared_worker_frontend, bool v8_only_frontend, const std::string& remote_frontend, bool can_dock, const std::string& panel) { if (base_url.SchemeIs("data")) return base_url; std::string frontend_url( !remote_frontend.empty() ? remote_frontend : base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec()); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&")); if (shared_worker_frontend) url_string += "&isSharedWorker=true"; if (v8_only_frontend) url_string += "&v8only=true"; if (remote_frontend.size()) { url_string += "&remoteFrontend=true"; } else { url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec(); } if (can_dock) url_string += "&can_dock=true"; if (panel.size()) url_string += "&panel=" + panel; return DevToolsUI::SanitizeFrontendURL(GURL(url_string)); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
GURL DevToolsWindow::GetDevToolsURL(Profile* profile, const GURL& base_url, bool shared_worker_frontend, bool v8_only_frontend, const std::string& remote_frontend, bool can_dock, const std::string& panel) { if (base_url.SchemeIs("data")) return base_url; std::string frontend_url( !remote_frontend.empty() ? remote_frontend : base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec()); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&")); if (shared_worker_frontend) url_string += "&isSharedWorker=true"; if (v8_only_frontend) url_string += "&v8only=true"; if (remote_frontend.size()) { url_string += "&remoteFrontend=true"; } else { url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec(); } if (can_dock) url_string += "&can_dock=true"; if (panel.size()) url_string += "&panel=" + panel; return DevToolsUIBindings::SanitizeFrontendURL(GURL(url_string)); }
172,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) { DCHECK(!defer_page_unload_); defer_page_unload_ = true; bool rv = false; switch (event.GetType()) { case PP_INPUTEVENT_TYPE_MOUSEDOWN: rv = OnMouseDown(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEUP: rv = OnMouseUp(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEMOVE: rv = OnMouseMove(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYDOWN: rv = OnKeyDown(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYUP: rv = OnKeyUp(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_CHAR: rv = OnChar(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_TOUCHSTART: { KillTouchTimer(next_touch_timer_id_); pp::TouchInputEvent touch_event(event); if (touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES) == 1) ScheduleTouchTimer(touch_event); break; } case PP_INPUTEVENT_TYPE_TOUCHEND: KillTouchTimer(next_touch_timer_id_); break; case PP_INPUTEVENT_TYPE_TOUCHMOVE: KillTouchTimer(next_touch_timer_id_); default: break; } DCHECK(defer_page_unload_); defer_page_unload_ = false; for (int page_index : deferred_page_unloads_) pages_[page_index]->Unload(); deferred_page_unloads_.clear(); return rv; } Commit Message: [pdf] Use a temporary list when unloading pages When traversing the |deferred_page_unloads_| list and handling the unloads it's possible for new pages to get added to the list which will invalidate the iterator. This CL swaps the list with an empty list and does the iteration on the list copy. New items that are unloaded while handling the defers will be unloaded at a later point. Bug: 780450 Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac Reviewed-on: https://chromium-review.googlesource.com/758916 Commit-Queue: dsinclair <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#515056} CWE ID: CWE-416
bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) { DCHECK(!defer_page_unload_); defer_page_unload_ = true; bool rv = false; switch (event.GetType()) { case PP_INPUTEVENT_TYPE_MOUSEDOWN: rv = OnMouseDown(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEUP: rv = OnMouseUp(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEMOVE: rv = OnMouseMove(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYDOWN: rv = OnKeyDown(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYUP: rv = OnKeyUp(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_CHAR: rv = OnChar(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_TOUCHSTART: { KillTouchTimer(next_touch_timer_id_); pp::TouchInputEvent touch_event(event); if (touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES) == 1) ScheduleTouchTimer(touch_event); break; } case PP_INPUTEVENT_TYPE_TOUCHEND: KillTouchTimer(next_touch_timer_id_); break; case PP_INPUTEVENT_TYPE_TOUCHMOVE: KillTouchTimer(next_touch_timer_id_); default: break; } DCHECK(defer_page_unload_); defer_page_unload_ = false; // Store the pages to unload away because the act of unloading pages can cause // there to be more pages to unload. We leave those extra pages to be unloaded // on the next go around. std::vector<int> pages_to_unload; std::swap(pages_to_unload, deferred_page_unloads_); for (int page_index : pages_to_unload) pages_[page_index]->Unload(); return rv; }
172,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc) { struct ib_cqe *cqe = wc->wr_cqe; struct svc_rdma_op_ctxt *ctxt; svc_rdma_send_wc_common_put(cq, wc, "write"); ctxt = container_of(cqe, struct svc_rdma_op_ctxt, cqe); svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 0); } 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_wc_write(struct ib_cq *cq, struct ib_wc *wc)
168,184
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentModuleScriptFetcher::NotifyFinished(Resource* resource) { ClearResource(); ScriptResource* script_resource = ToScriptResource(resource); HeapVector<Member<ConsoleMessage>> error_messages; if (!WasModuleLoadSuccessful(script_resource, &error_messages)) { Finalize(WTF::nullopt, error_messages); return; } ModuleScriptCreationParams params( script_resource->GetResponse().Url(), script_resource->SourceText(), script_resource->GetResourceRequest().GetFetchCredentialsMode(), script_resource->CalculateAccessControlStatus()); Finalize(params, error_messages); } Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin Partial revert of https://chromium-review.googlesource.com/535694. Bug: 799477 Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3 Reviewed-on: https://chromium-review.googlesource.com/898427 Commit-Queue: Hiroshige Hayashizaki <[email protected]> Reviewed-by: Kouhei Ueno <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Takeshi Yoshino <[email protected]> Cr-Commit-Position: refs/heads/master@{#535176} CWE ID: CWE-200
void DocumentModuleScriptFetcher::NotifyFinished(Resource* resource) { ClearResource(); ScriptResource* script_resource = ToScriptResource(resource); HeapVector<Member<ConsoleMessage>> error_messages; if (!WasModuleLoadSuccessful(script_resource, &error_messages)) { Finalize(WTF::nullopt, error_messages); return; } ModuleScriptCreationParams params( script_resource->GetResponse().Url(), script_resource->SourceText(), script_resource->GetResourceRequest().GetFetchCredentialsMode(), script_resource->CalculateAccessControlStatus( fetcher_->Context().GetSecurityOrigin())); Finalize(params, error_messages); }
172,887
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Edition::ParseAtom( IMkvReader* pReader, long long pos, long long size) { if (!ExpandAtomsArray()) return -1; Atom& a = m_atoms[m_atoms_count++]; a.Init(); return a.Parse(pReader, pos, 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
long Chapters::Edition::ParseAtom( SegmentInfo::~SegmentInfo() { delete[] m_pMuxingAppAsUTF8; m_pMuxingAppAsUTF8 = NULL; delete[] m_pWritingAppAsUTF8; m_pWritingAppAsUTF8 = NULL; delete[] m_pTitleAsUTF8; m_pTitleAsUTF8 = NULL; }
174,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int lsm_set_label_at(int procfd, int on_exec, char* lsm_label) { int labelfd = -1; int ret = 0; const char* name; char* command = NULL; name = lsm_name(); if (strcmp(name, "nop") == 0) goto out; if (strcmp(name, "none") == 0) goto out; /* We don't support on-exec with AppArmor */ if (strcmp(name, "AppArmor") == 0) on_exec = 0; if (on_exec) { labelfd = openat(procfd, "self/attr/exec", O_RDWR); } else { labelfd = openat(procfd, "self/attr/current", O_RDWR); } if (labelfd < 0) { SYSERROR("Unable to open LSM label"); ret = -1; goto out; } if (strcmp(name, "AppArmor") == 0) { int size; command = malloc(strlen(lsm_label) + strlen("changeprofile ") + 1); if (!command) { SYSERROR("Failed to write apparmor profile"); ret = -1; goto out; } size = sprintf(command, "changeprofile %s", lsm_label); if (size < 0) { SYSERROR("Failed to write apparmor profile"); ret = -1; goto out; } if (write(labelfd, command, size + 1) < 0) { SYSERROR("Unable to set LSM label"); ret = -1; goto out; } } else if (strcmp(name, "SELinux") == 0) { if (write(labelfd, lsm_label, strlen(lsm_label) + 1) < 0) { SYSERROR("Unable to set LSM label"); ret = -1; goto out; } } else { ERROR("Unable to restore label for unknown LSM: %s", name); ret = -1; goto out; } out: free(command); if (labelfd != -1) close(labelfd); return ret; } Commit Message: attach: do not send procfd to attached process So far, we opened a file descriptor refering to proc on the host inside the host namespace and handed that fd to the attached process in attach_child_main(). This was done to ensure that LSM labels were correctly setup. However, by exploiting a potential kernel bug, ptrace could be used to prevent the file descriptor from being closed which in turn could be used by an unprivileged container to gain access to the host namespace. Aside from this needing an upstream kernel fix, we should make sure that we don't pass the fd for proc itself to the attached process. However, we cannot completely prevent this, as the attached process needs to be able to change its apparmor profile by writing to /proc/self/attr/exec or /proc/self/attr/current. To minimize the attack surface, we only send the fd for /proc/self/attr/exec or /proc/self/attr/current to the attached process. To do this we introduce a little more IPC between the child and parent: * IPC mechanism: (X is receiver) * initial process intermediate attached * X <--- send pid of * attached proc, * then exit * send 0 ------------------------------------> X * [do initialization] * X <------------------------------------ send 1 * [add to cgroup, ...] * send 2 ------------------------------------> X * [set LXC_ATTACH_NO_NEW_PRIVS] * X <------------------------------------ send 3 * [open LSM label fd] * send 4 ------------------------------------> X * [set LSM label] * close socket close socket * run program The attached child tells the parent when it is ready to have its LSM labels set up. The parent then opens an approriate fd for the child PID to /proc/<pid>/attr/exec or /proc/<pid>/attr/current and sends it via SCM_RIGHTS to the child. The child can then set its LSM laben. Both sides then close the socket fds and the child execs the requested process. Signed-off-by: Christian Brauner <[email protected]> CWE ID: CWE-264
int lsm_set_label_at(int procfd, int on_exec, char* lsm_label) { static int lsm_openat(int procfd, pid_t pid, int on_exec) { int ret = -1; int labelfd = -1; const char* name; #define __LSMATTRLEN /* /proc */ (5 + /* /pid-to-str */ 21 + /* /current */ 7 + /* \0 */ 1) char path[__LSMATTRLEN]; name = lsm_name(); if (strcmp(name, "nop") == 0) return 0; if (strcmp(name, "none") == 0) return 0; /* We don't support on-exec with AppArmor */ if (strcmp(name, "AppArmor") == 0) on_exec = 0; if (on_exec) { ret = snprintf(path, __LSMATTRLEN, "%d/attr/exec", pid); if (ret < 0 || ret >= __LSMATTRLEN) return -1; labelfd = openat(procfd, path, O_RDWR); } else { ret = snprintf(path, __LSMATTRLEN, "%d/attr/current", pid); if (ret < 0 || ret >= __LSMATTRLEN) return -1; labelfd = openat(procfd, path, O_RDWR); } if (labelfd < 0) { SYSERROR("Unable to open LSM label"); return -1; } return labelfd; } static int lsm_set_label_at(int lsm_labelfd, int on_exec, char *lsm_label) { int fret = -1; const char* name; char *command = NULL; name = lsm_name(); if (strcmp(name, "nop") == 0) return 0; if (strcmp(name, "none") == 0) return 0; /* We don't support on-exec with AppArmor */ if (strcmp(name, "AppArmor") == 0) on_exec = 0; if (strcmp(name, "AppArmor") == 0) { int size; command = malloc(strlen(lsm_label) + strlen("changeprofile ") + 1); if (!command) { SYSERROR("Failed to write apparmor profile"); goto out; } size = sprintf(command, "changeprofile %s", lsm_label); if (size < 0) { SYSERROR("Failed to write apparmor profile"); goto out; } if (write(lsm_labelfd, command, size + 1) < 0) { SYSERROR("Unable to set LSM label: %s.", command); goto out; } INFO("Set LSM label to: %s.", command); } else if (strcmp(name, "SELinux") == 0) { if (write(lsm_labelfd, lsm_label, strlen(lsm_label) + 1) < 0) { SYSERROR("Unable to set LSM label"); goto out; } INFO("Set LSM label to: %s.", lsm_label); } else { ERROR("Unable to restore label for unknown LSM: %s", name); goto out; } fret = 0; out: free(command); if (lsm_labelfd != -1) close(lsm_labelfd); return fret; }
168,771
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void show_object_with_name(FILE *out, struct object *obj, struct strbuf *path, const char *component) { char *name = path_name(path, component); char *p; fprintf(out, "%s ", oid_to_hex(&obj->oid)); for (p = name; *p && *p != '\n'; p++) fputc(*p, out); fputc('\n', out); free(name); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
void show_object_with_name(FILE *out, struct object *obj, const char *p; fprintf(out, "%s ", oid_to_hex(&obj->oid)); for (p = name; *p && *p != '\n'; p++) fputc(*p, out); fputc('\n', out); }
167,427
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int read_request_line(request_rec *r, apr_bucket_brigade *bb) { const char *ll; const char *uri; const char *pro; unsigned int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */ char http[5]; apr_size_t len; int num_blank_lines = 0; int max_blank_lines = r->server->limit_req_fields; core_server_config *conf = ap_get_core_module_config(r->server->module_config); int strict = conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT; int enforce_strict = !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY); if (max_blank_lines <= 0) { max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS; } /* Read past empty lines until we get a real request line, * a read error, the connection closes (EOF), or we timeout. * * We skip empty lines because browsers have to tack a CRLF on to the end * of POSTs to support old CERN webservers. But note that we may not * have flushed any previous response completely to the client yet. * We delay the flush as long as possible so that we can improve * performance for clients that are pipelining requests. If a request * is pipelined then we won't block during the (implicit) read() below. * If the requests aren't pipelined, then the client is still waiting * for the final buffer flush from us, and we will block in the implicit * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will * have to block during a read. */ do { apr_status_t rv; /* ensure ap_rgetline allocates memory each time thru the loop * if there are empty lines */ r->the_request = NULL; rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2), &len, r, 0, bb); if (rv != APR_SUCCESS) { r->request_time = apr_time_now(); /* ap_rgetline returns APR_ENOSPC if it fills up the * buffer before finding the end-of-line. This is only going to * happen if it exceeds the configured limit for a request-line. */ if (APR_STATUS_IS_ENOSPC(rv)) { r->status = HTTP_REQUEST_URI_TOO_LARGE; r->proto_num = HTTP_VERSION(1,0); r->protocol = apr_pstrdup(r->pool, "HTTP/1.0"); } else if (APR_STATUS_IS_TIMEUP(rv)) { r->status = HTTP_REQUEST_TIME_OUT; } else if (APR_STATUS_IS_EINVAL(rv)) { r->status = HTTP_BAD_REQUEST; } return 0; } } while ((len <= 0) && (++num_blank_lines < max_blank_lines)); if (APLOGrtrace5(r)) { ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r, "Request received from client: %s", ap_escape_logitem(r->pool, r->the_request)); } r->request_time = apr_time_now(); ll = r->the_request; r->method = ap_getword_white(r->pool, &ll); uri = ap_getword_white(r->pool, &ll); /* Provide quick information about the request method as soon as known */ r->method_number = ap_method_number_of(r->method); if (r->method_number == M_GET && r->method[0] == 'H') { r->header_only = 1; } ap_parse_uri(r, uri); if (ll[0]) { r->assbackwards = 0; pro = ll; len = strlen(ll); } else { r->assbackwards = 1; pro = "HTTP/0.9"; len = 8; if (conf->http09_enable == AP_HTTP09_DISABLE) { r->status = HTTP_VERSION_NOT_SUPPORTED; r->protocol = apr_pstrmemdup(r->pool, pro, len); /* If we deny 0.9, send error message with 1.x */ r->assbackwards = 0; r->proto_num = HTTP_VERSION(0, 9); r->connection->keepalive = AP_CONN_CLOSE; ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401) "HTTP/0.9 denied by server configuration"); return 0; } } r->protocol = apr_pstrmemdup(r->pool, pro, len); /* Avoid sscanf in the common case */ if (len == 8 && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P' && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.' && apr_isdigit(pro[7])) { r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0'); } else { if (strict) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418) "Invalid protocol '%s'", r->protocol); if (enforce_strict) { r->status = HTTP_BAD_REQUEST; return 0; } } if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor) && (strcasecmp("http", http) == 0) && (minor < HTTP_VERSION(1, 0)) ) { /* don't allow HTTP/0.1000 */ r->proto_num = HTTP_VERSION(major, minor); } else { r->proto_num = HTTP_VERSION(1, 0); } } if (strict) { int err = 0; if (ap_has_cntrl(r->the_request)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02420) "Request line must not contain control characters"); err = HTTP_BAD_REQUEST; } if (r->parsed_uri.fragment) { /* RFC3986 3.5: no fragment */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421) "URI must not contain a fragment"); err = HTTP_BAD_REQUEST; } else if (r->parsed_uri.user || r->parsed_uri.password) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422) "URI must not contain a username/password"); err = HTTP_BAD_REQUEST; } else if (r->method_number == M_INVALID) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423) "Invalid HTTP method string: %s", r->method); err = HTTP_NOT_IMPLEMENTED; } else if (r->assbackwards == 0 && r->proto_num < HTTP_VERSION(1, 0)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02424) "HTTP/0.x does not take a protocol"); err = HTTP_BAD_REQUEST; } if (err && enforce_strict) { r->status = err; return 0; } } return 1; } Commit Message: *) SECURITY: CVE-2015-0253 (cve.mitre.org) core: Fix a crash introduced in with ErrorDocument 400 pointing to a local URL-path with the INCLUDES filter active, introduced in 2.4.11. PR 57531. [Yann Ylavic] Submitted By: ylavic Committed By: covener git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1664205 13f79535-47bb-0310-9956-ffa450edef68 CWE ID:
static int read_request_line(request_rec *r, apr_bucket_brigade *bb) { const char *ll; const char *uri; const char *pro; unsigned int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */ char http[5]; apr_size_t len; int num_blank_lines = 0; int max_blank_lines = r->server->limit_req_fields; core_server_config *conf = ap_get_core_module_config(r->server->module_config); int strict = conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT; int enforce_strict = !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY); if (max_blank_lines <= 0) { max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS; } /* Read past empty lines until we get a real request line, * a read error, the connection closes (EOF), or we timeout. * * We skip empty lines because browsers have to tack a CRLF on to the end * of POSTs to support old CERN webservers. But note that we may not * have flushed any previous response completely to the client yet. * We delay the flush as long as possible so that we can improve * performance for clients that are pipelining requests. If a request * is pipelined then we won't block during the (implicit) read() below. * If the requests aren't pipelined, then the client is still waiting * for the final buffer flush from us, and we will block in the implicit * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will * have to block during a read. */ do { apr_status_t rv; /* ensure ap_rgetline allocates memory each time thru the loop * if there are empty lines */ r->the_request = NULL; rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2), &len, r, 0, bb); if (rv != APR_SUCCESS) { r->request_time = apr_time_now(); /* ap_rgetline returns APR_ENOSPC if it fills up the * buffer before finding the end-of-line. This is only going to * happen if it exceeds the configured limit for a request-line. */ if (APR_STATUS_IS_ENOSPC(rv)) { r->status = HTTP_REQUEST_URI_TOO_LARGE; } else if (APR_STATUS_IS_TIMEUP(rv)) { r->status = HTTP_REQUEST_TIME_OUT; } else if (APR_STATUS_IS_EINVAL(rv)) { r->status = HTTP_BAD_REQUEST; } r->proto_num = HTTP_VERSION(1,0); r->protocol = apr_pstrdup(r->pool, "HTTP/1.0"); return 0; } } while ((len <= 0) && (++num_blank_lines < max_blank_lines)); if (APLOGrtrace5(r)) { ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r, "Request received from client: %s", ap_escape_logitem(r->pool, r->the_request)); } r->request_time = apr_time_now(); ll = r->the_request; r->method = ap_getword_white(r->pool, &ll); uri = ap_getword_white(r->pool, &ll); /* Provide quick information about the request method as soon as known */ r->method_number = ap_method_number_of(r->method); if (r->method_number == M_GET && r->method[0] == 'H') { r->header_only = 1; } ap_parse_uri(r, uri); if (ll[0]) { r->assbackwards = 0; pro = ll; len = strlen(ll); } else { r->assbackwards = 1; pro = "HTTP/0.9"; len = 8; if (conf->http09_enable == AP_HTTP09_DISABLE) { r->status = HTTP_VERSION_NOT_SUPPORTED; r->protocol = apr_pstrmemdup(r->pool, pro, len); /* If we deny 0.9, send error message with 1.x */ r->assbackwards = 0; r->proto_num = HTTP_VERSION(0, 9); r->connection->keepalive = AP_CONN_CLOSE; ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401) "HTTP/0.9 denied by server configuration"); return 0; } } r->protocol = apr_pstrmemdup(r->pool, pro, len); /* Avoid sscanf in the common case */ if (len == 8 && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P' && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.' && apr_isdigit(pro[7])) { r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0'); } else { if (strict) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418) "Invalid protocol '%s'", r->protocol); if (enforce_strict) { r->status = HTTP_BAD_REQUEST; return 0; } } if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor) && (strcasecmp("http", http) == 0) && (minor < HTTP_VERSION(1, 0)) ) { /* don't allow HTTP/0.1000 */ r->proto_num = HTTP_VERSION(major, minor); } else { r->proto_num = HTTP_VERSION(1, 0); } } if (strict) { int err = 0; if (ap_has_cntrl(r->the_request)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02420) "Request line must not contain control characters"); err = HTTP_BAD_REQUEST; } if (r->parsed_uri.fragment) { /* RFC3986 3.5: no fragment */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421) "URI must not contain a fragment"); err = HTTP_BAD_REQUEST; } else if (r->parsed_uri.user || r->parsed_uri.password) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422) "URI must not contain a username/password"); err = HTTP_BAD_REQUEST; } else if (r->method_number == M_INVALID) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423) "Invalid HTTP method string: %s", r->method); err = HTTP_NOT_IMPLEMENTED; } else if (r->assbackwards == 0 && r->proto_num < HTTP_VERSION(1, 0)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02424) "HTTP/0.x does not take a protocol"); err = HTTP_BAD_REQUEST; } if (err && enforce_strict) { r->status = err; return 0; } } return 1; }
166,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ int nBytes = sizeof(char *)*(2+pTable->nModuleArg); char **azModuleArg; azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); if( azModuleArg==0 ){ sqlite3DbFree(db, zArg); }else{ int i = pTable->nModuleArg++; azModuleArg[i] = zArg; azModuleArg[i+1] = 0; pTable->azModuleArg = azModuleArg; } } Commit Message: sqlite: backport bugfixes for dbfuzz2 Bug: 952406 Change-Id: Icbec429742048d6674828726c96d8e265c41b595 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1568152 Reviewed-by: Chris Mumford <[email protected]> Commit-Queue: Darwin Huang <[email protected]> Cr-Commit-Position: refs/heads/master@{#651030} CWE ID: CWE-190
static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){ sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg); char **azModuleArg; sqlite3 *db = pParse->db; if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName); } azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); if( azModuleArg==0 ){ sqlite3DbFree(db, zArg); }else{ int i = pTable->nModuleArg++; azModuleArg[i] = zArg; azModuleArg[i+1] = 0; pTable->azModuleArg = azModuleArg; } }
173,014
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n, CH_UNIX, &c_size); src += c_size; c = toupper_m(c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; } Commit Message: CWE ID: CWE-200
_PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n && *src) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n, CH_UNIX, &c_size); src += c_size; n -= c_size; c = toupper_m(c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; }
164,669
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: UserCloudPolicyManagerFactoryChromeOS::CreateManagerForProfile( Profile* profile, bool force_immediate_load, scoped_refptr<base::SequencedTaskRunner> background_task_runner) { const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (chromeos::ProfileHelper::IsSigninProfile(profile)) return scoped_ptr<UserCloudPolicyManagerChromeOS>(); chromeos::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile); CHECK(user); const std::string& username = user->email(); if (user->GetType() != user_manager::USER_TYPE_REGULAR || BrowserPolicyConnector::IsNonEnterpriseUser(username)) { return scoped_ptr<UserCloudPolicyManagerChromeOS>(); } policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); UserAffiliation affiliation = connector->GetUserAffiliation(username); const bool is_managed_user = affiliation == USER_AFFILIATION_MANAGED; const bool is_browser_restart = command_line->HasSwitch(chromeos::switches::kLoginUser); const bool wait_for_initial_policy = is_managed_user && !is_browser_restart; DeviceManagementService* device_management_service = connector->device_management_service(); if (wait_for_initial_policy) device_management_service->ScheduleInitialization(0); base::FilePath profile_dir = profile->GetPath(); const base::FilePath legacy_dir = profile_dir.Append(kDeviceManagementDir); const base::FilePath policy_cache_file = legacy_dir.Append(kPolicy); const base::FilePath token_cache_file = legacy_dir.Append(kToken); const base::FilePath component_policy_cache_dir = profile_dir.Append(kPolicy).Append(kComponentsDir); const base::FilePath external_data_dir = profile_dir.Append(kPolicy).Append(kPolicyExternalDataDir); base::FilePath policy_key_dir; CHECK(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &policy_key_dir)); scoped_ptr<UserCloudPolicyStoreChromeOS> store( new UserCloudPolicyStoreChromeOS( chromeos::DBusThreadManager::Get()->GetCryptohomeClient(), chromeos::DBusThreadManager::Get()->GetSessionManagerClient(), background_task_runner, username, policy_key_dir, token_cache_file, policy_cache_file)); scoped_refptr<base::SequencedTaskRunner> backend_task_runner = content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( content::BrowserThread::GetBlockingPool()->GetSequenceToken()); scoped_refptr<base::SequencedTaskRunner> io_task_runner = content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::IO); scoped_ptr<CloudExternalDataManager> external_data_manager( new UserCloudExternalDataManager(base::Bind(&GetChromePolicyDetails), backend_task_runner, io_task_runner, external_data_dir, store.get())); if (force_immediate_load) store->LoadImmediately(); scoped_refptr<base::SequencedTaskRunner> file_task_runner = content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::FILE); scoped_ptr<UserCloudPolicyManagerChromeOS> manager( new UserCloudPolicyManagerChromeOS( store.PassAs<CloudPolicyStore>(), external_data_manager.Pass(), component_policy_cache_dir, wait_for_initial_policy, base::TimeDelta::FromSeconds(kInitialPolicyFetchTimeoutSeconds), base::MessageLoopProxy::current(), file_task_runner, io_task_runner)); bool wildcard_match = false; if (connector->IsEnterpriseManaged() && chromeos::LoginUtils::IsWhitelisted(username, &wildcard_match) && wildcard_match && !connector->IsNonEnterpriseUser(username)) { manager->EnableWildcardLoginCheck(username); } manager->Init( SchemaRegistryServiceFactory::GetForContext(profile)->registry()); manager->Connect(g_browser_process->local_state(), device_management_service, g_browser_process->system_request_context(), affiliation); DCHECK(managers_.find(profile) == managers_.end()); managers_[profile] = manager.get(); return manager.Pass(); } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
UserCloudPolicyManagerFactoryChromeOS::CreateManagerForProfile( Profile* profile, bool force_immediate_load, scoped_refptr<base::SequencedTaskRunner> background_task_runner) { const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (chromeos::ProfileHelper::IsSigninProfile(profile)) return scoped_ptr<UserCloudPolicyManagerChromeOS>(); chromeos::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile); CHECK(user); // Non-managed domains will be skipped by the below check const std::string& username = user->email(); if (user->GetType() != user_manager::USER_TYPE_REGULAR || BrowserPolicyConnector::IsNonEnterpriseUser(username)) { return scoped_ptr<UserCloudPolicyManagerChromeOS>(); } policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); UserAffiliation affiliation = connector->GetUserAffiliation(username); const bool is_affiliated_user = affiliation == USER_AFFILIATION_MANAGED; const bool is_browser_restart = command_line->HasSwitch(chromeos::switches::kLoginUser); const bool wait_for_initial_policy = !is_browser_restart && (chromeos::UserManager::Get()->IsCurrentUserNew() || is_affiliated_user); const base::TimeDelta initial_policy_fetch_timeout = chromeos::UserManager::Get()->IsCurrentUserNew() ? base::TimeDelta::Max() : base::TimeDelta::FromSeconds(kInitialPolicyFetchTimeoutSeconds); DeviceManagementService* device_management_service = connector->device_management_service(); if (wait_for_initial_policy) device_management_service->ScheduleInitialization(0); base::FilePath profile_dir = profile->GetPath(); const base::FilePath legacy_dir = profile_dir.Append(kDeviceManagementDir); const base::FilePath policy_cache_file = legacy_dir.Append(kPolicy); const base::FilePath token_cache_file = legacy_dir.Append(kToken); const base::FilePath component_policy_cache_dir = profile_dir.Append(kPolicy).Append(kComponentsDir); const base::FilePath external_data_dir = profile_dir.Append(kPolicy).Append(kPolicyExternalDataDir); base::FilePath policy_key_dir; CHECK(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &policy_key_dir)); scoped_ptr<UserCloudPolicyStoreChromeOS> store( new UserCloudPolicyStoreChromeOS( chromeos::DBusThreadManager::Get()->GetCryptohomeClient(), chromeos::DBusThreadManager::Get()->GetSessionManagerClient(), background_task_runner, username, policy_key_dir, token_cache_file, policy_cache_file)); scoped_refptr<base::SequencedTaskRunner> backend_task_runner = content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( content::BrowserThread::GetBlockingPool()->GetSequenceToken()); scoped_refptr<base::SequencedTaskRunner> io_task_runner = content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::IO); scoped_ptr<CloudExternalDataManager> external_data_manager( new UserCloudExternalDataManager(base::Bind(&GetChromePolicyDetails), backend_task_runner, io_task_runner, external_data_dir, store.get())); if (force_immediate_load) store->LoadImmediately(); scoped_refptr<base::SequencedTaskRunner> file_task_runner = content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::FILE); scoped_ptr<UserCloudPolicyManagerChromeOS> manager( new UserCloudPolicyManagerChromeOS( store.PassAs<CloudPolicyStore>(), external_data_manager.Pass(), component_policy_cache_dir, wait_for_initial_policy, initial_policy_fetch_timeout, base::MessageLoopProxy::current(), file_task_runner, io_task_runner)); bool wildcard_match = false; if (connector->IsEnterpriseManaged() && chromeos::LoginUtils::IsWhitelisted(username, &wildcard_match) && wildcard_match && !connector->IsNonEnterpriseUser(username)) { manager->EnableWildcardLoginCheck(username); } manager->Init( SchemaRegistryServiceFactory::GetForContext(profile)->registry()); manager->Connect(g_browser_process->local_state(), device_management_service, g_browser_process->system_request_context(), affiliation); DCHECK(managers_.find(profile) == managers_.end()); managers_[profile] = manager.get(); return manager.Pass(); }
171,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PluginChannel::PluginChannel() : renderer_handle_(0), renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()) { set_send_unblocking_only_during_unblock_dispatch(); ChildProcess::current()->AddRefProcess(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
PluginChannel::PluginChannel() : renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()) { set_send_unblocking_only_during_unblock_dispatch(); ChildProcess::current()->AddRefProcess(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); }
170,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gplotGenCommandFile(GPLOT *gplot) { char buf[L_BUF_SIZE]; char *cmdstr, *plottitle, *dataname; l_int32 i, plotstyle, nplots; FILE *fp; PROCNAME("gplotGenCommandFile"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); /* Remove any previous command data */ sarrayClear(gplot->cmddata); /* Generate command data instructions */ if (gplot->title) { /* set title */ snprintf(buf, L_BUF_SIZE, "set title '%s'", gplot->title); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->xlabel) { /* set xlabel */ snprintf(buf, L_BUF_SIZE, "set xlabel '%s'", gplot->xlabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->ylabel) { /* set ylabel */ snprintf(buf, L_BUF_SIZE, "set ylabel '%s'", gplot->ylabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Set terminal type and output */ if (gplot->outformat == GPLOT_PNG) { snprintf(buf, L_BUF_SIZE, "set terminal png; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_PS) { snprintf(buf, L_BUF_SIZE, "set terminal postscript; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_EPS) { snprintf(buf, L_BUF_SIZE, "set terminal postscript eps; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_LATEX) { snprintf(buf, L_BUF_SIZE, "set terminal latex; set output '%s'", gplot->outname); } sarrayAddString(gplot->cmddata, buf, L_COPY); if (gplot->scaling == GPLOT_LOG_SCALE_X || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUF_SIZE, "set logscale x"); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->scaling == GPLOT_LOG_SCALE_Y || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUF_SIZE, "set logscale y"); sarrayAddString(gplot->cmddata, buf, L_COPY); } nplots = sarrayGetCount(gplot->datanames); for (i = 0; i < nplots; i++) { plottitle = sarrayGetString(gplot->plottitles, i, L_NOCOPY); dataname = sarrayGetString(gplot->datanames, i, L_NOCOPY); numaGetIValue(gplot->plotstyles, i, &plotstyle); if (nplots == 1) { snprintf(buf, L_BUF_SIZE, "plot '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } else { if (i == 0) snprintf(buf, L_BUF_SIZE, "plot '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else if (i < nplots - 1) snprintf(buf, L_BUF_SIZE, " '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else snprintf(buf, L_BUF_SIZE, " '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Write command data to file */ cmdstr = sarrayToString(gplot->cmddata, 1); if ((fp = fopenWriteStream(gplot->cmdname, "w")) == NULL) { LEPT_FREE(cmdstr); return ERROR_INT("cmd stream not opened", procName, 1); } fwrite(cmdstr, 1, strlen(cmdstr), fp); fclose(fp); LEPT_FREE(cmdstr); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotGenCommandFile(GPLOT *gplot) { char buf[L_BUFSIZE]; char *cmdstr, *plottitle, *dataname; l_int32 i, plotstyle, nplots; FILE *fp; PROCNAME("gplotGenCommandFile"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); /* Remove any previous command data */ sarrayClear(gplot->cmddata); /* Generate command data instructions */ if (gplot->title) { /* set title */ snprintf(buf, L_BUFSIZE, "set title '%s'", gplot->title); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->xlabel) { /* set xlabel */ snprintf(buf, L_BUFSIZE, "set xlabel '%s'", gplot->xlabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->ylabel) { /* set ylabel */ snprintf(buf, L_BUFSIZE, "set ylabel '%s'", gplot->ylabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Set terminal type and output */ if (gplot->outformat == GPLOT_PNG) { snprintf(buf, L_BUFSIZE, "set terminal png; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_PS) { snprintf(buf, L_BUFSIZE, "set terminal postscript; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_EPS) { snprintf(buf, L_BUFSIZE, "set terminal postscript eps; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_LATEX) { snprintf(buf, L_BUFSIZE, "set terminal latex; set output '%s'", gplot->outname); } sarrayAddString(gplot->cmddata, buf, L_COPY); if (gplot->scaling == GPLOT_LOG_SCALE_X || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUFSIZE, "set logscale x"); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->scaling == GPLOT_LOG_SCALE_Y || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUFSIZE, "set logscale y"); sarrayAddString(gplot->cmddata, buf, L_COPY); } nplots = sarrayGetCount(gplot->datanames); for (i = 0; i < nplots; i++) { plottitle = sarrayGetString(gplot->plottitles, i, L_NOCOPY); dataname = sarrayGetString(gplot->datanames, i, L_NOCOPY); numaGetIValue(gplot->plotstyles, i, &plotstyle); if (nplots == 1) { snprintf(buf, L_BUFSIZE, "plot '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } else { if (i == 0) snprintf(buf, L_BUFSIZE, "plot '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else if (i < nplots - 1) snprintf(buf, L_BUFSIZE, " '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else snprintf(buf, L_BUFSIZE, " '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Write command data to file */ cmdstr = sarrayToString(gplot->cmddata, 1); if ((fp = fopenWriteStream(gplot->cmdname, "w")) == NULL) { LEPT_FREE(cmdstr); return ERROR_INT("cmd stream not opened", procName, 1); } fwrite(cmdstr, 1, strlen(cmdstr), fp); fclose(fp); LEPT_FREE(cmdstr); return 0; }
169,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1; image=AcquireImage(image_info,exception); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; Rec2.RecordLength=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if (Rec.RecordLength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->resolution.x=BitmapHeader1.HorzRes/470.0; image->resolution.y=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->resolution.x=BitmapHeader2.HorzRes/470.0; image->resolution.y=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp <= 16)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp,exception) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); ReplaceImageInList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(image,BImgBuff,i,bpp,exception); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp,exception) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/85 CWE ID: CWE-119
static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1; image=AcquireImage(image_info,exception); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; Rec2.RecordLength=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if (Rec.RecordLength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->resolution.x=BitmapHeader1.HorzRes/470.0; image->resolution.y=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2)/3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); if (WPG_Palette.StartIndex > WPG_Palette.NumOfEntries) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->resolution.x=BitmapHeader2.HorzRes/470.0; image->resolution.y=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp <= 16)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp,exception) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); ReplaceImageInList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(image,BImgBuff,i,bpp,exception); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp,exception) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); }
167,674
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SegmentInfo::~SegmentInfo() { delete[] m_pMuxingAppAsUTF8; m_pMuxingAppAsUTF8 = NULL; delete[] m_pWritingAppAsUTF8; m_pWritingAppAsUTF8 = NULL; delete[] m_pTitleAsUTF8; m_pTitleAsUTF8 = NULL; } 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
SegmentInfo::~SegmentInfo()
174,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DesktopSessionWin::OnChannelConnected() { DCHECK(main_task_runner_->BelongsToCurrentThread()); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DesktopSessionWin::OnChannelConnected() { void DesktopSessionWin::OnChannelConnected(int32 peer_pid) { DCHECK(main_task_runner_->BelongsToCurrentThread()); }
171,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DefragReverseSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p3, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p1, NULL); if (reassembled == NULL) goto end; if (IPV4_GET_HLEN(reassembled) != 20) goto end; if (IPV4_GET_IPLEN(reassembled) != 39) goto end; /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragReverseSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(IPPROTO_ICMP, id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p3, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p1, NULL); if (reassembled == NULL) goto end; if (IPV4_GET_HLEN(reassembled) != 20) goto end; if (IPV4_GET_IPLEN(reassembled) != 39) goto end; /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') goto end; } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') goto end; } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; }
168,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n) { long v; int u; /* We can reliably get at most 31 bits since ISO/IEC 9899 only guarantees that a long can represent values up to 2^31-1. */ assert(n >= 0 && n < 32); /* Get the number of bits requested from the specified bit stream. */ v = 0; while (--n >= 0) { if ((u = jpc_bitstream_getbit(bitstream)) < 0) { return -1; } v = (v << 1) | u; } return v; } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). CWE ID:
long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n) { long v; int u; /* We can reliably get at most 31 bits since ISO/IEC 9899 only guarantees that a long can represent values up to 2^31-1. */ //assert(n >= 0 && n < 32); if (n < 0 || n >= 32) { return -1; } /* Get the number of bits requested from the specified bit stream. */ v = 0; while (--n >= 0) { if ((u = jpc_bitstream_getbit(bitstream)) < 0) { return -1; } v = (v << 1) | u; } return v; }
168,732
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/131 CWE ID: CWE-125
static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); }
168,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string ProcessRawBytesWithSeparators(const unsigned char* data, size_t data_length, char hex_separator, char line_separator) { static const char kHexChars[] = "0123456789ABCDEF"; std::string ret; size_t kMin = 0U; ret.reserve(std::max(kMin, data_length * 3 - 1)); for (size_t i = 0; i < data_length; ++i) { unsigned char b = data[i]; ret.push_back(kHexChars[(b >> 4) & 0xf]); ret.push_back(kHexChars[b & 0xf]); if (i + 1 < data_length) { if ((i + 1) % 16 == 0) ret.push_back(line_separator); else ret.push_back(hex_separator); } } return ret; } Commit Message: return early from ProcessRawBytesWithSeperators() when data length is 0 BUG=109717 TEST=N/A Review URL: http://codereview.chromium.org/9169028 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@117241 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
std::string ProcessRawBytesWithSeparators(const unsigned char* data, size_t data_length, char hex_separator, char line_separator) { static const char kHexChars[] = "0123456789ABCDEF"; std::string ret; size_t kMin = 0U; if (!data_length) return ""; ret.reserve(std::max(kMin, data_length * 3 - 1)); for (size_t i = 0; i < data_length; ++i) { unsigned char b = data[i]; ret.push_back(kHexChars[(b >> 4) & 0xf]); ret.push_back(kHexChars[b & 0xf]); if (i + 1 < data_length) { if ((i + 1) % 16 == 0) ret.push_back(line_separator); else ret.push_back(hex_separator); } } return ret; }
170,975