instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::CreateDelegatedFrameHostClient() { if (IsMus()) return; cc::FrameSinkId frame_sink_id = host_->AllocateFrameSinkId(is_guest_view_hack_); if (!delegated_frame_host_client_) { delegated_frame_host_client_ = base::MakeUnique<DelegatedFrameHostClientAura>(this); } delegated_frame_host_ = base::MakeUnique<DelegatedFrameHost>( frame_sink_id, delegated_frame_host_client_.get()); if (renderer_compositor_frame_sink_) { delegated_frame_host_->DidCreateNewRendererCompositorFrameSink( renderer_compositor_frame_sink_); } UpdateNeedsBeginFramesInternal(); if (host_->delegate() && host_->delegate()->GetInputEventRouter()) { host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner( GetFrameSinkId(), this); } } Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash RenderWidgetHostViewChildFrame expects its parent to have a valid FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even if DelegatedFrameHost is not used (in mus+ash). BUG=706553 [email protected] Review-Url: https://codereview.chromium.org/2847253003 Cr-Commit-Position: refs/heads/master@{#468179} CWE ID: CWE-254
void RenderWidgetHostViewAura::CreateDelegatedFrameHostClient() { if (IsMus()) return; if (!delegated_frame_host_client_) { delegated_frame_host_client_ = base::MakeUnique<DelegatedFrameHostClientAura>(this); } delegated_frame_host_ = base::MakeUnique<DelegatedFrameHost>( frame_sink_id_, delegated_frame_host_client_.get()); if (renderer_compositor_frame_sink_) { delegated_frame_host_->DidCreateNewRendererCompositorFrameSink( renderer_compositor_frame_sink_); } UpdateNeedsBeginFramesInternal(); if (host_->delegate() && host_->delegate()->GetInputEventRouter()) { host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner( GetFrameSinkId(), this); } }
172,233
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct tty_struct *tty = file_tty(file); struct tty_struct *real_tty; void __user *p = (void __user *)arg; int retval; struct tty_ldisc *ld; if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl")) return -EINVAL; real_tty = tty_pair_get_tty(tty); /* * Factor out some common prep work */ switch (cmd) { case TIOCSETD: case TIOCSBRK: case TIOCCBRK: case TCSBRK: case TCSBRKP: retval = tty_check_change(tty); if (retval) return retval; if (cmd != TIOCCBRK) { tty_wait_until_sent(tty, 0); if (signal_pending(current)) return -EINTR; } break; } /* * Now do the stuff. */ switch (cmd) { case TIOCSTI: return tiocsti(tty, p); case TIOCGWINSZ: return tiocgwinsz(real_tty, p); case TIOCSWINSZ: return tiocswinsz(real_tty, p); case TIOCCONS: return real_tty != tty ? -EINVAL : tioccons(file); case FIONBIO: return fionbio(file, p); case TIOCEXCL: set_bit(TTY_EXCLUSIVE, &tty->flags); return 0; case TIOCNXCL: clear_bit(TTY_EXCLUSIVE, &tty->flags); return 0; case TIOCGEXCL: { int excl = test_bit(TTY_EXCLUSIVE, &tty->flags); return put_user(excl, (int __user *)p); } case TIOCNOTTY: if (current->signal->tty != tty) return -ENOTTY; no_tty(); return 0; case TIOCSCTTY: return tiocsctty(real_tty, file, arg); case TIOCGPGRP: return tiocgpgrp(tty, real_tty, p); case TIOCSPGRP: return tiocspgrp(tty, real_tty, p); case TIOCGSID: return tiocgsid(tty, real_tty, p); case TIOCGETD: return put_user(tty->ldisc->ops->num, (int __user *)p); case TIOCSETD: return tiocsetd(tty, p); case TIOCVHANGUP: if (!capable(CAP_SYS_ADMIN)) return -EPERM; tty_vhangup(tty); return 0; case TIOCGDEV: { unsigned int ret = new_encode_dev(tty_devnum(real_tty)); return put_user(ret, (unsigned int __user *)p); } /* * Break handling */ case TIOCSBRK: /* Turn break on, unconditionally */ if (tty->ops->break_ctl) return tty->ops->break_ctl(tty, -1); return 0; case TIOCCBRK: /* Turn break off, unconditionally */ if (tty->ops->break_ctl) return tty->ops->break_ctl(tty, 0); return 0; case TCSBRK: /* SVID version: non-zero arg --> no break */ /* non-zero arg means wait for all output data * to be sent (performed above) but don't send break. * This is used by the tcdrain() termios function. */ if (!arg) return send_break(tty, 250); return 0; case TCSBRKP: /* support for POSIX tcsendbreak() */ return send_break(tty, arg ? arg*100 : 250); case TIOCMGET: return tty_tiocmget(tty, p); case TIOCMSET: case TIOCMBIC: case TIOCMBIS: return tty_tiocmset(tty, cmd, p); case TIOCGICOUNT: retval = tty_tiocgicount(tty, p); /* For the moment allow fall through to the old method */ if (retval != -EINVAL) return retval; break; case TCFLSH: switch (arg) { case TCIFLUSH: case TCIOFLUSH: /* flush tty buffer and allow ldisc to process ioctl */ tty_buffer_flush(tty, NULL); break; } break; case TIOCSSERIAL: tty_warn_deprecated_flags(p); break; } if (tty->ops->ioctl) { retval = tty->ops->ioctl(tty, cmd, arg); if (retval != -ENOIOCTLCMD) return retval; } ld = tty_ldisc_ref_wait(tty); retval = -EINVAL; if (ld->ops->ioctl) { retval = ld->ops->ioctl(tty, file, cmd, arg); if (retval == -ENOIOCTLCMD) retval = -ENOTTY; } tty_ldisc_deref(ld); return retval; } Commit Message: tty: Fix unsafe ldisc reference via ioctl(TIOCGETD) ioctl(TIOCGETD) retrieves the line discipline id directly from the ldisc because the line discipline id (c_line) in termios is untrustworthy; userspace may have set termios via ioctl(TCSETS*) without actually changing the line discipline via ioctl(TIOCSETD). However, directly accessing the current ldisc via tty->ldisc is unsafe; the ldisc ptr dereferenced may be stale if the line discipline is changing via ioctl(TIOCSETD) or hangup. Wait for the line discipline reference (just like read() or write()) to retrieve the "current" line discipline id. Cc: <[email protected]> Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-362
long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct tty_struct *tty = file_tty(file); struct tty_struct *real_tty; void __user *p = (void __user *)arg; int retval; struct tty_ldisc *ld; if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl")) return -EINVAL; real_tty = tty_pair_get_tty(tty); /* * Factor out some common prep work */ switch (cmd) { case TIOCSETD: case TIOCSBRK: case TIOCCBRK: case TCSBRK: case TCSBRKP: retval = tty_check_change(tty); if (retval) return retval; if (cmd != TIOCCBRK) { tty_wait_until_sent(tty, 0); if (signal_pending(current)) return -EINTR; } break; } /* * Now do the stuff. */ switch (cmd) { case TIOCSTI: return tiocsti(tty, p); case TIOCGWINSZ: return tiocgwinsz(real_tty, p); case TIOCSWINSZ: return tiocswinsz(real_tty, p); case TIOCCONS: return real_tty != tty ? -EINVAL : tioccons(file); case FIONBIO: return fionbio(file, p); case TIOCEXCL: set_bit(TTY_EXCLUSIVE, &tty->flags); return 0; case TIOCNXCL: clear_bit(TTY_EXCLUSIVE, &tty->flags); return 0; case TIOCGEXCL: { int excl = test_bit(TTY_EXCLUSIVE, &tty->flags); return put_user(excl, (int __user *)p); } case TIOCNOTTY: if (current->signal->tty != tty) return -ENOTTY; no_tty(); return 0; case TIOCSCTTY: return tiocsctty(real_tty, file, arg); case TIOCGPGRP: return tiocgpgrp(tty, real_tty, p); case TIOCSPGRP: return tiocspgrp(tty, real_tty, p); case TIOCGSID: return tiocgsid(tty, real_tty, p); case TIOCGETD: return tiocgetd(tty, p); case TIOCSETD: return tiocsetd(tty, p); case TIOCVHANGUP: if (!capable(CAP_SYS_ADMIN)) return -EPERM; tty_vhangup(tty); return 0; case TIOCGDEV: { unsigned int ret = new_encode_dev(tty_devnum(real_tty)); return put_user(ret, (unsigned int __user *)p); } /* * Break handling */ case TIOCSBRK: /* Turn break on, unconditionally */ if (tty->ops->break_ctl) return tty->ops->break_ctl(tty, -1); return 0; case TIOCCBRK: /* Turn break off, unconditionally */ if (tty->ops->break_ctl) return tty->ops->break_ctl(tty, 0); return 0; case TCSBRK: /* SVID version: non-zero arg --> no break */ /* non-zero arg means wait for all output data * to be sent (performed above) but don't send break. * This is used by the tcdrain() termios function. */ if (!arg) return send_break(tty, 250); return 0; case TCSBRKP: /* support for POSIX tcsendbreak() */ return send_break(tty, arg ? arg*100 : 250); case TIOCMGET: return tty_tiocmget(tty, p); case TIOCMSET: case TIOCMBIC: case TIOCMBIS: return tty_tiocmset(tty, cmd, p); case TIOCGICOUNT: retval = tty_tiocgicount(tty, p); /* For the moment allow fall through to the old method */ if (retval != -EINVAL) return retval; break; case TCFLSH: switch (arg) { case TCIFLUSH: case TCIOFLUSH: /* flush tty buffer and allow ldisc to process ioctl */ tty_buffer_flush(tty, NULL); break; } break; case TIOCSSERIAL: tty_warn_deprecated_flags(p); break; } if (tty->ops->ioctl) { retval = tty->ops->ioctl(tty, cmd, arg); if (retval != -ENOIOCTLCMD) return retval; } ld = tty_ldisc_ref_wait(tty); retval = -EINVAL; if (ld->ops->ioctl) { retval = ld->ops->ioctl(tty, file, cmd, arg); if (retval == -ENOIOCTLCMD) retval = -ENOTTY; } tty_ldisc_deref(ld); return retval; }
167,453
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC) { unsigned int i; zend_bool last_field_was_string = FALSE; zval **current_field, **end_field, **start_field; zend_uchar * p = row_buffer->ptr; size_t data_size = row_buffer->app; zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */ DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_aux"); if (!fields) { DBG_RETURN(FAIL); } end_field = (start_field = fields) + field_count; for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { DBG_INF("Directly creating zval"); MAKE_STD_ZVAL(*current_field); if (!*current_field) { DBG_RETURN(FAIL); } } for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { /* Don't reverse the order. It is significant!*/ zend_uchar *this_field_len_pos = p; /* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */ unsigned long len = php_mysqlnd_net_field_length(&p); if (copy_data == FALSE && current_field > start_field && last_field_was_string) { /* Normal queries: We have to put \0 now to the end of the previous field, if it was a string. IS_NULL doesn't matter. Because we have already read our length, then we can overwrite it in the row buffer. This statement terminates the previous field, not the current one. NULL_LENGTH is encoded in one byte, so we can stick a \0 there. Any string's length is encoded in at least one byte, so we can stick a \0 there. */ *this_field_len_pos = '\0'; } /* NULL or NOT NULL, this is the question! */ if (len == MYSQLND_NULL_LENGTH) { ZVAL_NULL(*current_field); last_field_was_string = FALSE; } else { #if defined(MYSQLND_STRING_TO_INT_CONVERSION) struct st_mysqlnd_perm_bind perm_bind = mysqlnd_ps_fetch_functions[fields_metadata[i].type]; #endif if (MYSQLND_G(collect_statistics)) { enum_mysqlnd_collected_stats statistic; switch (fields_metadata[i].type) { case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break; case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break; case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break; case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break; case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break; case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break; case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break; case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break; case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break; case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break; case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break; case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break; case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break; case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break; case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break; case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break; case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break; default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break; } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len); } #ifdef MYSQLND_STRING_TO_INT_CONVERSION if (as_int_or_float && perm_bind.php_type == IS_LONG) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; if (perm_bind.pack_len < SIZEOF_LONG) { /* direct conversion */ int64_t v = #ifndef PHP_WIN32 atoll((char *) p); #else _atoi64((char *) p); #endif ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } else { uint64_t v = #ifndef PHP_WIN32 (uint64_t) atoll((char *) p); #else (uint64_t) _atoi64((char *) p); #endif zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE; /* We have to make it ASCIIZ temporarily */ #if SIZEOF_LONG==8 if (uns == TRUE && v > 9223372036854775807L) #elif SIZEOF_LONG==4 if ((uns == TRUE && v > L64(2147483647)) || (uns == FALSE && (( L64(2147483647) < (int64_t) v) || (L64(-2147483648) > (int64_t) v)))) #else #error Need fix for this architecture #endif /* SIZEOF */ { ZVAL_STRINGL(*current_field, (char *)p, len, 0); } else { ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } } *(p + len) = save; } else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; ZVAL_DOUBLE(*current_field, atof((char *) p)); *(p + len) = save; } else #endif /* MYSQLND_STRING_TO_INT_CONVERSION */ if (fields_metadata[i].type == MYSQL_TYPE_BIT) { /* BIT fields are specially handled. As they come as bit mask, we have to convert it to human-readable representation. As the bits take less space in the protocol than the numbers they represent, we don't have enough space in the packet buffer to overwrite inside. Thus, a bit more space is pre-allocated at the end of the buffer, see php_mysqlnd_rowp_read(). And we add the strings at the end. Definitely not nice, _hackish_ :(, but works. */ zend_uchar *start = bit_area; ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC); /* We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because later in this function there will be an advancement. */ p -= len; if (Z_TYPE_PP(current_field) == IS_LONG) { bit_area += 1 + sprintf((char *)start, "%ld", Z_LVAL_PP(current_field)); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } else if (Z_TYPE_PP(current_field) == IS_STRING){ memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field)); bit_area += Z_STRLEN_PP(current_field); *bit_area++ = '\0'; zval_dtor(*current_field); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } } else { ZVAL_STRINGL(*current_field, (char *)p, len, copy_data); } p += len; last_field_was_string = TRUE; } } if (copy_data == FALSE && last_field_was_string) { /* Normal queries: The buffer has one more byte at the end, because we need it */ row_buffer->ptr[data_size] = '\0'; } DBG_RETURN(PASS); } Commit Message: Fix bug #72293 - Heap overflow in mysqlnd related to BIT fields CWE ID: CWE-119
php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC) { unsigned int i; zend_bool last_field_was_string = FALSE; zval **current_field, **end_field, **start_field; zend_uchar * p = row_buffer->ptr; size_t data_size = row_buffer->app; zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */ const zend_uchar * const packet_end = (zend_uchar*) row_buffer->ptr + data_size; DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_aux"); if (!fields) { DBG_RETURN(FAIL); } end_field = (start_field = fields) + field_count; for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { DBG_INF("Directly creating zval"); MAKE_STD_ZVAL(*current_field); if (!*current_field) { DBG_RETURN(FAIL); } } for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { /* Don't reverse the order. It is significant!*/ zend_uchar *this_field_len_pos = p; /* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */ const unsigned long len = php_mysqlnd_net_field_length(&p); if (len != MYSQLND_NULL_LENGTH && ((p + len) > packet_end)) { php_error_docref(NULL, E_WARNING, "Malformed server packet. Field length pointing "MYSQLND_SZ_T_SPEC " bytes after end of packet", (p + len) - packet_end - 1); DBG_RETURN(FAIL); } if (copy_data == FALSE && current_field > start_field && last_field_was_string) { /* Normal queries: We have to put \0 now to the end of the previous field, if it was a string. IS_NULL doesn't matter. Because we have already read our length, then we can overwrite it in the row buffer. This statement terminates the previous field, not the current one. NULL_LENGTH is encoded in one byte, so we can stick a \0 there. Any string's length is encoded in at least one byte, so we can stick a \0 there. */ *this_field_len_pos = '\0'; } /* NULL or NOT NULL, this is the question! */ if (len == MYSQLND_NULL_LENGTH) { ZVAL_NULL(*current_field); last_field_was_string = FALSE; } else { #if defined(MYSQLND_STRING_TO_INT_CONVERSION) struct st_mysqlnd_perm_bind perm_bind = mysqlnd_ps_fetch_functions[fields_metadata[i].type]; #endif if (MYSQLND_G(collect_statistics)) { enum_mysqlnd_collected_stats statistic; switch (fields_metadata[i].type) { case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break; case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break; case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break; case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break; case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break; case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break; case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break; case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break; case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break; case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break; case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break; case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break; case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break; case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break; case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break; case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break; case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break; default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break; } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len); } #ifdef MYSQLND_STRING_TO_INT_CONVERSION if (as_int_or_float && perm_bind.php_type == IS_LONG) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; if (perm_bind.pack_len < SIZEOF_LONG) { /* direct conversion */ int64_t v = #ifndef PHP_WIN32 atoll((char *) p); #else _atoi64((char *) p); #endif ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } else { uint64_t v = #ifndef PHP_WIN32 (uint64_t) atoll((char *) p); #else (uint64_t) _atoi64((char *) p); #endif zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE; /* We have to make it ASCIIZ temporarily */ #if SIZEOF_LONG==8 if (uns == TRUE && v > 9223372036854775807L) #elif SIZEOF_LONG==4 if ((uns == TRUE && v > L64(2147483647)) || (uns == FALSE && (( L64(2147483647) < (int64_t) v) || (L64(-2147483648) > (int64_t) v)))) #else #error Need fix for this architecture #endif /* SIZEOF */ { ZVAL_STRINGL(*current_field, (char *)p, len, 0); } else { ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } } *(p + len) = save; } else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; ZVAL_DOUBLE(*current_field, atof((char *) p)); *(p + len) = save; } else #endif /* MYSQLND_STRING_TO_INT_CONVERSION */ if (fields_metadata[i].type == MYSQL_TYPE_BIT) { /* BIT fields are specially handled. As they come as bit mask, we have to convert it to human-readable representation. As the bits take less space in the protocol than the numbers they represent, we don't have enough space in the packet buffer to overwrite inside. Thus, a bit more space is pre-allocated at the end of the buffer, see php_mysqlnd_rowp_read(). And we add the strings at the end. Definitely not nice, _hackish_ :(, but works. */ zend_uchar *start = bit_area; ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC); /* We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because later in this function there will be an advancement. */ p -= len; if (Z_TYPE_PP(current_field) == IS_LONG) { bit_area += 1 + sprintf((char *)start, "%ld", Z_LVAL_PP(current_field)); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } else if (Z_TYPE_PP(current_field) == IS_STRING){ memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field)); bit_area += Z_STRLEN_PP(current_field); *bit_area++ = '\0'; zval_dtor(*current_field); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } } else { ZVAL_STRINGL(*current_field, (char *)p, len, copy_data); } p += len; last_field_was_string = TRUE; } } if (copy_data == FALSE && last_field_was_string) { /* Normal queries: The buffer has one more byte at the end, because we need it */ row_buffer->ptr[data_size] = '\0'; } DBG_RETURN(PASS); }
166,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int get_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { /* * Because the kvm_regs structure is a mix of 32, 64 and * 128bit fields, we index it as if it was a 32bit * array. Hence below, nr_regs is the number of entries, and * off the index in the "array". */ __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); u32 off; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (copy_to_user(uaddr, ((u32 *)regs) + off, KVM_REG_SIZE(reg->id))) return -EFAULT; return 0; } Commit Message: arm64: KVM: Tighten guest core register access from userspace We currently allow userspace to access the core register file in about any possible way, including straddling multiple registers and doing unaligned accesses. This is not the expected use of the ABI, and nobody is actually using it that way. Let's tighten it by explicitly checking the size and alignment for each field of the register file. Cc: <[email protected]> Fixes: 2f4a07c5f9fe ("arm64: KVM: guest one-reg interface") Reviewed-by: Christoffer Dall <[email protected]> Reviewed-by: Mark Rutland <[email protected]> Signed-off-by: Dave Martin <[email protected]> [maz: rewrote Dave's initial patch to be more easily backported] Signed-off-by: Marc Zyngier <[email protected]> Signed-off-by: Will Deacon <[email protected]> CWE ID: CWE-20
static int get_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { /* * Because the kvm_regs structure is a mix of 32, 64 and * 128bit fields, we index it as if it was a 32bit * array. Hence below, nr_regs is the number of entries, and * off the index in the "array". */ __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); u32 off; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (validate_core_offset(reg)) return -EINVAL; if (copy_to_user(uaddr, ((u32 *)regs) + off, KVM_REG_SIZE(reg->id))) return -EFAULT; return 0; }
169,011
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer) { if (!createHarfBuzzRuns()) return false; m_totalWidth = 0; if (!shapeHarfBuzzRuns()) return false; if (glyphBuffer && !fillGlyphBuffer(glyphBuffer)) return false; return true; } Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape. [email protected] BUG=476647 Review URL: https://codereview.chromium.org/1108663003 git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer) { if (!createHarfBuzzRuns()) return false; if (!shapeHarfBuzzRuns()) return false; if (glyphBuffer && !fillGlyphBuffer(glyphBuffer)) return false; return true; }
172,005
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: produce_output() { char *str; FILE *mailer; MyString subject,szTmp; subject.sprintf("condor_preen results %s: %d old file%s found", my_full_hostname(), BadFiles->number(), (BadFiles->number() > 1)?"s":""); if( MailFlag ) { if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) { EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value()); } } else { mailer = stdout; } szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value()); dprintf(D_ALWAYS, szTmp.Value()); if( MailFlag ) { fprintf( mailer, "\n" ); fprintf( mailer, szTmp.Value()); } for( BadFiles->rewind(); (str = BadFiles->next()); ) { szTmp.sprintf(" %s\n", str); dprintf(D_ALWAYS, szTmp.Value() ); fprintf( mailer, szTmp.Value() ); } if( MailFlag ) { const char *explanation = "\n\nWhat is condor_preen?\n\n" "The condor_preen tool examines the directories belonging to Condor, and\n" "removes extraneous files and directories which may be left over from Condor\n" "processes which terminated abnormally either due to internal errors or a\n" "system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n" "directories as defined in the Condor configuration files. The condor_preen\n" "tool is intended to be run as user root (or user condor) periodically as a\n" "backup method to ensure reasonable file system cleanliness in the face of\n" "errors. This is done automatically by default by the condor_master daemon.\n" "It may also be explicitly invoked on an as needed basis.\n\n" "See the Condor manual section on condor_preen for more details.\n"; fprintf( mailer, "%s\n", explanation ); email_close( mailer ); } } Commit Message: CWE ID: CWE-134
produce_output() { char *str; FILE *mailer; MyString subject,szTmp; subject.sprintf("condor_preen results %s: %d old file%s found", my_full_hostname(), BadFiles->number(), (BadFiles->number() > 1)?"s":""); if( MailFlag ) { if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) { EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value()); } } else { mailer = stdout; } szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value()); dprintf(D_ALWAYS, "%s", szTmp.Value()); if( MailFlag ) { fprintf( mailer, "\n" ); fprintf( mailer, "%s", szTmp.Value()); } for( BadFiles->rewind(); (str = BadFiles->next()); ) { szTmp.sprintf(" %s\n", str); dprintf(D_ALWAYS, "%s", szTmp.Value() ); fprintf( mailer, "%s", szTmp.Value() ); } if( MailFlag ) { const char *explanation = "\n\nWhat is condor_preen?\n\n" "The condor_preen tool examines the directories belonging to Condor, and\n" "removes extraneous files and directories which may be left over from Condor\n" "processes which terminated abnormally either due to internal errors or a\n" "system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n" "directories as defined in the Condor configuration files. The condor_preen\n" "tool is intended to be run as user root (or user condor) periodically as a\n" "backup method to ensure reasonable file system cleanliness in the face of\n" "errors. This is done automatically by default by the condor_master daemon.\n" "It may also be explicitly invoked on an as needed basis.\n\n" "See the Condor manual section on condor_preen for more details.\n"; fprintf( mailer, "%s\n", explanation ); email_close( mailer ); } }
165,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrowserContextDestroyer::BrowserContextDestroyer( BrowserContext* context, const std::set<content::RenderProcessHost*>& hosts) : context_(context), pending_hosts_(0) { for (std::set<content::RenderProcessHost*>::iterator it = hosts.begin(); it != hosts.end(); ++it) { (*it)->AddObserver(this); ++pending_hosts_; } } Commit Message: CWE ID: CWE-20
BrowserContextDestroyer::BrowserContextDestroyer( std::unique_ptr<BrowserContext> context, const std::set<content::RenderProcessHost*>& hosts, uint32_t otr_contexts_pending_deletion) : context_(std::move(context)), otr_contexts_pending_deletion_(otr_contexts_pending_deletion), finish_destroy_scheduled_(false) { DCHECK(hosts.size() > 0 || (!context->IsOffTheRecord() && (otr_contexts_pending_deletion > 0 || context->HasOffTheRecordContext()))); g_contexts_pending_deletion.Get().push_back(this); for (auto* host : hosts) { ObserveHost(host); } }
165,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2; int thick = im->thick; int t; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { t=y1; y1 = y2; y2 = t; t = x1; x1 = x2; x2 = t; } x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2; if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { y1v = y1h + 1; y2v = y2h - 1; gdImageLine(im, x1h, y1h, x2h, y1h, color); gdImageLine(im, x1h, y2h, x2h, y2h, color); gdImageLine(im, x1v, y1v, x1v, y2v, color); gdImageLine(im, x2v, y1v, x2v, y2v, color); } } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2; int thick = im->thick; int t; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { t=y1; y1 = y2; y2 = t; t = x1; x1 = x2; x2 = t; } x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2; if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { y1v = y1h + 1; y2v = y2h - 1; gdImageLine(im, x1h, y1h, x2h, y1h, color); gdImageLine(im, x1h, y2h, x2h, y2h, color); gdImageLine(im, x1v, y1v, x1v, y2v, color); gdImageLine(im, x2v, y1v, x2v, y2v, color); } }
167,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_get_value (MyObject *obj, guint *ret, GError **error) { *ret = obj->val; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_get_value (MyObject *obj, guint *ret, GError **error)
165,104
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); if (getGraphicBufferSource() != NULL) { android_errorWriteLog(0x534e4554, "29422020"); return INVALID_OPERATION; } OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); } Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer Bug: 29422020 Bug: 31412859 Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375 (cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2) CWE ID: CWE-200
status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); if (getGraphicBufferSource() != NULL) { android_errorWriteLog(0x534e4554, "29422020"); return INVALID_OPERATION; } OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); // set up proper filled length if component is configured for gralloc metadata mode // ignore rangeOffset in this case (as client may be assuming ANW meta buffers). if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource) { header->nFilledLen = rangeLength ? sizeof(VideoGrallocMetadata) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); }
174,145
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int handle_wrmsr(struct kvm_vcpu *vcpu) { struct msr_data msr; u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX]; u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u) | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32); msr.data = data; msr.index = ecx; msr.host_initiated = false; if (vmx_set_msr(vcpu, &msr) != 0) { trace_kvm_msr_write_ex(ecx, data); kvm_inject_gp(vcpu, 0); return 1; } trace_kvm_msr_write(ecx, data); skip_emulated_instruction(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 handle_wrmsr(struct kvm_vcpu *vcpu) { struct msr_data msr; u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX]; u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u) | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32); msr.data = data; msr.index = ecx; msr.host_initiated = false; if (kvm_set_msr(vcpu, &msr) != 0) { trace_kvm_msr_write_ex(ecx, data); kvm_inject_gp(vcpu, 0); return 1; } trace_kvm_msr_write(ecx, data); skip_emulated_instruction(vcpu); return 1; }
166,349
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GF_Err urn_Read(GF_Box *s, GF_BitStream *bs) { u32 i, to_read; char *tmpName; GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if (! ptr->size ) return GF_OK; to_read = (u32) ptr->size; tmpName = (char*)gf_malloc(sizeof(char) * to_read); if (!tmpName) return GF_OUT_OF_MEM; gf_bs_read_data(bs, tmpName, to_read); i = 0; while ( (tmpName[i] != 0) && (i < to_read) ) { i++; } if (i == to_read) { gf_free(tmpName); return GF_ISOM_INVALID_FILE; } if (i == to_read - 1) { ptr->nameURN = tmpName; ptr->location = NULL; return GF_OK; } ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1)); if (!ptr->nameURN) { gf_free(tmpName); return GF_OUT_OF_MEM; } ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1)); if (!ptr->location) { gf_free(tmpName); gf_free(ptr->nameURN); ptr->nameURN = NULL; return GF_OUT_OF_MEM; } memcpy(ptr->nameURN, tmpName, i + 1); memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1)); gf_free(tmpName); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
GF_Err urn_Read(GF_Box *s, GF_BitStream *bs) { u32 i, to_read; char *tmpName; GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if (! ptr->size ) return GF_OK; to_read = (u32) ptr->size; tmpName = (char*)gf_malloc(sizeof(char) * to_read); if (!tmpName) return GF_OUT_OF_MEM; gf_bs_read_data(bs, tmpName, to_read); i = 0; while ( (i < to_read) && (tmpName[i] != 0) ) { i++; } if (i == to_read) { gf_free(tmpName); return GF_ISOM_INVALID_FILE; } if (i == to_read - 1) { ptr->nameURN = tmpName; ptr->location = NULL; return GF_OK; } ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1)); if (!ptr->nameURN) { gf_free(tmpName); return GF_OUT_OF_MEM; } ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1)); if (!ptr->location) { gf_free(tmpName); gf_free(ptr->nameURN); ptr->nameURN = NULL; return GF_OUT_OF_MEM; } memcpy(ptr->nameURN, tmpName, i + 1); memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1)); gf_free(tmpName); return GF_OK; }
169,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PixarLogClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer overflow on generation of PixarLog / LUV compressed files, with ColorMap, TransferFunction attached and nasty plays with bitspersample. The fix for LUV has not been tested, but suffers from the same kind of issue of PixarLog. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604 CWE ID: CWE-125
PixarLogClose(TIFF* tif) { PixarLogState* sp = (PixarLogState*) tif->tif_data; TIFFDirectory *td = &tif->tif_dir; assert(sp != 0); /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ if (sp->state&PLSTATE_INIT) { /* We test the state to avoid an issue such as in * http://bugzilla.maptools.org/show_bug.cgi?id=2604 * What appends in that case is that the bitspersample is 1 and * a TransferFunction is set. The size of the TransferFunction * depends on 1<<bitspersample. So if we increase it, an access * out of the buffer will happen at directory flushing. * Another option would be to clear those targs. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } }
168,466
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltValueOf(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemValueOfPtr comp = (xsltStyleItemValueOfPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xmlXPathObjectPtr res = NULL; xmlChar *value = NULL; xmlDocPtr oldXPContextDoc; xmlNsPtr *oldXPNamespaces; xmlNodePtr oldXPContextNode; int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; xmlXPathContextPtr xpctxt; if ((ctxt == NULL) || (node == NULL) || (inst == NULL)) return; if ((comp == NULL) || (comp->select == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltValueOf(): " "The XSLT 'value-of' instruction was not compiled.\n"); return; } #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_VALUE_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltValueOf: select %s\n", comp->select)); #endif xpctxt = ctxt->xpathCtxt; oldXPContextDoc = xpctxt->doc; oldXPContextNode = xpctxt->node; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; xpctxt->node = node; if (comp != NULL) { #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } res = xmlXPathCompiledEval(comp->comp, xpctxt); xpctxt->doc = oldXPContextDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; /* * Cast the XPath object to string. */ if (res != NULL) { value = xmlXPathCastToString(res); if (value == NULL) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltValueOf(): " "failed to cast an XPath object to string.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } if (value[0] != 0) { xsltCopyTextString(ctxt, ctxt->insert, value, comp->noescape); } } else { xsltTransformError(ctxt, NULL, inst, "XPath evaluation returned no result.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } #ifdef WITH_XSLT_DEBUG_PROCESS if (value) { XSLT_TRACE(ctxt,XSLT_TRACE_VALUE_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltValueOf: result '%s'\n", value)); } #endif error: if (value != NULL) xmlFree(value); if (res != NULL) xmlXPathFreeObject(res); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltValueOf(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemValueOfPtr comp = (xsltStyleItemValueOfPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xmlXPathObjectPtr res = NULL; xmlChar *value = NULL; if ((ctxt == NULL) || (node == NULL) || (inst == NULL)) return; if ((comp == NULL) || (comp->select == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltValueOf(): " "The XSLT 'value-of' instruction was not compiled.\n"); return; } #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_VALUE_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltValueOf: select %s\n", comp->select)); #endif res = xsltPreCompEval(ctxt, node, comp); /* * Cast the XPath object to string. */ if (res != NULL) { value = xmlXPathCastToString(res); if (value == NULL) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltValueOf(): " "failed to cast an XPath object to string.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } if (value[0] != 0) { xsltCopyTextString(ctxt, ctxt->insert, value, comp->noescape); } } else { xsltTransformError(ctxt, NULL, inst, "XPath evaluation returned no result.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } #ifdef WITH_XSLT_DEBUG_PROCESS if (value) { XSLT_TRACE(ctxt,XSLT_TRACE_VALUE_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltValueOf: result '%s'\n", value)); } #endif error: if (value != NULL) xmlFree(value); if (res != NULL) xmlXPathFreeObject(res); }
173,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void set_own_dir(const char *argv0) { size_t l = strlen(argv0); while(l && argv0[l - 1] != '/') l--; if(l == 0) memcpy(own_dir, ".", 2); else { memcpy(own_dir, argv0, l - 1); own_dir[l] = 0; } } Commit Message: fix for CVE-2015-3887 closes #60 CWE ID: CWE-426
static void set_own_dir(const char *argv0) { size_t l = strlen(argv0); while(l && argv0[l - 1] != '/') l--; if(l == 0) #ifdef SUPER_SECURE memcpy(own_dir, "/dev/null/", 2); #else memcpy(own_dir, ".", 2); #endif else { memcpy(own_dir, argv0, l - 1); own_dir[l] = 0; } }
168,884
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int key_reject_and_link(struct key *key, unsigned timeout, unsigned error, struct key *keyring, struct key *authkey) { struct assoc_array_edit *edit; struct timespec now; int ret, awaken, link_ret = 0; key_check(key); key_check(keyring); awaken = 0; ret = -EBUSY; if (keyring) { if (keyring->restrict_link) return -EPERM; link_ret = __key_link_begin(keyring, &key->index_key, &edit); } mutex_lock(&key_construction_mutex); /* can't instantiate twice */ if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { /* mark the key as being negatively instantiated */ atomic_inc(&key->user->nikeys); key->reject_error = -error; smp_wmb(); set_bit(KEY_FLAG_NEGATIVE, &key->flags); set_bit(KEY_FLAG_INSTANTIATED, &key->flags); now = current_kernel_time(); key->expiry = now.tv_sec + timeout; key_schedule_gc(key->expiry + key_gc_delay); if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) awaken = 1; ret = 0; /* and link it into the destination keyring */ if (keyring && link_ret == 0) __key_link(key, &edit); /* disable the authorisation key */ if (authkey) key_revoke(authkey); } mutex_unlock(&key_construction_mutex); if (keyring && link_ret == 0) __key_link_end(keyring, &key->index_key, edit); /* wake up anyone waiting for a key to be constructed */ if (awaken) wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT); return ret == 0 ? link_ret : ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
int key_reject_and_link(struct key *key, unsigned timeout, unsigned error, struct key *keyring, struct key *authkey) { struct assoc_array_edit *edit; struct timespec now; int ret, awaken, link_ret = 0; key_check(key); key_check(keyring); awaken = 0; ret = -EBUSY; if (keyring) { if (keyring->restrict_link) return -EPERM; link_ret = __key_link_begin(keyring, &key->index_key, &edit); } mutex_lock(&key_construction_mutex); /* can't instantiate twice */ if (key->state == KEY_IS_UNINSTANTIATED) { /* mark the key as being negatively instantiated */ atomic_inc(&key->user->nikeys); mark_key_instantiated(key, -error); now = current_kernel_time(); key->expiry = now.tv_sec + timeout; key_schedule_gc(key->expiry + key_gc_delay); if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) awaken = 1; ret = 0; /* and link it into the destination keyring */ if (keyring && link_ret == 0) __key_link(key, &edit); /* disable the authorisation key */ if (authkey) key_revoke(authkey); } mutex_unlock(&key_construction_mutex); if (keyring && link_ret == 0) __key_link_end(keyring, &key->index_key, edit); /* wake up anyone waiting for a key to be constructed */ if (awaken) wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT); return ret == 0 ? link_ret : ret; }
167,698
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sysapi_translate_arch( const char *machine, const char *) { char tmp[64]; char *tmparch; #if defined(AIX) /* AIX machines have a ton of different models encoded into the uname structure, so go to some other function to decode and group the architecture together */ struct utsname buf; if( uname(&buf) < 0 ) { return NULL; } return( get_aix_arch( &buf ) ); #elif defined(HPUX) return( get_hpux_arch( ) ); #else if( !strcmp(machine, "alpha") ) { sprintf( tmp, "ALPHA" ); } else if( !strcmp(machine, "i86pc") ) { sprintf( tmp, "INTEL" ); } else if( !strcmp(machine, "i686") ) { sprintf( tmp, "INTEL" ); } else if( !strcmp(machine, "i586") ) { sprintf( tmp, "INTEL" ); } else if( !strcmp(machine, "i486") ) { sprintf( tmp, "INTEL" ); } else if( !strcmp(machine, "i386") ) { //LDAP entry #if defined(Darwin) /* Mac OS X often claims to be i386 in uname, even if the * hardware is x86_64 and the OS can run 64-bit binaries. * We'll base our architecture name on the default build * target for gcc. In 10.5 and earlier, that's i386. * On 10.6, it's x86_64. * The value we're querying is the kernel version. * 10.6 kernels have a version that starts with "10." * Older versions have a lower first number. */ int ret; char val[32]; size_t len = sizeof(val); /* assume x86 */ sprintf( tmp, "INTEL" ); ret = sysctlbyname("kern.osrelease", &val, &len, NULL, 0); if (ret == 0 && strncmp(val, "10.", 3) == 0) { /* but we could be proven wrong */ sprintf( tmp, "X86_64" ); } #else sprintf( tmp, "INTEL" ); #endif } else if( !strcmp(machine, "ia64") ) { sprintf( tmp, "IA64" ); } else if( !strcmp(machine, "x86_64") ) { sprintf( tmp, "X86_64" ); } else if( !strcmp(machine, "amd64") ) { sprintf( tmp, "X86_64" ); } else if( !strcmp(machine, "sun4u") ) { sprintf( tmp, "SUN4u" ); } else if( !strcmp(machine, "sun4m") ) { sprintf( tmp, "SUN4x" ); } else if( !strcmp(machine, "sun4c") ) { sprintf( tmp, "SUN4x" ); } else if( !strcmp(machine, "sparc") ) { //LDAP entry sprintf( tmp, "SUN4x" ); } else if( !strcmp(machine, "Power Macintosh") ) { //LDAP entry sprintf( tmp, "PPC" ); } else if( !strcmp(machine, "ppc") ) { sprintf( tmp, "PPC" ); } else if( !strcmp(machine, "ppc32") ) { sprintf( tmp, "PPC" ); } else if( !strcmp(machine, "ppc64") ) { sprintf( tmp, "PPC64" ); } else { sprintf( tmp, machine ); } tmparch = strdup( tmp ); if( !tmparch ) { EXCEPT( "Out of memory!" ); } return( tmparch ); #endif /* if HPUX else */ } Commit Message: CWE ID: CWE-134
sysapi_translate_arch( const char *machine, const char *) { char tmp[64]; char *tmparch; #if defined(AIX) /* AIX machines have a ton of different models encoded into the uname structure, so go to some other function to decode and group the architecture together */ struct utsname buf; if( uname(&buf) < 0 ) { return NULL; } return( get_aix_arch( &buf ) ); #elif defined(HPUX) return( get_hpux_arch( ) ); #else if( !strcmp(machine, "alpha") ) { sprintf( tmp, "ALPHA" ); } else if( !strcmp(machine, "i86pc") ) { sprintf( tmp, "INTEL" ); } else if( !strcmp(machine, "i686") ) { sprintf( tmp, "INTEL" ); } else if( !strcmp(machine, "i586") ) { sprintf( tmp, "INTEL" ); } else if( !strcmp(machine, "i486") ) { sprintf( tmp, "INTEL" ); } else if( !strcmp(machine, "i386") ) { //LDAP entry #if defined(Darwin) /* Mac OS X often claims to be i386 in uname, even if the * hardware is x86_64 and the OS can run 64-bit binaries. * We'll base our architecture name on the default build * target for gcc. In 10.5 and earlier, that's i386. * On 10.6, it's x86_64. * The value we're querying is the kernel version. * 10.6 kernels have a version that starts with "10." * Older versions have a lower first number. */ int ret; char val[32]; size_t len = sizeof(val); /* assume x86 */ sprintf( tmp, "INTEL" ); ret = sysctlbyname("kern.osrelease", &val, &len, NULL, 0); if (ret == 0 && strncmp(val, "10.", 3) == 0) { /* but we could be proven wrong */ sprintf( tmp, "X86_64" ); } #else sprintf( tmp, "INTEL" ); #endif } else if( !strcmp(machine, "ia64") ) { sprintf( tmp, "IA64" ); } else if( !strcmp(machine, "x86_64") ) { sprintf( tmp, "X86_64" ); } else if( !strcmp(machine, "amd64") ) { sprintf( tmp, "X86_64" ); } else if( !strcmp(machine, "sun4u") ) { sprintf( tmp, "SUN4u" ); } else if( !strcmp(machine, "sun4m") ) { sprintf( tmp, "SUN4x" ); } else if( !strcmp(machine, "sun4c") ) { sprintf( tmp, "SUN4x" ); } else if( !strcmp(machine, "sparc") ) { //LDAP entry sprintf( tmp, "SUN4x" ); } else if( !strcmp(machine, "Power Macintosh") ) { //LDAP entry sprintf( tmp, "PPC" ); } else if( !strcmp(machine, "ppc") ) { sprintf( tmp, "PPC" ); } else if( !strcmp(machine, "ppc32") ) { sprintf( tmp, "PPC" ); } else if( !strcmp(machine, "ppc64") ) { sprintf( tmp, "PPC64" ); } else { sprintf( tmp, "%s", machine ); } tmparch = strdup( tmp ); if( !tmparch ) { EXCEPT( "Out of memory!" ); } return( tmparch ); #endif /* if HPUX else */ }
165,380
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int a2dp_command(struct a2dp_stream_common *common, char cmd) { char ack; DEBUG("A2DP COMMAND %s", dump_a2dp_ctrl_event(cmd)); /* send command */ if (send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL) == -1) { ERROR("cmd failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } /* wait for ack byte */ if (a2dp_ctrl_receive(common, &ack, 1) < 0) return -1; DEBUG("A2DP COMMAND %s DONE STATUS %d", dump_a2dp_ctrl_event(cmd), ack); if (ack == A2DP_CTRL_ACK_INCALL_FAILURE) return ack; if (ack != A2DP_CTRL_ACK_SUCCESS) return -1; return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int a2dp_command(struct a2dp_stream_common *common, char cmd) { char ack; DEBUG("A2DP COMMAND %s", dump_a2dp_ctrl_event(cmd)); /* send command */ if (TEMP_FAILURE_RETRY(send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL)) == -1) { ERROR("cmd failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } /* wait for ack byte */ if (a2dp_ctrl_receive(common, &ack, 1) < 0) return -1; DEBUG("A2DP COMMAND %s DONE STATUS %d", dump_a2dp_ctrl_event(cmd), ack); if (ack == A2DP_CTRL_ACK_INCALL_FAILURE) return ack; if (ack != A2DP_CTRL_ACK_SUCCESS) return -1; return 0; }
173,422
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ixheaacd_qmf_hbe_data_reinit(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer, WORD16 *p_freq_band_tab[2], WORD16 *p_num_sfb, WORD32 upsamp_4_flag) { WORD32 synth_size, sfb, patch, stop_patch; if (ptr_hbe_txposer != NULL) { ptr_hbe_txposer->start_band = p_freq_band_tab[LOW][0]; ptr_hbe_txposer->end_band = p_freq_band_tab[LOW][p_num_sfb[LOW]]; ptr_hbe_txposer->synth_size = 4 * ((ptr_hbe_txposer->start_band + 4) / 8 + 1); ptr_hbe_txposer->k_start = ixheaacd_start_subband2kL_tbl[ptr_hbe_txposer->start_band]; ptr_hbe_txposer->upsamp_4_flag = upsamp_4_flag; if (upsamp_4_flag) { if (ptr_hbe_txposer->k_start + ptr_hbe_txposer->synth_size > 16) ptr_hbe_txposer->k_start = 16 - ptr_hbe_txposer->synth_size; } else if (ptr_hbe_txposer->core_frame_length == 768) { if (ptr_hbe_txposer->k_start + ptr_hbe_txposer->synth_size > 24) ptr_hbe_txposer->k_start = 24 - ptr_hbe_txposer->synth_size; } memset(ptr_hbe_txposer->synth_buf, 0, 1280 * sizeof(FLOAT32)); synth_size = ptr_hbe_txposer->synth_size; ptr_hbe_txposer->synth_buf_offset = 18 * synth_size; switch (synth_size) { case 4: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_4; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_8; ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2; ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2; break; case 8: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_8; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_16; ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2; ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2; break; case 12: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_12; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_24; ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p3; ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p3; break; case 16: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_16; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_32; ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2; ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2; break; case 20: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_20; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_40; break; default: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_4; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_8; ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2; ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2; } ptr_hbe_txposer->synth_wind_coeff = ixheaacd_map_prot_filter(synth_size); memset(ptr_hbe_txposer->analy_buf, 0, 640 * sizeof(FLOAT32)); synth_size = 2 * ptr_hbe_txposer->synth_size; ptr_hbe_txposer->analy_wind_coeff = ixheaacd_map_prot_filter(synth_size); memset(ptr_hbe_txposer->x_over_qmf, 0, MAX_NUM_PATCHES * sizeof(WORD32)); sfb = 0; if (upsamp_4_flag) { stop_patch = MAX_NUM_PATCHES; ptr_hbe_txposer->max_stretch = MAX_STRETCH; } else { stop_patch = MAX_STRETCH; } for (patch = 1; patch <= stop_patch; patch++) { while (sfb <= p_num_sfb[LOW] && p_freq_band_tab[LOW][sfb] <= patch * ptr_hbe_txposer->start_band) sfb++; if (sfb <= p_num_sfb[LOW]) { if ((patch * ptr_hbe_txposer->start_band - p_freq_band_tab[LOW][sfb - 1]) <= 3) { ptr_hbe_txposer->x_over_qmf[patch - 1] = p_freq_band_tab[LOW][sfb - 1]; } else { WORD32 sfb = 0; while (sfb <= p_num_sfb[HIGH] && p_freq_band_tab[HIGH][sfb] <= patch * ptr_hbe_txposer->start_band) sfb++; ptr_hbe_txposer->x_over_qmf[patch - 1] = p_freq_band_tab[HIGH][sfb - 1]; } } else { ptr_hbe_txposer->x_over_qmf[patch - 1] = ptr_hbe_txposer->end_band; ptr_hbe_txposer->max_stretch = min(patch, MAX_STRETCH); break; } } } if (ptr_hbe_txposer->k_start < 0) { return -1; } return 0; } Commit Message: Fix for stack corruption in esbr Bug: 110769924 Test: poc from bug before/after Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e (cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a) (cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50) CWE ID: CWE-787
WORD32 ixheaacd_qmf_hbe_data_reinit(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer, WORD16 *p_freq_band_tab[2], WORD16 *p_num_sfb, WORD32 upsamp_4_flag) { WORD32 synth_size, sfb, patch, stop_patch; if (ptr_hbe_txposer != NULL) { ptr_hbe_txposer->start_band = p_freq_band_tab[LOW][0]; ptr_hbe_txposer->end_band = p_freq_band_tab[LOW][p_num_sfb[LOW]]; ptr_hbe_txposer->synth_size = 4 * ((ptr_hbe_txposer->start_band + 4) / 8 + 1); ptr_hbe_txposer->k_start = ixheaacd_start_subband2kL_tbl[ptr_hbe_txposer->start_band]; ptr_hbe_txposer->upsamp_4_flag = upsamp_4_flag; if (upsamp_4_flag) { if (ptr_hbe_txposer->k_start + ptr_hbe_txposer->synth_size > 16) ptr_hbe_txposer->k_start = 16 - ptr_hbe_txposer->synth_size; } else if (ptr_hbe_txposer->core_frame_length == 768) { if (ptr_hbe_txposer->k_start + ptr_hbe_txposer->synth_size > 24) ptr_hbe_txposer->k_start = 24 - ptr_hbe_txposer->synth_size; } memset(ptr_hbe_txposer->synth_buf, 0, 1280 * sizeof(FLOAT32)); synth_size = ptr_hbe_txposer->synth_size; ptr_hbe_txposer->synth_buf_offset = 18 * synth_size; switch (synth_size) { case 4: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_4; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_8; ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2; ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2; break; case 8: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_8; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_16; ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2; ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2; break; case 12: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_12; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_24; ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p3; ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p3; break; case 16: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_16; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_32; ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2; ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2; break; case 20: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_20; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_40; break; default: ptr_hbe_txposer->synth_cos_tab = (FLOAT32 *)ixheaacd_synth_cos_table_kl_4; ptr_hbe_txposer->analy_cos_sin_tab = (FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_8; ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2; ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2; } ptr_hbe_txposer->synth_wind_coeff = ixheaacd_map_prot_filter(synth_size); memset(ptr_hbe_txposer->analy_buf, 0, 640 * sizeof(FLOAT32)); synth_size = 2 * ptr_hbe_txposer->synth_size; ptr_hbe_txposer->analy_wind_coeff = ixheaacd_map_prot_filter(synth_size); memset(ptr_hbe_txposer->x_over_qmf, 0, MAX_NUM_PATCHES * sizeof(WORD32)); sfb = 0; if (upsamp_4_flag) { stop_patch = MAX_NUM_PATCHES; ptr_hbe_txposer->max_stretch = MAX_STRETCH; } else { stop_patch = MAX_STRETCH; } for (patch = 1; patch <= stop_patch; patch++) { while (sfb <= p_num_sfb[LOW] && p_freq_band_tab[LOW][sfb] <= patch * ptr_hbe_txposer->start_band) sfb++; if (sfb <= p_num_sfb[LOW]) { if ((patch * ptr_hbe_txposer->start_band - p_freq_band_tab[LOW][sfb - 1]) <= 3) { ptr_hbe_txposer->x_over_qmf[patch - 1] = p_freq_band_tab[LOW][sfb - 1]; } else { WORD32 sfb = 0; while (sfb <= p_num_sfb[HIGH] && p_freq_band_tab[HIGH][sfb] <= patch * ptr_hbe_txposer->start_band) sfb++; ptr_hbe_txposer->x_over_qmf[patch - 1] = p_freq_band_tab[HIGH][sfb - 1]; } } else { ptr_hbe_txposer->x_over_qmf[patch - 1] = ptr_hbe_txposer->end_band; ptr_hbe_txposer->max_stretch = min(patch, MAX_STRETCH); break; } } if (ptr_hbe_txposer->k_start < 0) { return -1; } } return 0; }
174,092
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void sum_update(const char *p, int32 len) { switch (cursum_type) { case CSUM_MD5: md5_update(&md, (uchar *)p, len); break; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: if (len + sumresidue < CSUM_CHUNK) { memcpy(md.buffer + sumresidue, p, len); sumresidue += len; } if (sumresidue) { int32 i = CSUM_CHUNK - sumresidue; memcpy(md.buffer + sumresidue, p, i); mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK); len -= i; p += i; } while (len >= CSUM_CHUNK) { mdfour_update(&md, (uchar *)p, CSUM_CHUNK); len -= CSUM_CHUNK; p += CSUM_CHUNK; } sumresidue = len; if (sumresidue) memcpy(md.buffer, p, sumresidue); break; case CSUM_NONE: break; } } Commit Message: CWE ID: CWE-354
void sum_update(const char *p, int32 len) { switch (cursum_type) { case CSUM_MD5: md5_update(&md, (uchar *)p, len); break; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: case CSUM_MD4_ARCHAIC: if (len + sumresidue < CSUM_CHUNK) { memcpy(md.buffer + sumresidue, p, len); sumresidue += len; } if (sumresidue) { int32 i = CSUM_CHUNK - sumresidue; memcpy(md.buffer + sumresidue, p, i); mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK); len -= i; p += i; } while (len >= CSUM_CHUNK) { mdfour_update(&md, (uchar *)p, CSUM_CHUNK); len -= CSUM_CHUNK; p += CSUM_CHUNK; } sumresidue = len; if (sumresidue) memcpy(md.buffer, p, sumresidue); break; case CSUM_NONE: break; } }
164,640
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URI, int line, int nsNr, int tlen) { const xmlChar *name; GROW; if ((RAW != '<') || (NXT(1) != '/')) { xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL); return; } SKIP(2); if ((tlen > 0) && (xmlStrncmp(ctxt->input->cur, ctxt->name, tlen) == 0)) { if (ctxt->input->cur[tlen] == '>') { ctxt->input->cur += tlen + 1; goto done; } ctxt->input->cur += tlen; name = (xmlChar*)1; } else { if (prefix == NULL) name = xmlParseNameAndCompare(ctxt, ctxt->name); else name = xmlParseQNameAndCompare(ctxt, ctxt->name, prefix); } /* * We should definitely be at the ending "S? '>'" part */ GROW; SKIP_BLANKS; if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); } else NEXT1; /* * [ WFC: Element Type Match ] * The Name in an element's end-tag must match the element type in the * start-tag. * */ if (name != (xmlChar*)1) { if (name == NULL) name = BAD_CAST "unparseable"; if ((line == 0) && (ctxt->node != NULL)) line = ctxt->node->line; xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH, "Opening and ending tag mismatch: %s line %d and %s\n", ctxt->name, line, name); } /* * SAX: End of Tag */ done: if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, ctxt->name, prefix, URI); spacePop(ctxt); if (nsNr != 0) nsPop(ctxt, nsNr); return; } 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
xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URI, int line, int nsNr, int tlen) { const xmlChar *name; GROW; if ((RAW != '<') || (NXT(1) != '/')) { xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL); return; } SKIP(2); if ((tlen > 0) && (xmlStrncmp(ctxt->input->cur, ctxt->name, tlen) == 0)) { if (ctxt->input->cur[tlen] == '>') { ctxt->input->cur += tlen + 1; goto done; } ctxt->input->cur += tlen; name = (xmlChar*)1; } else { if (prefix == NULL) name = xmlParseNameAndCompare(ctxt, ctxt->name); else name = xmlParseQNameAndCompare(ctxt, ctxt->name, prefix); } /* * We should definitely be at the ending "S? '>'" part */ GROW; if (ctxt->instate == XML_PARSER_EOF) return; SKIP_BLANKS; if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); } else NEXT1; /* * [ WFC: Element Type Match ] * The Name in an element's end-tag must match the element type in the * start-tag. * */ if (name != (xmlChar*)1) { if (name == NULL) name = BAD_CAST "unparseable"; if ((line == 0) && (ctxt->node != NULL)) line = ctxt->node->line; xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH, "Opening and ending tag mismatch: %s line %d and %s\n", ctxt->name, line, name); } /* * SAX: End of Tag */ done: if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, ctxt->name, prefix, URI); spacePop(ctxt); if (nsNr != 0) nsPop(ctxt, nsNr); return; }
171,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SyncBackendHost::Initialize( SyncFrontend* frontend, const GURL& sync_service_url, const syncable::ModelTypeSet& types, net::URLRequestContextGetter* baseline_context_getter, const SyncCredentials& credentials, bool delete_sync_data_folder) { if (!core_thread_.Start()) return; frontend_ = frontend; DCHECK(frontend); registrar_.workers[GROUP_DB] = new DatabaseModelWorker(); registrar_.workers[GROUP_UI] = new UIModelWorker(); registrar_.workers[GROUP_PASSIVE] = new ModelSafeWorker(); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableSyncTypedUrls) || types.count(syncable::TYPED_URLS)) { registrar_.workers[GROUP_HISTORY] = new HistoryModelWorker( profile_->GetHistoryService(Profile::IMPLICIT_ACCESS)); } for (syncable::ModelTypeSet::const_iterator it = types.begin(); it != types.end(); ++it) { registrar_.routing_info[(*it)] = GROUP_PASSIVE; } PasswordStore* password_store = profile_->GetPasswordStore(Profile::IMPLICIT_ACCESS); if (password_store) { registrar_.workers[GROUP_PASSWORD] = new PasswordModelWorker(password_store); } else { LOG_IF(WARNING, types.count(syncable::PASSWORDS) > 0) << "Password store " << "not initialized, cannot sync passwords"; registrar_.routing_info.erase(syncable::PASSWORDS); } registrar_.routing_info[syncable::NIGORI] = GROUP_PASSIVE; core_->CreateSyncNotifier(baseline_context_getter); InitCore(Core::DoInitializeOptions( sync_service_url, MakeHttpBridgeFactory(baseline_context_getter), credentials, delete_sync_data_folder, RestoreEncryptionBootstrapToken(), false)); } Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed. BUG=69561 TEST=Run sync manually and run integration tests, sync should not crash. Review URL: http://codereview.chromium.org/7016007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void SyncBackendHost::Initialize( SyncFrontend* frontend, const GURL& sync_service_url, const syncable::ModelTypeSet& types, net::URLRequestContextGetter* baseline_context_getter, const SyncCredentials& credentials, bool delete_sync_data_folder) { if (!core_thread_.Start()) return; frontend_ = frontend; DCHECK(frontend); registrar_.workers[GROUP_DB] = new DatabaseModelWorker(); registrar_.workers[GROUP_UI] = new UIModelWorker(); registrar_.workers[GROUP_PASSIVE] = new ModelSafeWorker(); registrar_.workers[GROUP_HISTORY] = new HistoryModelWorker( profile_->GetHistoryService(Profile::IMPLICIT_ACCESS)); for (syncable::ModelTypeSet::const_iterator it = types.begin(); it != types.end(); ++it) { registrar_.routing_info[(*it)] = GROUP_PASSIVE; } PasswordStore* password_store = profile_->GetPasswordStore(Profile::IMPLICIT_ACCESS); if (password_store) { registrar_.workers[GROUP_PASSWORD] = new PasswordModelWorker(password_store); } else { LOG_IF(WARNING, types.count(syncable::PASSWORDS) > 0) << "Password store " << "not initialized, cannot sync passwords"; registrar_.routing_info.erase(syncable::PASSWORDS); } registrar_.routing_info[syncable::NIGORI] = GROUP_PASSIVE; core_->CreateSyncNotifier(baseline_context_getter); InitCore(Core::DoInitializeOptions( sync_service_url, MakeHttpBridgeFactory(baseline_context_getter), credentials, delete_sync_data_folder, RestoreEncryptionBootstrapToken(), false)); }
170,614
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_DeleteItemFromObject( cJSON *object, const char *string ) { cJSON_Delete( cJSON_DetachItemFromObject( object, string ) ); } 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
void cJSON_DeleteItemFromObject( cJSON *object, const char *string )
167,283
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DataReductionProxySettings::~DataReductionProxySettings() { spdy_proxy_auth_enabled_.Destroy(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
DataReductionProxySettings::~DataReductionProxySettings() {
172,559
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int myrecvfrom6(int sockfd, void *buf, size_t *buflen, int flags, struct in6_addr *addr, uint32_t *ifindex) { struct sockaddr_in6 sin6; unsigned char cbuf[CMSG_SPACE(sizeof(struct in6_pktinfo))]; struct iovec iovec; struct msghdr msghdr; struct cmsghdr *cmsghdr; ssize_t len; iovec.iov_len = *buflen; iovec.iov_base = buf; memset(&msghdr, 0, sizeof(msghdr)); msghdr.msg_name = &sin6; msghdr.msg_namelen = sizeof(sin6); msghdr.msg_iov = &iovec; msghdr.msg_iovlen = 1; msghdr.msg_control = cbuf; msghdr.msg_controllen = sizeof(cbuf); len = recvmsg(sockfd, &msghdr, flags); if (len == -1) return -errno; *buflen = len; /* Set ifindex to scope_id now. But since scope_id gets not * set by kernel for linklocal addresses, use pktinfo to obtain that * value right after. */ *ifindex = sin6.sin6_scope_id; for (cmsghdr = CMSG_FIRSTHDR(&msghdr); cmsghdr; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) { if (cmsghdr->cmsg_level == IPPROTO_IPV6 && cmsghdr->cmsg_type == IPV6_PKTINFO && cmsghdr->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) { struct in6_pktinfo *pktinfo; pktinfo = (struct in6_pktinfo *) CMSG_DATA(cmsghdr); *ifindex = pktinfo->ipi6_ifindex; } } *addr = sin6.sin6_addr; return 0; } Commit Message: libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <[email protected]> Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]> CWE ID: CWE-284
static int myrecvfrom6(int sockfd, void *buf, size_t *buflen, int flags, struct in6_addr *addr, uint32_t *ifindex, int *hoplimit) { struct sockaddr_in6 sin6; unsigned char cbuf[2 * CMSG_SPACE(sizeof(struct in6_pktinfo))]; struct iovec iovec; struct msghdr msghdr; struct cmsghdr *cmsghdr; ssize_t len; iovec.iov_len = *buflen; iovec.iov_base = buf; memset(&msghdr, 0, sizeof(msghdr)); msghdr.msg_name = &sin6; msghdr.msg_namelen = sizeof(sin6); msghdr.msg_iov = &iovec; msghdr.msg_iovlen = 1; msghdr.msg_control = cbuf; msghdr.msg_controllen = sizeof(cbuf); len = recvmsg(sockfd, &msghdr, flags); if (len == -1) return -errno; *buflen = len; /* Set ifindex to scope_id now. But since scope_id gets not * set by kernel for linklocal addresses, use pktinfo to obtain that * value right after. */ *ifindex = sin6.sin6_scope_id; for (cmsghdr = CMSG_FIRSTHDR(&msghdr); cmsghdr; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) { if (cmsghdr->cmsg_level != IPPROTO_IPV6) continue; switch(cmsghdr->cmsg_type) { case IPV6_PKTINFO: if (cmsghdr->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) { struct in6_pktinfo *pktinfo; pktinfo = (struct in6_pktinfo *) CMSG_DATA(cmsghdr); *ifindex = pktinfo->ipi6_ifindex; } break; case IPV6_HOPLIMIT: if (cmsghdr->cmsg_len == CMSG_LEN(sizeof(int))) { int *val; val = (int *) CMSG_DATA(cmsghdr); *hoplimit = *val; } break; } } *addr = sin6.sin6_addr; return 0; }
167,348
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int fpga_reset(void) { if (!check_boco2()) { /* we do not have BOCO2, this is not really used */ return 0; } printf("PCIe reset through GPIO7: "); /* apply PCIe reset via GPIO */ kw_gpio_set_valid(KM_PEX_RST_GPIO_PIN, 1); kw_gpio_direction_output(KM_PEX_RST_GPIO_PIN, 1); kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 0); udelay(1000*10); kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 1); printf(" done\n"); return 0; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
int fpga_reset(void) { /* no dedicated reset pin for FPGA */ return 0; }
169,626
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IndexedDBDispatcher::~IndexedDBDispatcher() { g_idb_dispatcher_tls.Pointer()->Set(NULL); } Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created. This could happen if there are IDB objects that survive the call to didStopWorkerRunLoop. BUG=121734 TEST= Review URL: http://codereview.chromium.org/9999035 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
IndexedDBDispatcher::~IndexedDBDispatcher() { g_idb_dispatcher_tls.Pointer()->Set(HAS_BEEN_DELETED); }
171,040
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int raw_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; __be32 daddr; __be32 saddr; u8 tos; int err; err = -EMSGSIZE; if (len > 0xFFFF) goto out; /* * Check the flags. */ err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */ goto out; /* compatibility */ /* * Get and verify the address. */ if (msg->msg_namelen) { struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name; err = -EINVAL; if (msg->msg_namelen < sizeof(*usin)) goto out; if (usin->sin_family != AF_INET) { static int complained; if (!complained++) printk(KERN_INFO "%s forgot to set AF_INET in " "raw sendmsg. Fix it!\n", current->comm); err = -EAFNOSUPPORT; if (usin->sin_family) goto out; } daddr = usin->sin_addr.s_addr; /* ANK: I did not forget to get protocol from port field. * I just do not know, who uses this weirdness. * IP_HDRINCL is much more convenient. */ } else { err = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; } ipc.addr = inet->inet_saddr; ipc.opt = NULL; ipc.tx_flags = 0; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(sock_net(sk), msg, &ipc); if (err) goto out; if (ipc.opt) free = 1; } saddr = ipc.addr; ipc.addr = daddr; if (!ipc.opt) ipc.opt = inet->opt; if (ipc.opt) { err = -EINVAL; /* Linux does not mangle headers on raw sockets, * so that IP options + IP_HDRINCL is non-sense. */ if (inet->hdrincl) goto done; if (ipc.opt->srr) { if (!daddr) goto done; daddr = ipc.opt->faddr; } } tos = RT_CONN_FLAGS(sk); if (msg->msg_flags & MSG_DONTROUTE) tos |= RTO_ONLINK; if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; } { struct flowi4 fl4; flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, FLOWI_FLAG_CAN_SLEEP, daddr, saddr, 0, 0); if (!inet->hdrincl) { err = raw_probe_proto_opt(&fl4, msg); if (err) goto done; } security_sk_classify_flow(sk, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto done; } } err = -EACCES; if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST)) goto done; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: if (inet->hdrincl) err = raw_send_hdrinc(sk, msg->msg_iov, len, &rt, msg->msg_flags); else { if (!ipc.addr) ipc.addr = rt->rt_dst; lock_sock(sk); err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, len, 0, &ipc, &rt, msg->msg_flags); if (err) ip_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) { err = ip_push_pending_frames(sk); if (err == -ENOBUFS && !inet->recverr) err = 0; } release_sock(sk); } done: if (free) kfree(ipc.opt); ip_rt_put(rt); out: if (err < 0) return err; return len; do_confirm: dst_confirm(&rt->dst); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static int raw_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; __be32 daddr; __be32 saddr; u8 tos; int err; struct ip_options_data opt_copy; err = -EMSGSIZE; if (len > 0xFFFF) goto out; /* * Check the flags. */ err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */ goto out; /* compatibility */ /* * Get and verify the address. */ if (msg->msg_namelen) { struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name; err = -EINVAL; if (msg->msg_namelen < sizeof(*usin)) goto out; if (usin->sin_family != AF_INET) { static int complained; if (!complained++) printk(KERN_INFO "%s forgot to set AF_INET in " "raw sendmsg. Fix it!\n", current->comm); err = -EAFNOSUPPORT; if (usin->sin_family) goto out; } daddr = usin->sin_addr.s_addr; /* ANK: I did not forget to get protocol from port field. * I just do not know, who uses this weirdness. * IP_HDRINCL is much more convenient. */ } else { err = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; } ipc.addr = inet->inet_saddr; ipc.opt = NULL; ipc.tx_flags = 0; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(sock_net(sk), msg, &ipc); if (err) goto out; if (ipc.opt) free = 1; } saddr = ipc.addr; ipc.addr = daddr; if (!ipc.opt) { struct ip_options_rcu *inet_opt; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt) { memcpy(&opt_copy, inet_opt, sizeof(*inet_opt) + inet_opt->opt.optlen); ipc.opt = &opt_copy.opt; } rcu_read_unlock(); } if (ipc.opt) { err = -EINVAL; /* Linux does not mangle headers on raw sockets, * so that IP options + IP_HDRINCL is non-sense. */ if (inet->hdrincl) goto done; if (ipc.opt->opt.srr) { if (!daddr) goto done; daddr = ipc.opt->opt.faddr; } } tos = RT_CONN_FLAGS(sk); if (msg->msg_flags & MSG_DONTROUTE) tos |= RTO_ONLINK; if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; } { struct flowi4 fl4; flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, FLOWI_FLAG_CAN_SLEEP, daddr, saddr, 0, 0); if (!inet->hdrincl) { err = raw_probe_proto_opt(&fl4, msg); if (err) goto done; } security_sk_classify_flow(sk, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto done; } } err = -EACCES; if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST)) goto done; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: if (inet->hdrincl) err = raw_send_hdrinc(sk, msg->msg_iov, len, &rt, msg->msg_flags); else { if (!ipc.addr) ipc.addr = rt->rt_dst; lock_sock(sk); err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, len, 0, &ipc, &rt, msg->msg_flags); if (err) ip_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) { err = ip_push_pending_frames(sk); if (err == -ENOBUFS && !inet->recverr) err = 0; } release_sock(sk); } done: if (free) kfree(ipc.opt); ip_rt_put(rt); out: if (err < 0) return err; return len; do_confirm: dst_confirm(&rt->dst); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; }
165,568
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip, impeg2d_video_decode_op_t *ps_op) { UWORD32 u4_bits_read; dec_state_t *ps_dec; UWORD32 u4_size = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; ps_dec = (dec_state_t *)pv_dec; ps_op->s_ivd_video_decode_op_t.u4_error_code = 0; if (u4_size > MAX_BITSTREAM_BUFFER_SIZE) { u4_size = MAX_BITSTREAM_BUFFER_SIZE; } memcpy(ps_dec->pu1_input_buffer, ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer, u4_size); impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), ps_dec->pu1_input_buffer, u4_size); { { IMPEG2D_ERROR_CODES_T e_error; e_error = impeg2d_process_video_header(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) { ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; } if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0) ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; if (IMPEG2D_UNSUPPORTED_DIMENSIONS == e_error) { ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0; ps_dec->u2_header_done = 0; ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_reinit_max_height; ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_reinit_max_width; } impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE); return; } } ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size; ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size; ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME; ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS; u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) { ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; } ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0; /* MOD */ ps_dec->u2_header_done = 1; } } Commit Message: Adding check for min_width and min_height Add check for min_wd and min_ht. Stride is updated if header decode is done. Bug: 74078669 Change-Id: Ided95395e1138335dbb4b05131a8551f6f7bbfcd (cherry picked from commit 84eba4863dd50083951db83ea3cc81e015bf51da) CWE ID: CWE-787
void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip, impeg2d_video_decode_op_t *ps_op) { UWORD32 u4_bits_read; dec_state_t *ps_dec; UWORD32 u4_size = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; ps_dec = (dec_state_t *)pv_dec; ps_op->s_ivd_video_decode_op_t.u4_error_code = 0; if (u4_size > MAX_BITSTREAM_BUFFER_SIZE) { u4_size = MAX_BITSTREAM_BUFFER_SIZE; } memcpy(ps_dec->pu1_input_buffer, ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer, u4_size); impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), ps_dec->pu1_input_buffer, u4_size); { { IMPEG2D_ERROR_CODES_T e_error; e_error = impeg2d_process_video_header(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) { ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; } if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0) ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; if (IMPEG2D_UNSUPPORTED_DIMENSIONS == e_error) { ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0; ps_dec->u2_header_done = 0; ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_reinit_max_height; ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_reinit_max_width; } impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE); return; } } ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size; ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size; ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME; ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS; u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) { ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; } ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0; /* Set the stride */ if (0 == ps_dec->u4_frm_buf_stride) { ps_dec->u4_frm_buf_stride = ps_dec->u2_horizontal_size; } /* MOD */ ps_dec->u2_header_done = 1; } }
174,086
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SMBC_server_internal(TALLOC_CTX *ctx, SMBCCTX *context, bool connect_if_not_found, const char *server, uint16_t port, const char *share, char **pp_workgroup, char **pp_username, char **pp_password, bool *in_cache) { SMBCSRV *srv=NULL; char *workgroup = NULL; struct cli_state *c = NULL; const char *server_n = server; int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0); uint32_t fs_attrs = 0; const char *username_used; NTSTATUS status; char *newserver, *newshare; int flags = 0; struct smbXcli_tcon *tcon = NULL; ZERO_STRUCT(c); *in_cache = false; if (server[0] == 0) { errno = EPERM; return NULL; } /* Look for a cached connection */ srv = SMBC_find_server(ctx, context, server, share, pp_workgroup, pp_username, pp_password); /* * If we found a connection and we're only allowed one share per * server... */ if (srv && share != NULL && *share != '\0' && smbc_getOptionOneSharePerServer(context)) { /* * ... then if there's no current connection to the share, * connect to it. SMBC_find_server(), or rather the function * pointed to by context->get_cached_srv_fn which * was called by SMBC_find_server(), will have issued a tree * disconnect if the requested share is not the same as the * one that was already connected. */ /* * Use srv->cli->desthost and srv->cli->share instead of * server and share below to connect to the actual share, * i.e., a normal share or a referred share from * 'msdfs proxy' share. */ if (!cli_state_has_tcon(srv->cli)) { /* Ensure we have accurate auth info */ SMBC_call_auth_fn(ctx, context, smbXcli_conn_remote_name(srv->cli->conn), srv->cli->share, pp_workgroup, pp_username, pp_password); if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; cli_shutdown(srv->cli); srv->cli = NULL; smbc_getFunctionRemoveCachedServer(context)(context, srv); return NULL; } /* * We don't need to renegotiate encryption * here as the encryption context is not per * tid. */ status = cli_tree_connect(srv->cli, srv->cli->share, "?????", *pp_password, strlen(*pp_password)+1); if (!NT_STATUS_IS_OK(status)) { errno = map_errno_from_nt_status(status); cli_shutdown(srv->cli); srv->cli = NULL; smbc_getFunctionRemoveCachedServer(context)(context, srv); srv = NULL; } /* Determine if this share supports case sensitivity */ if (is_ipc) { DEBUG(4, ("IPC$ so ignore case sensitivity\n")); status = NT_STATUS_OK; } else { status = cli_get_fs_attr_info(c, &fs_attrs); } if (!NT_STATUS_IS_OK(status)) { DEBUG(4, ("Could not retrieve " "case sensitivity flag: %s.\n", nt_errstr(status))); /* * We can't determine the case sensitivity of * the share. We have no choice but to use the * user-specified case sensitivity setting. */ if (smbc_getOptionCaseSensitive(context)) { cli_set_case_sensitive(c, True); } else { cli_set_case_sensitive(c, False); } } else if (!is_ipc) { DEBUG(4, ("Case sensitive: %s\n", (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? "True" : "False"))); cli_set_case_sensitive( c, (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? True : False)); } /* * Regenerate the dev value since it's based on both * server and share */ if (srv) { const char *remote_name = smbXcli_conn_remote_name(srv->cli->conn); srv->dev = (dev_t)(str_checksum(remote_name) ^ str_checksum(srv->cli->share)); } } } /* If we have a connection... */ if (srv) { /* ... then we're done here. Give 'em what they came for. */ *in_cache = true; goto done; } /* If we're not asked to connect when a connection doesn't exist... */ if (! connect_if_not_found) { /* ... then we're done here. */ return NULL; } if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; return NULL; } DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server)); DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server)); status = NT_STATUS_UNSUCCESSFUL; if (smbc_getOptionUseKerberos(context)) { flags |= CLI_FULL_CONNECTION_USE_KERBEROS; } if (smbc_getOptionFallbackAfterKerberos(context)) { flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS; } if (smbc_getOptionUseCCache(context)) { flags |= CLI_FULL_CONNECTION_USE_CCACHE; } if (smbc_getOptionUseNTHash(context)) { flags |= CLI_FULL_CONNECTION_USE_NT_HASH; flags |= CLI_FULL_CONNECTION_USE_NT_HASH; } if (port == 0) { if (share == NULL || *share == '\0' || is_ipc) { /* } */ status = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20, smbc_getNetbiosName(context), SMB_SIGNING_DEFAULT, flags, &c); } } Commit Message: CWE ID: CWE-20
SMBC_server_internal(TALLOC_CTX *ctx, SMBCCTX *context, bool connect_if_not_found, const char *server, uint16_t port, const char *share, char **pp_workgroup, char **pp_username, char **pp_password, bool *in_cache) { SMBCSRV *srv=NULL; char *workgroup = NULL; struct cli_state *c = NULL; const char *server_n = server; int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0); uint32_t fs_attrs = 0; const char *username_used; NTSTATUS status; char *newserver, *newshare; int flags = 0; struct smbXcli_tcon *tcon = NULL; int signing_state = SMB_SIGNING_DEFAULT; ZERO_STRUCT(c); *in_cache = false; if (server[0] == 0) { errno = EPERM; return NULL; } /* Look for a cached connection */ srv = SMBC_find_server(ctx, context, server, share, pp_workgroup, pp_username, pp_password); /* * If we found a connection and we're only allowed one share per * server... */ if (srv && share != NULL && *share != '\0' && smbc_getOptionOneSharePerServer(context)) { /* * ... then if there's no current connection to the share, * connect to it. SMBC_find_server(), or rather the function * pointed to by context->get_cached_srv_fn which * was called by SMBC_find_server(), will have issued a tree * disconnect if the requested share is not the same as the * one that was already connected. */ /* * Use srv->cli->desthost and srv->cli->share instead of * server and share below to connect to the actual share, * i.e., a normal share or a referred share from * 'msdfs proxy' share. */ if (!cli_state_has_tcon(srv->cli)) { /* Ensure we have accurate auth info */ SMBC_call_auth_fn(ctx, context, smbXcli_conn_remote_name(srv->cli->conn), srv->cli->share, pp_workgroup, pp_username, pp_password); if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; cli_shutdown(srv->cli); srv->cli = NULL; smbc_getFunctionRemoveCachedServer(context)(context, srv); return NULL; } /* * We don't need to renegotiate encryption * here as the encryption context is not per * tid. */ status = cli_tree_connect(srv->cli, srv->cli->share, "?????", *pp_password, strlen(*pp_password)+1); if (!NT_STATUS_IS_OK(status)) { errno = map_errno_from_nt_status(status); cli_shutdown(srv->cli); srv->cli = NULL; smbc_getFunctionRemoveCachedServer(context)(context, srv); srv = NULL; } /* Determine if this share supports case sensitivity */ if (is_ipc) { DEBUG(4, ("IPC$ so ignore case sensitivity\n")); status = NT_STATUS_OK; } else { status = cli_get_fs_attr_info(c, &fs_attrs); } if (!NT_STATUS_IS_OK(status)) { DEBUG(4, ("Could not retrieve " "case sensitivity flag: %s.\n", nt_errstr(status))); /* * We can't determine the case sensitivity of * the share. We have no choice but to use the * user-specified case sensitivity setting. */ if (smbc_getOptionCaseSensitive(context)) { cli_set_case_sensitive(c, True); } else { cli_set_case_sensitive(c, False); } } else if (!is_ipc) { DEBUG(4, ("Case sensitive: %s\n", (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? "True" : "False"))); cli_set_case_sensitive( c, (fs_attrs & FILE_CASE_SENSITIVE_SEARCH ? True : False)); } /* * Regenerate the dev value since it's based on both * server and share */ if (srv) { const char *remote_name = smbXcli_conn_remote_name(srv->cli->conn); srv->dev = (dev_t)(str_checksum(remote_name) ^ str_checksum(srv->cli->share)); } } } /* If we have a connection... */ if (srv) { /* ... then we're done here. Give 'em what they came for. */ *in_cache = true; goto done; } /* If we're not asked to connect when a connection doesn't exist... */ if (! connect_if_not_found) { /* ... then we're done here. */ return NULL; } if (!*pp_workgroup || !*pp_username || !*pp_password) { errno = ENOMEM; return NULL; } DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server)); DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server)); status = NT_STATUS_UNSUCCESSFUL; if (smbc_getOptionUseKerberos(context)) { flags |= CLI_FULL_CONNECTION_USE_KERBEROS; } if (smbc_getOptionFallbackAfterKerberos(context)) { flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS; } if (smbc_getOptionUseCCache(context)) { flags |= CLI_FULL_CONNECTION_USE_CCACHE; } if (smbc_getOptionUseNTHash(context)) { flags |= CLI_FULL_CONNECTION_USE_NT_HASH; flags |= CLI_FULL_CONNECTION_USE_NT_HASH; } if (context->internal->smb_encryption_level != SMBC_ENCRYPTLEVEL_NONE) { signing_state = SMB_SIGNING_REQUIRED; } if (port == 0) { if (share == NULL || *share == '\0' || is_ipc) { /* } */ status = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20, smbc_getNetbiosName(context), signing_state, flags, &c); } }
164,677
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void IBusBusGlobalEngineChangedCallback( IBusBus* bus, const gchar* engine_name, gpointer user_data) { DCHECK(engine_name); DLOG(INFO) << "Global engine is changed to " << engine_name; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateUI(engine_name); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void IBusBusGlobalEngineChangedCallback( void IBusBusGlobalEngineChanged(IBusBus* bus, const gchar* engine_name) { DCHECK(engine_name); VLOG(1) << "Global engine is changed to " << engine_name; UpdateUI(engine_name); }
170,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_call_errors_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; uint16_t val_h, val_l; ptr++; /* skip "Reserved" */ val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "CRCErr=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "FrameErr=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "HardOver=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "BufOver=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "Timeout=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "AlignErr=%u ", (val_h<<16) + val_l)); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_call_errors_print(netdissect_options *ndo, const u_char *dat) l2tp_call_errors_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; uint16_t val_h, val_l; if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ptr++; /* skip "Reserved" */ length -= 2; if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "CRCErr=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "FrameErr=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "HardOver=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "BufOver=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "Timeout=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "AlignErr=%u ", (val_h<<16) + val_l)); }
167,893
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void* sspi_SecureHandleGetUpperPointer(SecHandle* handle) { void* pointer; if (!handle) return NULL; pointer = (void*) ~((size_t) handle->dwUpper); return pointer; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
void* sspi_SecureHandleGetUpperPointer(SecHandle* handle) { void* pointer; if (!handle || !SecIsValidHandle(handle)) return NULL; pointer = (void*) ~((size_t) handle->dwUpper); return pointer; }
167,605
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else if (n->mac_table.in_use) { uint8_t *buf = g_malloc0(n->mac_table.in_use); qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); g_free(buf); n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } } if (version_id >= 6) qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3); if (version_id >= 7) { if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) { error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } } if (version_id >= 9) { n->mac_table.multi_overflow = qemu_get_byte(f); n->mac_table.uni_overflow = qemu_get_byte(f); } if (version_id >= 10) { n->alluni = qemu_get_byte(f); n->nomulti = qemu_get_byte(f); n->nouni = qemu_get_byte(f); n->nobcast = qemu_get_byte(f); } if (version_id >= 11) { if (qemu_get_byte(f) && !peer_has_ufo(n)) { error_report("virtio-net: saved image requires TUN_F_UFO support"); return -1; } } if (n->max_queues > 1) { if (n->max_queues != qemu_get_be16(f)) { error_report("virtio-net: different max_queues "); return -1; } n->curr_queues = qemu_get_be16(f); for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } n->curr_guest_offloads = virtio_net_supported_guest_offloads(n); } if (peer_has_vnet_hdr(n)) { virtio_net_apply_guest_offloads(n); } virtio_net_set_queues(n); /* Find the first multicast entry in the saved MAC filter */ for (i = 0; i < n->mac_table.in_use; i++) { if (n->mac_table.macs[i * ETH_ALEN] & 1) { break; } } n->mac_table.first_multi = i; /* nc.link_down can't be migrated, so infer link_down according * to link status bit in n->status */ link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0; for (i = 0; i < n->max_queues; i++) { qemu_get_subqueue(n->nic, i)->link_down = link_down; } return 0; } Commit Message: CWE ID: CWE-119
static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else if (n->mac_table.in_use) { uint8_t *buf = g_malloc0(n->mac_table.in_use); qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); g_free(buf); n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } } if (version_id >= 6) qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3); if (version_id >= 7) { if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) { error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } } if (version_id >= 9) { n->mac_table.multi_overflow = qemu_get_byte(f); n->mac_table.uni_overflow = qemu_get_byte(f); } if (version_id >= 10) { n->alluni = qemu_get_byte(f); n->nomulti = qemu_get_byte(f); n->nouni = qemu_get_byte(f); n->nobcast = qemu_get_byte(f); } if (version_id >= 11) { if (qemu_get_byte(f) && !peer_has_ufo(n)) { error_report("virtio-net: saved image requires TUN_F_UFO support"); return -1; } } if (n->max_queues > 1) { if (n->max_queues != qemu_get_be16(f)) { error_report("virtio-net: different max_queues "); return -1; } n->curr_queues = qemu_get_be16(f); if (n->curr_queues > n->max_queues) { error_report("virtio-net: curr_queues %x > max_queues %x", n->curr_queues, n->max_queues); return -1; } for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } n->curr_guest_offloads = virtio_net_supported_guest_offloads(n); } if (peer_has_vnet_hdr(n)) { virtio_net_apply_guest_offloads(n); } virtio_net_set_queues(n); /* Find the first multicast entry in the saved MAC filter */ for (i = 0; i < n->mac_table.in_use; i++) { if (n->mac_table.macs[i * ETH_ALEN] & 1) { break; } } n->mac_table.first_multi = i; /* nc.link_down can't be migrated, so infer link_down according * to link status bit in n->status */ link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0; for (i = 0; i < n->max_queues; i++) { qemu_get_subqueue(n->nic, i)->link_down = link_down; } return 0; }
165,362
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ int j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: memcpy(file->name, d, len); file->namelen = len; break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ size_t j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: file->namelen = MIN(sizeof file->name, len); memcpy(file->name, d, file->namelen); break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; }
169,075
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserView::TabDetachedAt(TabContents* contents, int index) { if (index == browser_->active_index()) { contents_container_->SetWebContents(NULL); infobar_container_->ChangeTabContents(NULL); UpdateDevToolsForContents(NULL); } } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserView::TabDetachedAt(TabContents* contents, int index) { void BrowserView::TabDetachedAt(WebContents* contents, int index) { if (index == browser_->active_index()) { contents_container_->SetWebContents(NULL); infobar_container_->ChangeTabContents(NULL); UpdateDevToolsForContents(NULL); } }
171,522
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StoreNewGroup() { PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_StoreNewGroup, base::Unretained(this))); group_ = new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT, 1, kDefaultEntrySize)); mock_quota_manager_proxy_->mock_manager_->async_ = true; storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); } 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 StoreNewGroup() { PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_StoreNewGroup, base::Unretained(this))); group_ = new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::MASTER, 1, kDefaultEntrySize, /*padding_size=*/0)); mock_quota_manager_proxy_->mock_manager_->async_ = true; storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); }
172,991
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } /* * we assume that no multi-byte character can take more than 5 bytes. * we assume that no multi-byte character can take more than 5 bytes. * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = strnlen(str, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); *bytes_consumed = 1; return INVALID_CODEPOINT; } Commit Message: CWE ID: CWE-200
_PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, size_t len, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } /* * we assume that no multi-byte character can take more than 5 bytes. * we assume that no multi-byte character can take more than 5 bytes. * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = MIN(len, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); *bytes_consumed = 1; return INVALID_CODEPOINT; }
164,670
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_inval_entry_out outarg; int err = -ENOMEM; char *buf; struct qstr name; buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL); if (!buf) goto err; err = -EINVAL; if (size < sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; err = -ENAMETOOLONG; if (outarg.namelen > FUSE_NAME_MAX) goto err; name.name = buf; name.len = outarg.namelen; err = fuse_copy_one(cs, buf, outarg.namelen + 1); if (err) goto err; fuse_copy_finish(cs); buf[outarg.namelen] = 0; name.hash = full_name_hash(name.name, name.len); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name); up_read(&fc->killsb); kfree(buf); return err; err: kfree(buf); fuse_copy_finish(cs); return err; } Commit Message: fuse: check size of FUSE_NOTIFY_INVAL_ENTRY message FUSE_NOTIFY_INVAL_ENTRY didn't check the length of the write so the message processing could overrun and result in a "kernel BUG at fs/fuse/dev.c:629!" Reported-by: Han-Wen Nienhuys <[email protected]> Signed-off-by: Miklos Szeredi <[email protected]> CC: [email protected] CWE ID: CWE-119
static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_inval_entry_out outarg; int err = -ENOMEM; char *buf; struct qstr name; buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL); if (!buf) goto err; err = -EINVAL; if (size < sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; err = -ENAMETOOLONG; if (outarg.namelen > FUSE_NAME_MAX) goto err; err = -EINVAL; if (size != sizeof(outarg) + outarg.namelen + 1) goto err; name.name = buf; name.len = outarg.namelen; err = fuse_copy_one(cs, buf, outarg.namelen + 1); if (err) goto err; fuse_copy_finish(cs); buf[outarg.namelen] = 0; name.hash = full_name_hash(name.name, name.len); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name); up_read(&fc->killsb); kfree(buf); return err; err: kfree(buf); fuse_copy_finish(cs); return err; }
165,747
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int UDPSocketWin::DoBind(const IPEndPoint& address) { SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; int rv = bind(socket_, storage.addr, storage.addr_len); if (rv == 0) return OK; int last_error = WSAGetLastError(); UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromWinOS", last_error); if (last_error == WSAEACCES || last_error == WSAEINVAL) return ERR_ADDRESS_IN_USE; return MapSystemError(last_error); } 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::DoBind(const IPEndPoint& address) { SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; int rv = bind(socket_, storage.addr, storage.addr_len); if (rv == 0) return OK; int last_error = WSAGetLastError(); UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromWinOS", last_error); // * WSAEACCES: If a port is already bound to a socket, WSAEACCES may be // returned instead of WSAEADDRINUSE, depending on whether the socket // option SO_REUSEADDR or SO_EXCLUSIVEADDRUSE is set and whether the // conflicting socket is owned by a different user account. See the MSDN // page "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" for the gory details. if (last_error == WSAEACCES || last_error == WSAEADDRNOTAVAIL) return ERR_ADDRESS_IN_USE; return MapSystemError(last_error); }
171,317
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: write_header( FT_Error error_code ) { FT_Face face; const char* basename; const char* format; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) Fatal( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%s')", basename ); break; default: sprintf( status.header_buffer, "File `%s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = (const char *)status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); format = "at %g points, first glyph index = %d"; snprintf( status.header_buffer, 256, format, status.ptsize/64., status.Num ); if ( FT_HAS_GLYPH_NAMES( face ) ) { char* p; int format_len, gindex, size; size = strlen( status.header_buffer ); p = status.header_buffer + size; size = 256 - size; format = ", name = "; format_len = strlen( format ); if ( size >= format_len + 2 ) { gindex = status.Num; strcpy( p, format ); if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) ) *p = '\0'; } } status.header = (const char *)status.header_buffer; grWriteCellString( display->bitmap, 0, HEADER_HEIGHT, status.header_buffer, display->fore_color ); grRefreshSurface( display->surface ); } Commit Message: CWE ID: CWE-119
write_header( FT_Error error_code ) { FT_Face face; const char* basename; const char* format; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) Fatal( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%.50s %.50s (file `%.100s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%.100s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%.100s')", basename ); break; default: sprintf( status.header_buffer, "File `%.100s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = (const char *)status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); format = "at %g points, first glyph index = %d"; snprintf( status.header_buffer, 256, format, status.ptsize/64., status.Num ); if ( FT_HAS_GLYPH_NAMES( face ) ) { char* p; int format_len, gindex, size; size = strlen( status.header_buffer ); p = status.header_buffer + size; size = 256 - size; format = ", name = "; format_len = strlen( format ); if ( size >= format_len + 2 ) { gindex = status.Num; strcpy( p, format ); if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) ) *p = '\0'; } } status.header = (const char *)status.header_buffer; grWriteCellString( display->bitmap, 0, HEADER_HEIGHT, status.header_buffer, display->fore_color ); grRefreshSurface( display->surface ); }
164,998
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h) { int i; VncDisplay *vd = ds->opaque; struct VncSurface *s = &vd->guest; h += y; two 16-pixel blocks but we only mark the first as dirty */ w += (x % 16); x -= (x % 16); w += (x % 16); x -= (x % 16); x = MIN(x, s->ds->width); y = MIN(y, s->ds->height); w = MIN(x + w, s->ds->width) - x; h = MIN(h, s->ds->height); for (; y < h; y++) for (i = 0; i < w; i += 16) void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h, int32_t encoding) { vnc_write_u16(vs, x); vnc_write_u16(vs, y); vnc_write_u16(vs, w); vnc_write_u16(vs, h); vnc_write_s32(vs, encoding); } void buffer_reserve(Buffer *buffer, size_t len) { if ((buffer->capacity - buffer->offset) < len) { buffer->capacity += (len + 1024); buffer->buffer = g_realloc(buffer->buffer, buffer->capacity); if (buffer->buffer == NULL) { fprintf(stderr, "vnc: out of memory\n"); exit(1); } } } int buffer_empty(Buffer *buffer) { return buffer->offset == 0; } uint8_t *buffer_end(Buffer *buffer) { return buffer->buffer + buffer->offset; } void buffer_reset(Buffer *buffer) { buffer->offset = 0; } void buffer_free(Buffer *buffer) { g_free(buffer->buffer); buffer->offset = 0; buffer->capacity = 0; buffer->buffer = NULL; } void buffer_append(Buffer *buffer, const void *data, size_t len) { memcpy(buffer->buffer + buffer->offset, data, len); buffer->offset += len; } static void vnc_desktop_resize(VncState *vs) { DisplayState *ds = vs->ds; if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) { return; } if (vs->client_width == ds_get_width(ds) && vs->client_height == ds_get_height(ds)) { return; } vs->client_width = ds_get_width(ds); vs->client_height = ds_get_height(ds); vnc_lock_output(vs); vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE); vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); /* number of rects */ vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height, VNC_ENCODING_DESKTOPRESIZE); vnc_unlock_output(vs); vnc_flush(vs); } static void vnc_abort_display_jobs(VncDisplay *vd) { VncState *vs; QTAILQ_FOREACH(vs, &vd->clients, next) { vnc_lock_output(vs); vs->abort = true; vnc_unlock_output(vs); } QTAILQ_FOREACH(vs, &vd->clients, next) { vnc_jobs_join(vs); } QTAILQ_FOREACH(vs, &vd->clients, next) { vnc_lock_output(vs); vs->abort = false; vnc_unlock_output(vs); } } } Commit Message: CWE ID: CWE-125
static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h) { int i; VncDisplay *vd = ds->opaque; struct VncSurface *s = &vd->guest; int width = ds_get_width(ds); int height = ds_get_height(ds); h += y; two 16-pixel blocks but we only mark the first as dirty */ w += (x % 16); x -= (x % 16); w += (x % 16); x -= (x % 16); x = MIN(x, width); y = MIN(y, height); w = MIN(x + w, width) - x; h = MIN(h, height); for (; y < h; y++) for (i = 0; i < w; i += 16) void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h, int32_t encoding) { vnc_write_u16(vs, x); vnc_write_u16(vs, y); vnc_write_u16(vs, w); vnc_write_u16(vs, h); vnc_write_s32(vs, encoding); } void buffer_reserve(Buffer *buffer, size_t len) { if ((buffer->capacity - buffer->offset) < len) { buffer->capacity += (len + 1024); buffer->buffer = g_realloc(buffer->buffer, buffer->capacity); if (buffer->buffer == NULL) { fprintf(stderr, "vnc: out of memory\n"); exit(1); } } } int buffer_empty(Buffer *buffer) { return buffer->offset == 0; } uint8_t *buffer_end(Buffer *buffer) { return buffer->buffer + buffer->offset; } void buffer_reset(Buffer *buffer) { buffer->offset = 0; } void buffer_free(Buffer *buffer) { g_free(buffer->buffer); buffer->offset = 0; buffer->capacity = 0; buffer->buffer = NULL; } void buffer_append(Buffer *buffer, const void *data, size_t len) { memcpy(buffer->buffer + buffer->offset, data, len); buffer->offset += len; } static void vnc_desktop_resize(VncState *vs) { DisplayState *ds = vs->ds; if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) { return; } if (vs->client_width == ds_get_width(ds) && vs->client_height == ds_get_height(ds)) { return; } vs->client_width = ds_get_width(ds); vs->client_height = ds_get_height(ds); vnc_lock_output(vs); vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE); vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); /* number of rects */ vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height, VNC_ENCODING_DESKTOPRESIZE); vnc_unlock_output(vs); vnc_flush(vs); } static void vnc_abort_display_jobs(VncDisplay *vd) { VncState *vs; QTAILQ_FOREACH(vs, &vd->clients, next) { vnc_lock_output(vs); vs->abort = true; vnc_unlock_output(vs); } QTAILQ_FOREACH(vs, &vd->clients, next) { vnc_jobs_join(vs); } QTAILQ_FOREACH(vs, &vd->clients, next) { vnc_lock_output(vs); vs->abort = false; vnc_unlock_output(vs); } } }
165,470
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: QualifyIpPacket(IPHeader *pIpHeader, ULONG len) { tTcpIpPacketParsingResult res; UCHAR ver_len = pIpHeader->v4.ip_verlen; UCHAR ip_version = (ver_len & 0xF0) >> 4; USHORT ipHeaderSize = 0; USHORT fullLength = 0; res.value = 0; if (ip_version == 4) { ipHeaderSize = (ver_len & 0xF) << 2; fullLength = swap_short(pIpHeader->v4.ip_length); DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n", ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength)); res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP; if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort; if (fullLength) {} else { DPrintf(2, ("ip v.%d, iplen %d\n", ip_version, fullLength)); } } else if (ip_version == 6) { UCHAR nextHeader = pIpHeader->v6.ip6_next_header; BOOLEAN bParsingDone = FALSE; ipHeaderSize = sizeof(pIpHeader->v6); res.ipStatus = ppresIPV6; res.ipCheckSum = ppresCSOK; fullLength = swap_short(pIpHeader->v6.ip6_payload_len); fullLength += ipHeaderSize; while (nextHeader != 59) { IPv6ExtHeader *pExt; switch (nextHeader) { case PROTOCOL_TCP: bParsingDone = TRUE; res.xxpStatus = ppresXxpKnown; res.TcpUdp = ppresIsTCP; res.xxpFull = len >= fullLength ? 1 : 0; res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); break; case PROTOCOL_UDP: bParsingDone = TRUE; res.xxpStatus = ppresXxpKnown; res.TcpUdp = ppresIsUDP; res.xxpFull = len >= fullLength ? 1 : 0; res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); break; case 0: case 60: case 43: case 44: case 51: case 50: case 135: if (len >= ((ULONG)ipHeaderSize + 8)) { pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize); nextHeader = pExt->ip6ext_next_header; ipHeaderSize += 8; ipHeaderSize += pExt->ip6ext_hdr_len * 8; } else { DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize)); res.ipStatus = ppresNotIP; bParsingDone = TRUE; } break; default: res.xxpStatus = ppresXxpOther; bParsingDone = TRUE; break; } if (bParsingDone) break; } if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS) { DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n", ip_version, ipHeaderSize, nextHeader, fullLength)); res.ipHeaderSize = ipHeaderSize; } else { DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize)); res.ipStatus = ppresNotIP; } } if (res.ipStatus == ppresIPV4) { res.ipHeaderSize = ipHeaderSize; res.xxpFull = len >= fullLength ? 1 : 0; res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0; switch (pIpHeader->v4.ip_protocol) { case PROTOCOL_TCP: { res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); } break; case PROTOCOL_UDP: { res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); } break; default: res.xxpStatus = ppresXxpOther; break; } } return res; } Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20
QualifyIpPacket(IPHeader *pIpHeader, ULONG len) { tTcpIpPacketParsingResult res; res.value = 0; if (len < 4) { res.ipStatus = ppresNotIP; return res; } UCHAR ver_len = pIpHeader->v4.ip_verlen; UCHAR ip_version = (ver_len & 0xF0) >> 4; USHORT ipHeaderSize = 0; USHORT fullLength = 0; res.value = 0; if (ip_version == 4) { if (len < sizeof(IPv4Header)) { res.ipStatus = ppresNotIP; return res; } ipHeaderSize = (ver_len & 0xF) << 2; fullLength = swap_short(pIpHeader->v4.ip_length); DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n", ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len)); res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP; if (res.ipStatus == ppresNotIP) { return res; } if (ipHeaderSize >= fullLength || len < fullLength) { DPrintf(2, ("[%s] - truncated packet - ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n", ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len)); res.ipCheckSum = ppresIPTooShort; return res; } } else if (ip_version == 6) { UCHAR nextHeader = pIpHeader->v6.ip6_next_header; BOOLEAN bParsingDone = FALSE; ipHeaderSize = sizeof(pIpHeader->v6); res.ipStatus = ppresIPV6; res.ipCheckSum = ppresCSOK; fullLength = swap_short(pIpHeader->v6.ip6_payload_len); fullLength += ipHeaderSize; while (nextHeader != 59) { IPv6ExtHeader *pExt; switch (nextHeader) { case PROTOCOL_TCP: bParsingDone = TRUE; res.xxpStatus = ppresXxpKnown; res.TcpUdp = ppresIsTCP; res.xxpFull = len >= fullLength ? 1 : 0; res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); break; case PROTOCOL_UDP: bParsingDone = TRUE; res.xxpStatus = ppresXxpKnown; res.TcpUdp = ppresIsUDP; res.xxpFull = len >= fullLength ? 1 : 0; res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); break; case 0: case 60: case 43: case 44: case 51: case 50: case 135: if (len >= ((ULONG)ipHeaderSize + 8)) { pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize); nextHeader = pExt->ip6ext_next_header; ipHeaderSize += 8; ipHeaderSize += pExt->ip6ext_hdr_len * 8; } else { DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize)); res.ipStatus = ppresNotIP; bParsingDone = TRUE; } break; default: res.xxpStatus = ppresXxpOther; bParsingDone = TRUE; break; } if (bParsingDone) break; } if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS) { DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n", ip_version, ipHeaderSize, nextHeader, fullLength)); res.ipHeaderSize = ipHeaderSize; } else { DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize)); res.ipStatus = ppresNotIP; } } if (res.ipStatus == ppresIPV4) { res.ipHeaderSize = ipHeaderSize; res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0; switch (pIpHeader->v4.ip_protocol) { case PROTOCOL_TCP: { res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); } break; case PROTOCOL_UDP: { res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); } break; default: res.xxpStatus = ppresXxpOther; break; } } return res; }
168,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PushMessagingServiceImpl::PushMessagingServiceImpl(Profile* profile) : profile_(profile), push_subscription_count_(0), pending_push_subscription_count_(0), notification_manager_(profile), push_messaging_service_observer_(PushMessagingServiceObserver::Create()), weak_factory_(this) { DCHECK(profile); HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this); registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); } Commit Message: Remove some senseless indirection from the Push API code Four files to call one Java function. Let's just call it directly. BUG= Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6 Reviewed-on: https://chromium-review.googlesource.com/749147 Reviewed-by: Anita Woodruff <[email protected]> Commit-Queue: Peter Beverloo <[email protected]> Cr-Commit-Position: refs/heads/master@{#513464} CWE ID: CWE-119
PushMessagingServiceImpl::PushMessagingServiceImpl(Profile* profile) : profile_(profile), push_subscription_count_(0), pending_push_subscription_count_(0), notification_manager_(profile), weak_factory_(this) { DCHECK(profile); HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this); registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); }
172,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PaymentRequest::Init(mojom::PaymentRequestClientPtr client, std::vector<mojom::PaymentMethodDataPtr> method_data, mojom::PaymentDetailsPtr details, mojom::PaymentOptionsPtr options) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); client_ = std::move(client); const GURL last_committed_url = delegate_->GetLastCommittedURL(); if (!OriginSecurityChecker::IsOriginSecure(last_committed_url)) { LOG(ERROR) << "Not in a secure origin"; OnConnectionTerminated(); return; } bool allowed_origin = OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) || OriginSecurityChecker::IsOriginLocalhostOrFile(last_committed_url); if (!allowed_origin) { LOG(ERROR) << "Only localhost, file://, and cryptographic scheme origins " "allowed"; } bool invalid_ssl = OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) && !delegate_->IsSslCertificateValid(); if (invalid_ssl) LOG(ERROR) << "SSL certificate is not valid"; if (!allowed_origin || invalid_ssl) { return; } std::string error; if (!ValidatePaymentDetails(ConvertPaymentDetails(details), &error)) { LOG(ERROR) << error; OnConnectionTerminated(); return; } if (!details->total) { LOG(ERROR) << "Missing total"; OnConnectionTerminated(); return; } spec_ = std::make_unique<PaymentRequestSpec>( std::move(options), std::move(details), std::move(method_data), this, delegate_->GetApplicationLocale()); state_ = std::make_unique<PaymentRequestState>( web_contents_, top_level_origin_, frame_origin_, spec_.get(), this, delegate_->GetApplicationLocale(), delegate_->GetPersonalDataManager(), delegate_.get(), &journey_logger_); journey_logger_.SetRequestedInformation( spec_->request_shipping(), spec_->request_payer_email(), spec_->request_payer_phone(), spec_->request_payer_name()); GURL google_pay_url(kGooglePayMethodName); GURL android_pay_url(kAndroidPayMethodName); auto non_google_it = std::find_if(spec_->url_payment_method_identifiers().begin(), spec_->url_payment_method_identifiers().end(), [google_pay_url, android_pay_url](const GURL& url) { return url != google_pay_url && url != android_pay_url; }); journey_logger_.SetRequestedPaymentMethodTypes( /*requested_basic_card=*/!spec_->supported_card_networks().empty(), /*requested_method_google=*/ base::ContainsValue(spec_->url_payment_method_identifiers(), google_pay_url) || base::ContainsValue(spec_->url_payment_method_identifiers(), android_pay_url), /*requested_method_other=*/non_google_it != spec_->url_payment_method_identifiers().end()); } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189
void PaymentRequest::Init(mojom::PaymentRequestClientPtr client, std::vector<mojom::PaymentMethodDataPtr> method_data, mojom::PaymentDetailsPtr details, mojom::PaymentOptionsPtr options) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (is_initialized_) { log_.Error("Attempted initialization twice"); OnConnectionTerminated(); return; } is_initialized_ = true; client_ = std::move(client); const GURL last_committed_url = delegate_->GetLastCommittedURL(); if (!OriginSecurityChecker::IsOriginSecure(last_committed_url)) { log_.Error("Not in a secure origin"); OnConnectionTerminated(); return; } bool allowed_origin = OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) || OriginSecurityChecker::IsOriginLocalhostOrFile(last_committed_url); if (!allowed_origin) { log_.Error( "Only localhost, file://, and cryptographic scheme origins allowed"); } bool invalid_ssl = OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) && !delegate_->IsSslCertificateValid(); if (invalid_ssl) { log_.Error("SSL certificate is not valid."); } if (!allowed_origin || invalid_ssl) { // Intentionally don't set |spec_| and |state_|, so the UI is never shown. log_.Error( "No UI will be shown. CanMakePayment will always return false. " "Show will be rejected with NotSupportedError."); return; } std::string error; if (!ValidatePaymentDetails(ConvertPaymentDetails(details), &error)) { log_.Error(error); OnConnectionTerminated(); return; } if (!details->total) { log_.Error("Missing total"); OnConnectionTerminated(); return; } spec_ = std::make_unique<PaymentRequestSpec>( std::move(options), std::move(details), std::move(method_data), this, delegate_->GetApplicationLocale()); state_ = std::make_unique<PaymentRequestState>( web_contents_, top_level_origin_, frame_origin_, spec_.get(), this, delegate_->GetApplicationLocale(), delegate_->GetPersonalDataManager(), delegate_.get(), &journey_logger_); journey_logger_.SetRequestedInformation( spec_->request_shipping(), spec_->request_payer_email(), spec_->request_payer_phone(), spec_->request_payer_name()); GURL google_pay_url(kGooglePayMethodName); GURL android_pay_url(kAndroidPayMethodName); auto non_google_it = std::find_if(spec_->url_payment_method_identifiers().begin(), spec_->url_payment_method_identifiers().end(), [google_pay_url, android_pay_url](const GURL& url) { return url != google_pay_url && url != android_pay_url; }); journey_logger_.SetRequestedPaymentMethodTypes( /*requested_basic_card=*/!spec_->supported_card_networks().empty(), /*requested_method_google=*/ base::ContainsValue(spec_->url_payment_method_identifiers(), google_pay_url) || base::ContainsValue(spec_->url_payment_method_identifiers(), android_pay_url), /*requested_method_other=*/non_google_it != spec_->url_payment_method_identifiers().end()); }
173,082
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, copy) { char *oldfile, *newfile, *error; const char *pcr_error; size_t oldfile_len, newfile_len; phar_entry_info *oldentry, newentry = {0}, *temp; int tmp_len = 0; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile); RETURN_FALSE; } if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len)) || oldentry->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) { if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) || !temp->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } } tmp_len = (int)newfile_len; if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname); RETURN_FALSE; } newfile_len = tmp_len; if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate with copied-on-write entry */ oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len); } memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info)); if (Z_TYPE(newentry.metadata) != IS_UNDEF) { zval_copy_ctor(&newentry.metadata); newentry.metadata_str.s = NULL; } newentry.filename = estrndup(newfile, newfile_len); newentry.filename_len = newfile_len; newentry.fp_refcount = 0; if (oldentry->fp_type != PHAR_FP) { if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) { efree(newentry.filename); php_stream_close(newentry.fp); zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); return; } } zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info)); phar_obj->archive->is_modified = 1; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, copy) { char *oldfile, *newfile, *error; const char *pcr_error; size_t oldfile_len, newfile_len; phar_entry_info *oldentry, newentry = {0}, *temp; int tmp_len = 0; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile); RETURN_FALSE; } if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len)) || oldentry->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) { if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) || !temp->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } } tmp_len = (int)newfile_len; if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname); RETURN_FALSE; } newfile_len = tmp_len; if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate with copied-on-write entry */ oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len); } memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info)); if (Z_TYPE(newentry.metadata) != IS_UNDEF) { zval_copy_ctor(&newentry.metadata); newentry.metadata_str.s = NULL; } newentry.filename = estrndup(newfile, newfile_len); newentry.filename_len = newfile_len; newentry.fp_refcount = 0; if (oldentry->fp_type != PHAR_FP) { if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) { efree(newentry.filename); php_stream_close(newentry.fp); zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); return; } } zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info)); phar_obj->archive->is_modified = 1; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; }
165,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaStreamDispatcherHost::BindRequest( mojom::MediaStreamDispatcherHostRequest request) { DCHECK_CURRENTLY_ON(BrowserThread::IO); bindings_.AddBinding(this, std::move(request)); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void MediaStreamDispatcherHost::BindRequest( void MediaStreamDispatcherHost::Create( int render_process_id, int render_frame_id, MediaStreamManager* media_stream_manager, mojom::MediaStreamDispatcherHostRequest request) { DCHECK_CURRENTLY_ON(BrowserThread::IO); mojo::MakeStrongBinding( std::make_unique<MediaStreamDispatcherHost>( render_process_id, render_frame_id, media_stream_manager), std::move(request)); }
173,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc __unused, char** argv) { signal(SIGPIPE, SIG_IGN); char value[PROPERTY_VALUE_MAX]; bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1); pid_t childPid; if (doLog && (childPid = fork()) != 0) { strcpy(argv[0], "media.log"); sp<ProcessState> proc(ProcessState::self()); MediaLogService::instantiate(); ProcessState::self()->startThreadPool(); for (;;) { siginfo_t info; int ret = waitid(P_PID, childPid, &info, WEXITED | WSTOPPED | WCONTINUED); if (ret == EINTR) { continue; } if (ret < 0) { break; } char buffer[32]; const char *code; switch (info.si_code) { case CLD_EXITED: code = "CLD_EXITED"; break; case CLD_KILLED: code = "CLD_KILLED"; break; case CLD_DUMPED: code = "CLD_DUMPED"; break; case CLD_STOPPED: code = "CLD_STOPPED"; break; case CLD_TRAPPED: code = "CLD_TRAPPED"; break; case CLD_CONTINUED: code = "CLD_CONTINUED"; break; default: snprintf(buffer, sizeof(buffer), "unknown (%d)", info.si_code); code = buffer; break; } struct rusage usage; getrusage(RUSAGE_CHILDREN, &usage); ALOG(LOG_ERROR, "media.log", "pid %d status %d code %s user %ld.%03lds sys %ld.%03lds", info.si_pid, info.si_status, code, usage.ru_utime.tv_sec, usage.ru_utime.tv_usec / 1000, usage.ru_stime.tv_sec, usage.ru_stime.tv_usec / 1000); sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("media.log")); if (binder != 0) { Vector<String16> args; binder->dump(-1, args); } switch (info.si_code) { case CLD_EXITED: case CLD_KILLED: case CLD_DUMPED: { ALOG(LOG_INFO, "media.log", "exiting"); _exit(0); } default: break; } } } else { if (doLog) { prctl(PR_SET_PDEATHSIG, SIGKILL); // if parent media.log dies before me, kill me also setpgid(0, 0); // but if I die first, don't kill my parent } InitializeIcuOrDie(); sp<ProcessState> proc(ProcessState::self()); sp<IServiceManager> sm = defaultServiceManager(); ALOGI("ServiceManager: %p", sm.get()); AudioFlinger::instantiate(); MediaPlayerService::instantiate(); ResourceManagerService::instantiate(); CameraService::instantiate(); AudioPolicyService::instantiate(); SoundTriggerHwService::instantiate(); RadioService::instantiate(); registerExtensions(); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); } } Commit Message: limit mediaserver memory Limit mediaserver using rlimit, to prevent it from bringing down the system via the low memory killer. Default max is 65% of total RAM, but can be customized via system property. Bug: 28471206 Bug: 28615448 Change-Id: Ic84137435d1ef0a6883e9789a4b4f399e4283f05 CWE ID: CWE-399
int main(int argc __unused, char** argv) { limitProcessMemory( "ro.media.maxmem", /* property that defines limit */ SIZE_MAX, /* upper limit in bytes */ 65 /* upper limit as percentage of physical RAM */); signal(SIGPIPE, SIG_IGN); char value[PROPERTY_VALUE_MAX]; bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1); pid_t childPid; if (doLog && (childPid = fork()) != 0) { strcpy(argv[0], "media.log"); sp<ProcessState> proc(ProcessState::self()); MediaLogService::instantiate(); ProcessState::self()->startThreadPool(); for (;;) { siginfo_t info; int ret = waitid(P_PID, childPid, &info, WEXITED | WSTOPPED | WCONTINUED); if (ret == EINTR) { continue; } if (ret < 0) { break; } char buffer[32]; const char *code; switch (info.si_code) { case CLD_EXITED: code = "CLD_EXITED"; break; case CLD_KILLED: code = "CLD_KILLED"; break; case CLD_DUMPED: code = "CLD_DUMPED"; break; case CLD_STOPPED: code = "CLD_STOPPED"; break; case CLD_TRAPPED: code = "CLD_TRAPPED"; break; case CLD_CONTINUED: code = "CLD_CONTINUED"; break; default: snprintf(buffer, sizeof(buffer), "unknown (%d)", info.si_code); code = buffer; break; } struct rusage usage; getrusage(RUSAGE_CHILDREN, &usage); ALOG(LOG_ERROR, "media.log", "pid %d status %d code %s user %ld.%03lds sys %ld.%03lds", info.si_pid, info.si_status, code, usage.ru_utime.tv_sec, usage.ru_utime.tv_usec / 1000, usage.ru_stime.tv_sec, usage.ru_stime.tv_usec / 1000); sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("media.log")); if (binder != 0) { Vector<String16> args; binder->dump(-1, args); } switch (info.si_code) { case CLD_EXITED: case CLD_KILLED: case CLD_DUMPED: { ALOG(LOG_INFO, "media.log", "exiting"); _exit(0); } default: break; } } } else { if (doLog) { prctl(PR_SET_PDEATHSIG, SIGKILL); // if parent media.log dies before me, kill me also setpgid(0, 0); // but if I die first, don't kill my parent } InitializeIcuOrDie(); sp<ProcessState> proc(ProcessState::self()); sp<IServiceManager> sm = defaultServiceManager(); ALOGI("ServiceManager: %p", sm.get()); AudioFlinger::instantiate(); MediaPlayerService::instantiate(); ResourceManagerService::instantiate(); CameraService::instantiate(); AudioPolicyService::instantiate(); SoundTriggerHwService::instantiate(); RadioService::instantiate(); registerExtensions(); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); } }
173,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t ACodec::setupAACCodec( bool encoder, int32_t numChannels, int32_t sampleRate, int32_t bitRate, int32_t aacProfile, bool isADTS, int32_t sbrMode, int32_t maxOutputChannelCount, const drcParams_t& drc, int32_t pcmLimiterEnable) { if (encoder && isADTS) { return -EINVAL; } status_t err = setupRawAudioFormat( encoder ? kPortIndexInput : kPortIndexOutput, sampleRate, numChannels); if (err != OK) { return err; } if (encoder) { err = selectAudioPortFormat(kPortIndexOutput, OMX_AUDIO_CodingAAC); if (err != OK) { return err; } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = kPortIndexOutput; err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } def.format.audio.bFlagErrorConcealment = OMX_TRUE; def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; err = mOMX->setParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } OMX_AUDIO_PARAM_AACPROFILETYPE profile; InitOMXParams(&profile); profile.nPortIndex = kPortIndexOutput; err = mOMX->getParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } profile.nChannels = numChannels; profile.eChannelMode = (numChannels == 1) ? OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo; profile.nSampleRate = sampleRate; profile.nBitRate = bitRate; profile.nAudioBandWidth = 0; profile.nFrameLength = 0; profile.nAACtools = OMX_AUDIO_AACToolAll; profile.nAACERtools = OMX_AUDIO_AACERNone; profile.eAACProfile = (OMX_AUDIO_AACPROFILETYPE) aacProfile; profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; switch (sbrMode) { case 0: profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 1: profile.nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 2: profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; case -1: profile.nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; default: return BAD_VALUE; } err = mOMX->setParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } return err; } OMX_AUDIO_PARAM_AACPROFILETYPE profile; InitOMXParams(&profile); profile.nPortIndex = kPortIndexInput; err = mOMX->getParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } profile.nChannels = numChannels; profile.nSampleRate = sampleRate; profile.eAACStreamFormat = isADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF; OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE presentation; presentation.nMaxOutputChannels = maxOutputChannelCount; presentation.nDrcCut = drc.drcCut; presentation.nDrcBoost = drc.drcBoost; presentation.nHeavyCompression = drc.heavyCompression; presentation.nTargetReferenceLevel = drc.targetRefLevel; presentation.nEncodedTargetLevel = drc.encodedTargetLevel; presentation.nPCMLimiterEnable = pcmLimiterEnable; status_t res = mOMX->setParameter(mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (res == OK) { mOMX->setParameter(mNode, (OMX_INDEXTYPE)OMX_IndexParamAudioAndroidAacPresentation, &presentation, sizeof(presentation)); } else { ALOGW("did not set AudioAndroidAacPresentation due to error %d when setting AudioAac", res); } return res; } Commit Message: Fix initialization of AAC presentation struct Otherwise the new size checks trip on this. Bug: 27207275 Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766 CWE ID: CWE-119
status_t ACodec::setupAACCodec( bool encoder, int32_t numChannels, int32_t sampleRate, int32_t bitRate, int32_t aacProfile, bool isADTS, int32_t sbrMode, int32_t maxOutputChannelCount, const drcParams_t& drc, int32_t pcmLimiterEnable) { if (encoder && isADTS) { return -EINVAL; } status_t err = setupRawAudioFormat( encoder ? kPortIndexInput : kPortIndexOutput, sampleRate, numChannels); if (err != OK) { return err; } if (encoder) { err = selectAudioPortFormat(kPortIndexOutput, OMX_AUDIO_CodingAAC); if (err != OK) { return err; } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = kPortIndexOutput; err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } def.format.audio.bFlagErrorConcealment = OMX_TRUE; def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; err = mOMX->setParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } OMX_AUDIO_PARAM_AACPROFILETYPE profile; InitOMXParams(&profile); profile.nPortIndex = kPortIndexOutput; err = mOMX->getParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } profile.nChannels = numChannels; profile.eChannelMode = (numChannels == 1) ? OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo; profile.nSampleRate = sampleRate; profile.nBitRate = bitRate; profile.nAudioBandWidth = 0; profile.nFrameLength = 0; profile.nAACtools = OMX_AUDIO_AACToolAll; profile.nAACERtools = OMX_AUDIO_AACERNone; profile.eAACProfile = (OMX_AUDIO_AACPROFILETYPE) aacProfile; profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; switch (sbrMode) { case 0: profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 1: profile.nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 2: profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; case -1: profile.nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; default: return BAD_VALUE; } err = mOMX->setParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } return err; } OMX_AUDIO_PARAM_AACPROFILETYPE profile; InitOMXParams(&profile); profile.nPortIndex = kPortIndexInput; err = mOMX->getParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } profile.nChannels = numChannels; profile.nSampleRate = sampleRate; profile.eAACStreamFormat = isADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF; OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE presentation; InitOMXParams(&presentation); presentation.nMaxOutputChannels = maxOutputChannelCount; presentation.nDrcCut = drc.drcCut; presentation.nDrcBoost = drc.drcBoost; presentation.nHeavyCompression = drc.heavyCompression; presentation.nTargetReferenceLevel = drc.targetRefLevel; presentation.nEncodedTargetLevel = drc.encodedTargetLevel; presentation.nPCMLimiterEnable = pcmLimiterEnable; status_t res = mOMX->setParameter(mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (res == OK) { mOMX->setParameter(mNode, (OMX_INDEXTYPE)OMX_IndexParamAudioAndroidAacPresentation, &presentation, sizeof(presentation)); } else { ALOGW("did not set AudioAndroidAacPresentation due to error %d when setting AudioAac", res); } return res; }
174,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mm_sshpam_init_ctx(Authctxt *authctxt) { Buffer m; int success; debug3("%s", __func__); buffer_init(&m); buffer_put_cstring(&m, authctxt->user); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m); debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m); success = buffer_get_int(&m); if (success == 0) { debug3("%s: pam_init_ctx failed", __func__); buffer_free(&m); return (NULL); } buffer_free(&m); return (authctxt); } Commit Message: Don't resend username to PAM; it already has it. Pointed out by Moritz Jodeit; ok dtucker@ CWE ID: CWE-20
mm_sshpam_init_ctx(Authctxt *authctxt) { Buffer m; int success; debug3("%s", __func__); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m); debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m); success = buffer_get_int(&m); if (success == 0) { debug3("%s: pam_init_ctx failed", __func__); buffer_free(&m); return (NULL); } buffer_free(&m); return (authctxt); }
166,586
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OpenSession() { const int render_process_id = 1; const int render_frame_id = 1; const int page_request_id = 1; const url::Origin security_origin = url::Origin::Create(GURL("http://test.com")); ASSERT_TRUE(opened_device_label_.empty()); MediaDeviceInfoArray video_devices; { base::RunLoop run_loop; MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; media_stream_manager_->media_devices_manager()->EnumerateDevices( devices_to_enumerate, base::BindOnce(&VideoInputDevicesEnumerated, run_loop.QuitClosure(), browser_context_.GetMediaDeviceIDSalt(), security_origin, &video_devices)); run_loop.Run(); } ASSERT_FALSE(video_devices.empty()); { base::RunLoop run_loop; media_stream_manager_->OpenDevice( render_process_id, render_frame_id, page_request_id, video_devices[0].device_id, MEDIA_DEVICE_VIDEO_CAPTURE, MediaDeviceSaltAndOrigin{browser_context_.GetMediaDeviceIDSalt(), browser_context_.GetMediaDeviceIDSalt(), security_origin}, base::BindOnce(&VideoCaptureTest::OnDeviceOpened, base::Unretained(this), run_loop.QuitClosure()), MediaStreamManager::DeviceStoppedCallback()); run_loop.Run(); } ASSERT_NE(MediaStreamDevice::kNoId, opened_session_id_); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void OpenSession() { const int render_process_id = 1; const int render_frame_id = 1; const int requester_id = 1; const int page_request_id = 1; const url::Origin security_origin = url::Origin::Create(GURL("http://test.com")); ASSERT_TRUE(opened_device_label_.empty()); MediaDeviceInfoArray video_devices; { base::RunLoop run_loop; MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; media_stream_manager_->media_devices_manager()->EnumerateDevices( devices_to_enumerate, base::BindOnce(&VideoInputDevicesEnumerated, run_loop.QuitClosure(), browser_context_.GetMediaDeviceIDSalt(), security_origin, &video_devices)); run_loop.Run(); } ASSERT_FALSE(video_devices.empty()); { base::RunLoop run_loop; media_stream_manager_->OpenDevice( render_process_id, render_frame_id, requester_id, page_request_id, video_devices[0].device_id, MEDIA_DEVICE_VIDEO_CAPTURE, MediaDeviceSaltAndOrigin{browser_context_.GetMediaDeviceIDSalt(), browser_context_.GetMediaDeviceIDSalt(), security_origin}, base::BindOnce(&VideoCaptureTest::OnDeviceOpened, base::Unretained(this), run_loop.QuitClosure()), MediaStreamManager::DeviceStoppedCallback()); run_loop.Run(); } ASSERT_NE(MediaStreamDevice::kNoId, opened_session_id_); }
173,109
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(openssl_encrypt) { zend_bool raw_output = 0; char *data, *method, *password, *iv = ""; int data_len, method_len, password_len, iv_len = 0, max_iv_len; const EVP_CIPHER *cipher_type; EVP_CIPHER_CTX cipher_ctx; int i, outlen, keylen; unsigned char *outbuf, *key; zend_bool free_iv; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) { return; } cipher_type = EVP_get_cipherbyname(method); if (!cipher_type) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm"); RETURN_FALSE; } keylen = EVP_CIPHER_key_length(cipher_type); if (keylen > password_len) { key = emalloc(keylen); memset(key, 0, keylen); memcpy(key, password, password_len); } else { key = (unsigned char*)password; } max_iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv_len <= 0 && max_iv_len > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended"); } free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC); outlen = data_len + EVP_CIPHER_block_size(cipher_type); outbuf = emalloc(outlen + 1); EVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL); if (password_len > keylen) { EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len); } EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv); if (data_len > 0) { EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len); } outlen = i; if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) { outlen += i; if (raw_output) { outbuf[outlen] = '\0'; RETVAL_STRINGL((char *)outbuf, outlen, 0); } else { int base64_str_len; char *base64_str; base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len); efree(outbuf); RETVAL_STRINGL(base64_str, base64_str_len, 0); } } else { efree(outbuf); RETVAL_FALSE; } if (key != (unsigned char*)password) { efree(key); } if (free_iv) { efree(iv); } EVP_CIPHER_CTX_cleanup(&cipher_ctx); } Commit Message: CWE ID: CWE-200
PHP_FUNCTION(openssl_encrypt) { zend_bool raw_output = 0; char *data, *method, *password, *iv = ""; int data_len, method_len, password_len, iv_len = 0, max_iv_len; const EVP_CIPHER *cipher_type; EVP_CIPHER_CTX cipher_ctx; int i = 0, outlen, keylen; unsigned char *outbuf, *key; zend_bool free_iv; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) { return; } cipher_type = EVP_get_cipherbyname(method); if (!cipher_type) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm"); RETURN_FALSE; } keylen = EVP_CIPHER_key_length(cipher_type); if (keylen > password_len) { key = emalloc(keylen); memset(key, 0, keylen); memcpy(key, password, password_len); } else { key = (unsigned char*)password; } max_iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv_len <= 0 && max_iv_len > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended"); } free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC); outlen = data_len + EVP_CIPHER_block_size(cipher_type); outbuf = emalloc(outlen + 1); EVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL); if (password_len > keylen) { EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len); } EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv); if (data_len > 0) { EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len); } outlen = i; if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) { outlen += i; if (raw_output) { outbuf[outlen] = '\0'; RETVAL_STRINGL((char *)outbuf, outlen, 0); } else { int base64_str_len; char *base64_str; base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len); efree(outbuf); RETVAL_STRINGL(base64_str, base64_str_len, 0); } } else { efree(outbuf); RETVAL_FALSE; } if (key != (unsigned char*)password) { efree(key); } if (free_iv) { efree(iv); } EVP_CIPHER_CTX_cleanup(&cipher_ctx); }
164,805
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int toggle_utf8(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
static int toggle_utf8(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); r = vt_verify_kbmode(fd); if (r == -EBUSY) { log_warning_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", name); return 0; } else if (r < 0) return log_warning_errno(r, "Failed to verify kbdmode on %s: %m", name); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; }
169,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog( WebContents* initiator) { base::AutoReset<bool> auto_reset(&is_creating_print_preview_dialog_, true); ConstrainedWebDialogDelegate* web_dialog_delegate = ShowConstrainedWebDialog(initiator->GetBrowserContext(), new PrintPreviewDialogDelegate(initiator), initiator); WebContents* preview_dialog = web_dialog_delegate->GetWebContents(); GURL print_url(chrome::kChromeUIPrintURL); content::HostZoomMap::Get(preview_dialog->GetSiteInstance()) ->SetZoomLevelForHostAndScheme(print_url.scheme(), print_url.host(), 0); PrintViewManager::CreateForWebContents(preview_dialog); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( preview_dialog); preview_dialog_map_[preview_dialog] = initiator; waiting_for_new_preview_page_ = true; task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog); AddObservers(initiator); AddObservers(preview_dialog); return preview_dialog; } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog( WebContents* initiator) { base::AutoReset<bool> auto_reset(&is_creating_print_preview_dialog_, true); ConstrainedWebDialogDelegate* web_dialog_delegate = ShowConstrainedWebDialog(initiator->GetBrowserContext(), new PrintPreviewDialogDelegate(initiator), initiator); WebContents* preview_dialog = web_dialog_delegate->GetWebContents(); GURL print_url(chrome::kChromeUIPrintURL); content::HostZoomMap::Get(preview_dialog->GetSiteInstance()) ->SetZoomLevelForHostAndScheme(print_url.scheme(), print_url.host(), 0); PrintViewManager::CreateForWebContents(preview_dialog); CreateCompositeClientIfNeeded(preview_dialog, true /* for_preview */); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( preview_dialog); preview_dialog_map_[preview_dialog] = initiator; waiting_for_new_preview_page_ = true; task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog); AddObservers(initiator); AddObservers(preview_dialog); return preview_dialog; }
171,887
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer, apr_size_t len, int linelimit) { apr_size_t i = 0; while (i < len) { char c = buffer[i]; ap_xlate_proto_from_ascii(&c, 1); /* handle CRLF after the chunk */ if (ctx->state == BODY_CHUNK_END) { if (c == LF) { ctx->state = BODY_CHUNK; } i++; continue; } /* handle start of the chunk */ if (ctx->state == BODY_CHUNK) { if (!apr_isxdigit(c)) { /* * Detect invalid character at beginning. This also works for empty * chunk size lines. */ return APR_EGENERAL; } else { ctx->state = BODY_CHUNK_PART; } ctx->remaining = 0; ctx->chunkbits = sizeof(long) * 8; ctx->chunk_used = 0; } /* handle a chunk part, or a chunk extension */ /* * In theory, we are supposed to expect CRLF only, but our * test suite sends LF only. Tolerate a missing CR. */ if (c == ';' || c == CR) { ctx->state = BODY_CHUNK_EXT; } else if (c == LF) { if (ctx->remaining) { ctx->state = BODY_CHUNK_DATA; } else { ctx->state = BODY_CHUNK_TRAILER; } } else if (ctx->state != BODY_CHUNK_EXT) { int xvalue = 0; /* ignore leading zeros */ if (!ctx->remaining && c == '0') { i++; continue; } if (c >= '0' && c <= '9') { xvalue = c - '0'; } else if (c >= 'A' && c <= 'F') { xvalue = c - 'A' + 0xa; } else if (c >= 'a' && c <= 'f') { xvalue = c - 'a' + 0xa; } else { /* bogus character */ return APR_EGENERAL; } ctx->remaining = (ctx->remaining << 4) | xvalue; ctx->chunkbits -= 4; if (ctx->chunkbits <= 0 || ctx->remaining < 0) { /* overflow */ return APR_ENOSPC; } } i++; } /* sanity check */ ctx->chunk_used += len; if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) { return APR_ENOSPC; } return APR_SUCCESS; } Commit Message: Limit accepted chunk-size to 2^63-1 and be strict about chunk-ext authorized characters. Submitted by: Yann Ylavic git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684513 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-20
static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer, apr_size_t len, int linelimit) { apr_size_t i = 0; while (i < len) { char c = buffer[i]; ap_xlate_proto_from_ascii(&c, 1); /* handle CRLF after the chunk */ if (ctx->state == BODY_CHUNK_END || ctx->state == BODY_CHUNK_END_LF) { if (c == LF) { ctx->state = BODY_CHUNK; } else if (c == CR && ctx->state == BODY_CHUNK_END) { ctx->state = BODY_CHUNK_END_LF; } else { /* * LF expected. */ return APR_EINVAL; } i++; continue; } /* handle start of the chunk */ if (ctx->state == BODY_CHUNK) { if (!apr_isxdigit(c)) { /* * Detect invalid character at beginning. This also works for * empty chunk size lines. */ return APR_EINVAL; } else { ctx->state = BODY_CHUNK_PART; } ctx->remaining = 0; ctx->chunkbits = sizeof(apr_off_t) * 8; ctx->chunk_used = 0; } if (c == LF) { if (ctx->remaining) { ctx->state = BODY_CHUNK_DATA; } else { ctx->state = BODY_CHUNK_TRAILER; } } else if (ctx->state == BODY_CHUNK_LF) { /* * LF expected. */ return APR_EINVAL; } else if (c == CR) { ctx->state = BODY_CHUNK_LF; } else if (c == ';') { ctx->state = BODY_CHUNK_EXT; } else if (ctx->state == BODY_CHUNK_EXT) { /* * Control chars (but tabs) are invalid. */ if (c != '\t' && apr_iscntrl(c)) { return APR_EINVAL; } } else if (ctx->state == BODY_CHUNK_PART) { int xvalue; /* ignore leading zeros */ if (!ctx->remaining && c == '0') { i++; continue; } ctx->chunkbits -= 4; if (ctx->chunkbits < 0) { /* overflow */ return APR_ENOSPC; } if (c >= '0' && c <= '9') { xvalue = c - '0'; } else if (c >= 'A' && c <= 'F') { xvalue = c - 'A' + 0xa; } else if (c >= 'a' && c <= 'f') { xvalue = c - 'a' + 0xa; } else { /* bogus character */ return APR_EINVAL; } ctx->remaining = (ctx->remaining << 4) | xvalue; if (ctx->remaining < 0) { /* overflow */ return APR_ENOSPC; } } else { /* Should not happen */ return APR_EGENERAL; } i++; } /* sanity check */ ctx->chunk_used += len; if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) { return APR_ENOSPC; } return APR_SUCCESS; }
166,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) { _cleanup_close_ int fd; int r; assert(path); if (parents) mkdir_parents(path, 0755); fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644); if (fd < 0) return -errno; if (mode != MODE_INVALID) { r = fchmod(fd, mode); if (r < 0) return -errno; } if (uid != UID_INVALID || gid != GID_INVALID) { r = fchown(fd, uid, gid); if (r < 0) return -errno; } if (stamp != USEC_INFINITY) { struct timespec ts[2]; timespec_store(&ts[0], stamp); ts[1] = ts[0]; r = futimens(fd, ts); } else r = futimens(fd, NULL); if (r < 0) return -errno; return 0; } Commit Message: basic: fix touch() creating files with 07777 mode mode_t is unsigned, so MODE_INVALID < 0 can never be true. This fixes a possible DoS where any user could fill /run by writing to a world-writable /run/systemd/show-status. CWE ID: CWE-264
int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) { _cleanup_close_ int fd; int r; assert(path); if (parents) mkdir_parents(path, 0755); fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, (mode == 0 || mode == MODE_INVALID) ? 0644 : mode); if (fd < 0) return -errno; if (mode != MODE_INVALID) { r = fchmod(fd, mode); if (r < 0) return -errno; } if (uid != UID_INVALID || gid != GID_INVALID) { r = fchown(fd, uid, gid); if (r < 0) return -errno; } if (stamp != USEC_INFINITY) { struct timespec ts[2]; timespec_store(&ts[0], stamp); ts[1] = ts[0]; r = futimens(fd, ts); } else r = futimens(fd, NULL); if (r < 0) return -errno; return 0; }
168,517
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HeapAllocator::backingFree(void* address) { if (!address) return; ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return; ASSERT(!state->isInGC()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); ASSERT(header->checkHeader()); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); state->promptlyFreed(header->gcInfoIndex()); arena->promptlyFreeObject(header); } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
void HeapAllocator::backingFree(void* address) { if (!address) return; ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return; ASSERT(!state->isInGC()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); header->checkHeader(); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); state->promptlyFreed(header->gcInfoIndex()); arena->promptlyFreeObject(header); }
172,706
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool ndp_msg_check_valid(struct ndp_msg *msg) { size_t len = ndp_msg_payload_len(msg); enum ndp_msg_type msg_type = ndp_msg_type(msg); if (len < ndp_msg_type_info(msg_type)->raw_struct_size) return false; return true; } Commit Message: libndb: reject redirect and router advertisements from non-link-local RFC4861 suggests that these messages should only originate from link-local addresses in 6.1.2 (RA) and 8.1. (redirect): Mitigates CVE-2016-3698. Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]> CWE ID: CWE-284
static bool ndp_msg_check_valid(struct ndp_msg *msg) { size_t len = ndp_msg_payload_len(msg); enum ndp_msg_type msg_type = ndp_msg_type(msg); if (len < ndp_msg_type_info(msg_type)->raw_struct_size) return false; if (ndp_msg_type_info(msg_type)->addrto_validate) return ndp_msg_type_info(msg_type)->addrto_validate(&msg->addrto); else return true; }
169,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char *argv[]) { libettercap_init(); ef_globals_alloc(); select_text_interface(); libettercap_ui_init(); /* etterfilter copyright */ fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n", PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS); /* initialize the line number */ EF_GBL->lineno = 1; /* getopt related parsing... */ parse_options(argc, argv); /* set the input for source file */ if (EF_GBL_OPTIONS->source_file) { yyin = fopen(EF_GBL_OPTIONS->source_file, "r"); if (yyin == NULL) FATAL_ERROR("Input file not found !"); } else { FATAL_ERROR("No source file."); } /* no buffering */ setbuf(yyin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); /* load the tables in etterfilter.tbl */ load_tables(); /* load the constants in etterfilter.cnt */ load_constants(); /* print the message */ fprintf(stdout, "\n Parsing source file \'%s\' ", EF_GBL_OPTIONS->source_file); fflush(stdout); ef_debug(1, "\n"); /* begin the parsing */ if (yyparse() == 0) fprintf(stdout, " done.\n\n"); else fprintf(stdout, "\n\nThe script contains errors...\n\n"); /* write to file */ if (write_output() != E_SUCCESS) FATAL_ERROR("Cannot write output file (%s)", EF_GBL_OPTIONS->output_file); ef_globals_free(); return 0; } Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782) CWE ID: CWE-125
int main(int argc, char *argv[]) { int ret_value = 0; libettercap_init(); ef_globals_alloc(); select_text_interface(); libettercap_ui_init(); /* etterfilter copyright */ fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n", PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS); /* initialize the line number */ EF_GBL->lineno = 1; /* getopt related parsing... */ parse_options(argc, argv); /* set the input for source file */ if (EF_GBL_OPTIONS->source_file) { yyin = fopen(EF_GBL_OPTIONS->source_file, "r"); if (yyin == NULL) FATAL_ERROR("Input file not found !"); } else { FATAL_ERROR("No source file."); } /* no buffering */ setbuf(yyin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); /* load the tables in etterfilter.tbl */ load_tables(); /* load the constants in etterfilter.cnt */ load_constants(); /* print the message */ fprintf(stdout, "\n Parsing source file \'%s\' ", EF_GBL_OPTIONS->source_file); fflush(stdout); ef_debug(1, "\n"); /* begin the parsing */ if (yyparse() == 0) fprintf(stdout, " done.\n\n"); else fprintf(stdout, "\n\nThe script contains errors...\n\n"); /* write to file */ ret_value = write_output(); if (ret_value == -E_NOTHANDLED) FATAL_ERROR("Cannot write output file (%s): the filter is not correctly handled.", EF_GBL_OPTIONS->output_file); else if (ret_value == -E_INVALID) FATAL_ERROR("Cannot write output file (%s): the filter format is not correct. ", EF_GBL_OPTIONS->output_file); ef_globals_free(); return 0; }
168,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::SpeakOrEnqueue(Utterance* utterance) { if (IsSpeaking() && utterance->can_enqueue()) { utterance_queue_.push(utterance); } else { Stop(); SpeakNow(utterance); } } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::SpeakOrEnqueue(Utterance* utterance) { std::string gender; if (options->HasKey(constants::kGenderKey)) EXTENSION_FUNCTION_VALIDATE( options->GetString(constants::kGenderKey, &gender)); if (!gender.empty() && gender != constants::kGenderFemale && gender != constants::kGenderMale) { error_ = constants::kErrorInvalidGender; return false; }
170,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid("incorrect prefix length"); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; } Commit Message: index: error out on unreasonable prefix-compressed path lengths When computing the complete path length from the encoded prefix-compressed path, we end up just allocating the complete path without ever checking what the encoded path length actually is. This can easily lead to a denial of service by just encoding an unreasonable long path name inside of the index. Git already enforces a maximum path length of 4096 bytes. As we also have that enforcement ready in some places, just make sure that the resulting path is smaller than GIT_PATH_MAX. Reported-by: Krishna Ram Prakash R <[email protected]> Reported-by: Vivek Parikh <[email protected]> CWE ID: CWE-190
static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid("incorrect prefix length"); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); if (path_len > GIT_PATH_MAX) return index_error_invalid("unreasonable path length"); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; }
170,171
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ext2_xattr_get(struct inode *inode, int name_index, const char *name, void *buffer, size_t buffer_size) { struct buffer_head *bh = NULL; struct ext2_xattr_entry *entry; size_t name_len, size; char *end; int error; ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld", name_index, name, buffer, (long)buffer_size); if (name == NULL) return -EINVAL; name_len = strlen(name); if (name_len > 255) return -ERANGE; down_read(&EXT2_I(inode)->xattr_sem); error = -ENODATA; if (!EXT2_I(inode)->i_file_acl) goto cleanup; ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl); bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl); error = -EIO; if (!bh) goto cleanup; ea_bdebug(bh, "b_count=%d, refcount=%d", atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount)); end = bh->b_data + bh->b_size; if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) || HDR(bh)->h_blocks != cpu_to_le32(1)) { bad_block: ext2_error(inode->i_sb, "ext2_xattr_get", "inode %ld: bad block %d", inode->i_ino, EXT2_I(inode)->i_file_acl); error = -EIO; goto cleanup; } /* find named attribute */ entry = FIRST_ENTRY(bh); while (!IS_LAST_ENTRY(entry)) { struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(entry); if ((char *)next >= end) goto bad_block; if (name_index == entry->e_name_index && name_len == entry->e_name_len && memcmp(name, entry->e_name, name_len) == 0) goto found; entry = next; } if (ext2_xattr_cache_insert(bh)) ea_idebug(inode, "cache insert failed"); error = -ENODATA; goto cleanup; found: /* check the buffer size */ if (entry->e_value_block != 0) goto bad_block; size = le32_to_cpu(entry->e_value_size); if (size > inode->i_sb->s_blocksize || le16_to_cpu(entry->e_value_offs) + size > inode->i_sb->s_blocksize) goto bad_block; if (ext2_xattr_cache_insert(bh)) ea_idebug(inode, "cache insert failed"); if (buffer) { error = -ERANGE; if (size > buffer_size) goto cleanup; /* return value of attribute */ memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs), size); } error = size; cleanup: brelse(bh); up_read(&EXT2_I(inode)->xattr_sem); return error; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
ext2_xattr_get(struct inode *inode, int name_index, const char *name, void *buffer, size_t buffer_size) { struct buffer_head *bh = NULL; struct ext2_xattr_entry *entry; size_t name_len, size; char *end; int error; struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache; ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld", name_index, name, buffer, (long)buffer_size); if (name == NULL) return -EINVAL; name_len = strlen(name); if (name_len > 255) return -ERANGE; down_read(&EXT2_I(inode)->xattr_sem); error = -ENODATA; if (!EXT2_I(inode)->i_file_acl) goto cleanup; ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl); bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl); error = -EIO; if (!bh) goto cleanup; ea_bdebug(bh, "b_count=%d, refcount=%d", atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount)); end = bh->b_data + bh->b_size; if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) || HDR(bh)->h_blocks != cpu_to_le32(1)) { bad_block: ext2_error(inode->i_sb, "ext2_xattr_get", "inode %ld: bad block %d", inode->i_ino, EXT2_I(inode)->i_file_acl); error = -EIO; goto cleanup; } /* find named attribute */ entry = FIRST_ENTRY(bh); while (!IS_LAST_ENTRY(entry)) { struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(entry); if ((char *)next >= end) goto bad_block; if (name_index == entry->e_name_index && name_len == entry->e_name_len && memcmp(name, entry->e_name, name_len) == 0) goto found; entry = next; } if (ext2_xattr_cache_insert(ext2_mb_cache, bh)) ea_idebug(inode, "cache insert failed"); error = -ENODATA; goto cleanup; found: /* check the buffer size */ if (entry->e_value_block != 0) goto bad_block; size = le32_to_cpu(entry->e_value_size); if (size > inode->i_sb->s_blocksize || le16_to_cpu(entry->e_value_offs) + size > inode->i_sb->s_blocksize) goto bad_block; if (ext2_xattr_cache_insert(ext2_mb_cache, bh)) ea_idebug(inode, "cache insert failed"); if (buffer) { error = -ERANGE; if (size > buffer_size) goto cleanup; /* return value of attribute */ memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs), size); } error = size; cleanup: brelse(bh); up_read(&EXT2_I(inode)->xattr_sem); return error; }
169,980
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } } } Commit Message: Fix bug #72340: Double Free Courruption in wddx_deserialize CWE ID: CWE-415
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } } }
167,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GLboolean WebGLRenderingContextBase::isRenderbuffer( WebGLRenderbuffer* renderbuffer) { if (!renderbuffer || isContextLost()) return 0; if (!renderbuffer->HasEverBeenBound()) return 0; if (renderbuffer->IsDeleted()) return 0; return ContextGL()->IsRenderbuffer(renderbuffer->Object()); } Commit Message: Validate all incoming WebGLObjects. A few entry points were missing the correct validation. Tested with improved conformance tests in https://github.com/KhronosGroup/WebGL/pull/2654 . Bug: 848914 Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008 Reviewed-on: https://chromium-review.googlesource.com/1086718 Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Commit-Queue: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#565016} CWE ID: CWE-119
GLboolean WebGLRenderingContextBase::isRenderbuffer( WebGLRenderbuffer* renderbuffer) { if (!renderbuffer || isContextLost() || !renderbuffer->Validate(ContextGroup(), this)) return 0; if (!renderbuffer->HasEverBeenBound()) return 0; if (renderbuffer->IsDeleted()) return 0; return ContextGL()->IsRenderbuffer(renderbuffer->Object()); }
173,131
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadOneDJVUImage(LoadContext* lc,const int pagenum, const ImageInfo *image_info,ExceptionInfo *exception) { ddjvu_page_type_t type; ddjvu_pageinfo_t info; ddjvu_message_t *message; Image *image; int logging; int tag; /* so, we know that the page is there! Get its dimension, and */ /* Read one DJVU image */ image = lc->image; /* register PixelPacket *q; */ logging=LogMagickEvent(CoderEvent,GetMagickModule(), " enter ReadOneDJVUImage()"); (void) logging; #if DEBUG printf("==== Loading the page %d\n", pagenum); #endif lc->page = ddjvu_page_create_by_pageno(lc->document, pagenum); /* 0? */ /* pump data untill the page is ready for rendering. */ tag=(-1); do { while ((message = ddjvu_message_peek(lc->context))) { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } /* fixme: maybe exit? */ /* if (lc->error) break; */ message = pump_data_until_message(lc,image); if (message) do { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } while ((message = ddjvu_message_peek(lc->context))); } while (!ddjvu_page_decoding_done(lc->page)); ddjvu_document_get_pageinfo(lc->document, pagenum, &info); image->x_resolution = (float) info.dpi; image->y_resolution =(float) info.dpi; if (image_info->density != (char *) NULL) { int flags; GeometryInfo geometry_info; /* Set rendering resolution. */ flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; info.width=(int) (info.width*image->x_resolution/info.dpi); info.height=(int) (info.height*image->y_resolution/info.dpi); info.dpi=(int) MagickMax(image->x_resolution,image->y_resolution); } type = ddjvu_page_get_type(lc->page); /* double -> float! */ /* image->gamma = (float)ddjvu_page_get_gamma(lc->page); */ /* mmc: set image->depth */ /* mmc: This from the type */ image->columns=(size_t) info.width; image->rows=(size_t) info.height; /* mmc: bitonal should be palettized, and compressed! */ if (type == DDJVU_PAGETYPE_BITONAL){ image->colorspace = GRAYColorspace; image->storage_class = PseudoClass; image->depth = 8UL; /* i only support that? */ image->colors= 2; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } else { image->colorspace = RGBColorspace; image->storage_class = DirectClass; /* fixme: MAGICKCORE_QUANTUM_DEPTH ?*/ image->depth = 8UL; /* i only support that? */ image->matte = MagickTrue; /* is this useful? */ } #if DEBUG printf("now filling %.20g x %.20g\n",(double) image->columns,(double) image->rows); #endif #if 1 /* per_line */ /* q = QueueAuthenticPixels(image,0,0,image->columns,image->rows); */ get_page_image(lc, lc->page, 0, 0, info.width, info.height, image_info); #else int i; for (i = 0;i< image->rows; i++) { printf("%d\n",i); q = QueueAuthenticPixels(image,0,i,image->columns,1); get_page_line(lc, i, quantum_info); SyncAuthenticPixels(image); } #endif /* per_line */ #if DEBUG printf("END: finished filling %.20g x %.20g\n",(double) image->columns, (double) image->rows); #endif if (!image->ping) SyncImage(image); /* indexes=GetAuthenticIndexQueue(image); */ /* mmc: ??? Convert PNM pixels to runlength-encoded MIFF packets. */ /* image->colors = */ /* how is the line padding / stride? */ if (lc->page) { ddjvu_page_release(lc->page); lc->page = NULL; } /* image->page.y=mng_info->y_off[mng_info->object_id]; */ if (tag == 0) image=DestroyImage(image); return image; /* end of reading one DJVU page/image */ } Commit Message: CWE ID: CWE-119
static Image *ReadOneDJVUImage(LoadContext* lc,const int pagenum, const ImageInfo *image_info,ExceptionInfo *exception) { ddjvu_page_type_t type; ddjvu_pageinfo_t info; ddjvu_message_t *message; Image *image; int logging; int tag; MagickBooleanType status; /* so, we know that the page is there! Get its dimension, and */ /* Read one DJVU image */ image = lc->image; /* register PixelPacket *q; */ logging=LogMagickEvent(CoderEvent,GetMagickModule(), " enter ReadOneDJVUImage()"); (void) logging; #if DEBUG printf("==== Loading the page %d\n", pagenum); #endif lc->page = ddjvu_page_create_by_pageno(lc->document, pagenum); /* 0? */ /* pump data untill the page is ready for rendering. */ tag=(-1); do { while ((message = ddjvu_message_peek(lc->context))) { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } /* fixme: maybe exit? */ /* if (lc->error) break; */ message = pump_data_until_message(lc,image); if (message) do { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } while ((message = ddjvu_message_peek(lc->context))); } while (!ddjvu_page_decoding_done(lc->page)); ddjvu_document_get_pageinfo(lc->document, pagenum, &info); image->x_resolution = (float) info.dpi; image->y_resolution =(float) info.dpi; if (image_info->density != (char *) NULL) { int flags; GeometryInfo geometry_info; /* Set rendering resolution. */ flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; info.width=(int) (info.width*image->x_resolution/info.dpi); info.height=(int) (info.height*image->y_resolution/info.dpi); info.dpi=(int) MagickMax(image->x_resolution,image->y_resolution); } type = ddjvu_page_get_type(lc->page); /* double -> float! */ /* image->gamma = (float)ddjvu_page_get_gamma(lc->page); */ /* mmc: set image->depth */ /* mmc: This from the type */ image->columns=(size_t) info.width; image->rows=(size_t) info.height; /* mmc: bitonal should be palettized, and compressed! */ if (type == DDJVU_PAGETYPE_BITONAL){ image->colorspace = GRAYColorspace; image->storage_class = PseudoClass; image->depth = 8UL; /* i only support that? */ image->colors= 2; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } else { image->colorspace = RGBColorspace; image->storage_class = DirectClass; /* fixme: MAGICKCORE_QUANTUM_DEPTH ?*/ image->depth = 8UL; /* i only support that? */ image->matte = MagickTrue; /* is this useful? */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } #if DEBUG printf("now filling %.20g x %.20g\n",(double) image->columns,(double) image->rows); #endif #if 1 /* per_line */ /* q = QueueAuthenticPixels(image,0,0,image->columns,image->rows); */ get_page_image(lc, lc->page, 0, 0, info.width, info.height, image_info); #else int i; for (i = 0;i< image->rows; i++) { printf("%d\n",i); q = QueueAuthenticPixels(image,0,i,image->columns,1); get_page_line(lc, i, quantum_info); SyncAuthenticPixels(image); } #endif /* per_line */ #if DEBUG printf("END: finished filling %.20g x %.20g\n",(double) image->columns, (double) image->rows); #endif if (!image->ping) SyncImage(image); /* indexes=GetAuthenticIndexQueue(image); */ /* mmc: ??? Convert PNM pixels to runlength-encoded MIFF packets. */ /* image->colors = */ /* how is the line padding / stride? */ if (lc->page) { ddjvu_page_release(lc->page); lc->page = NULL; } /* image->page.y=mng_info->y_off[mng_info->object_id]; */ if (tag == 0) image=DestroyImage(image); return image; /* end of reading one DJVU page/image */ }
168,558
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int orangefs_set_acl(struct inode *inode, struct posix_acl *acl, int type) { struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode); int error = 0; void *value = NULL; size_t size = 0; const char *name = NULL; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { umode_t mode = inode->i_mode; /* * can we represent this with the traditional file * mode permission bits? */ error = posix_acl_equiv_mode(acl, &mode); if (error < 0) { gossip_err("%s: posix_acl_equiv_mode err: %d\n", __func__, error); return error; } if (inode->i_mode != mode) SetModeFlag(orangefs_inode); inode->i_mode = mode; mark_inode_dirty_sync(inode); if (error == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: gossip_err("%s: invalid type %d!\n", __func__, type); return -EINVAL; } gossip_debug(GOSSIP_ACL_DEBUG, "%s: inode %pU, key %s type %d\n", __func__, get_khandle_from_ino(inode), name, type); if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) return -ENOMEM; error = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (error < 0) goto out; } gossip_debug(GOSSIP_ACL_DEBUG, "%s: name %s, value %p, size %zd, acl %p\n", __func__, name, value, size, acl); /* * Go ahead and set the extended attribute now. NOTE: Suppose acl * was NULL, then value will be NULL and size will be 0 and that * will xlate to a removexattr. However, we don't want removexattr * complain if attributes does not exist. */ error = orangefs_inode_setxattr(inode, name, value, size, 0); out: kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
int orangefs_set_acl(struct inode *inode, struct posix_acl *acl, int type) { struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode); int error = 0; void *value = NULL; size_t size = 0; const char *name = NULL; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { umode_t mode; error = posix_acl_update_mode(inode, &mode, &acl); if (error) { gossip_err("%s: posix_acl_update_mode err: %d\n", __func__, error); return error; } if (inode->i_mode != mode) SetModeFlag(orangefs_inode); inode->i_mode = mode; mark_inode_dirty_sync(inode); } break; case ACL_TYPE_DEFAULT: name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: gossip_err("%s: invalid type %d!\n", __func__, type); return -EINVAL; } gossip_debug(GOSSIP_ACL_DEBUG, "%s: inode %pU, key %s type %d\n", __func__, get_khandle_from_ino(inode), name, type); if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) return -ENOMEM; error = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (error < 0) goto out; } gossip_debug(GOSSIP_ACL_DEBUG, "%s: name %s, value %p, size %zd, acl %p\n", __func__, name, value, size, acl); /* * Go ahead and set the extended attribute now. NOTE: Suppose acl * was NULL, then value will be NULL and size will be 0 and that * will xlate to a removexattr. However, we don't want removexattr * complain if attributes does not exist. */ error = orangefs_inode_setxattr(inode, name, value, size, 0); out: kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; }
166,977
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j, num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh = NULL, *dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p, *d; int al, i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4], kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type = s->s3->tmp.new_cipher->algorithm_mkey; cert = s->cert; buf = s->init_buf; r[0] = r[1] = r[2] = r[3] = NULL; n = 0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa = cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa = s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp = rsa; } if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0] = rsa->n; r[1] = rsa->e; s->s3->tmp.use_rsa_tmp = 1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kEDH) { dhp = cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp = s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (dhp == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((dh = DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } s->s3->tmp.dh = dh; if ((dhp->pub_key == NULL || dhp->priv_key == NULL || (s->options & SSL_OP_SINGLE_DH_USE))) { if (!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; r[2] = dh->pub_key; } else Commit Message: CWE ID: CWE-200
int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j, num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh = NULL, *dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p, *d; int al, i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4], kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type = s->s3->tmp.new_cipher->algorithm_mkey; cert = s->cert; buf = s->init_buf; r[0] = r[1] = r[2] = r[3] = NULL; n = 0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa = cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa = s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp = rsa; } if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0] = rsa->n; r[1] = rsa->e; s->s3->tmp.use_rsa_tmp = 1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kEDH) { dhp = cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp = s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (dhp == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((dh = DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } s->s3->tmp.dh = dh; if (!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } r[0] = dh->p; r[1] = dh->g; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; r[2] = dh->pub_key; } else
165,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_video::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { DEBUG_PRINT_LOW("FTB: buffer->pBuffer[%p]", buffer->pBuffer); if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: FTB in Invalid State"); return OMX_ErrorInvalidState; } if (buffer == NULL ||(buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Invalid buffer or size"); return OMX_ErrorBadParameter; } if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->OMX Version Invalid"); return OMX_ErrorVersionMismatch; } if (buffer->nOutputPortIndex != (OMX_U32)PORT_INDEX_OUT) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Bad port index"); return OMX_ErrorBadPortIndex; } if (!m_sOutPortDef.bEnabled) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->port is disabled"); return OMX_ErrorIncorrectStateOperation; } post_event((unsigned long) hComp, (unsigned long)buffer,OMX_COMPONENT_GENERATE_FTB); return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27903498 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVenc problem #3) CRs-Fixed: 1010088 Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3 CWE ID:
OMX_ERRORTYPE omx_video::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { DEBUG_PRINT_LOW("FTB: buffer->pBuffer[%p]", buffer->pBuffer); if (m_state != OMX_StateExecuting && m_state != OMX_StatePause && m_state != OMX_StateIdle) { DEBUG_PRINT_ERROR("ERROR: FTB in Invalid State"); return OMX_ErrorInvalidState; } if (buffer == NULL ||(buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Invalid buffer or size"); return OMX_ErrorBadParameter; } if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->OMX Version Invalid"); return OMX_ErrorVersionMismatch; } if (buffer->nOutputPortIndex != (OMX_U32)PORT_INDEX_OUT) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Bad port index"); return OMX_ErrorBadPortIndex; } if (!m_sOutPortDef.bEnabled) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->port is disabled"); return OMX_ErrorIncorrectStateOperation; } post_event((unsigned long) hComp, (unsigned long)buffer,OMX_COMPONENT_GENERATE_FTB); return OMX_ErrorNone; }
173,747
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jas_matrix_t *jas_matrix_copy(jas_matrix_t *x) { jas_matrix_t *y; int i; int j; y = jas_matrix_create(x->numrows_, x->numcols_); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
jas_matrix_t *jas_matrix_copy(jas_matrix_t *x) { jas_matrix_t *y; jas_matind_t i; jas_matind_t j; y = jas_matrix_create(x->numrows_, x->numcols_); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; }
168,702
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, WebGlobalObjectReusePolicy global_object_reuse_policy, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } const SecurityOrigin* previous_security_origin = nullptr; const ContentSecurityPolicy* previous_csp = nullptr; if (frame_->GetDocument()) { previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); previous_csp = frame_->GetDocument()->GetContentSecurityPolicy(); } if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithDocumentLoader(this) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext() .WithPreviousDocumentCSP(previous_csp), false); if (frame_->IsMainFrame()) frame_->ClearActivation(); if (frame_->HasReceivedUserGestureBeforeNavigation() != had_sticky_activation_) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document, previous_csp); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(global_object_reuse_policy); if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) { if (document->GetSettings() ->GetForceTouchEventFeatureDetectionForInspector()) { OriginTrialContext::FromOrCreate(document)->AddFeature( "ForceTouchEventFeatureDetectionForInspector"); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(http_names::kOriginTrial)); } bool stale_while_revalidate_enabled = origin_trials::StaleWhileRevalidateEnabled(document); fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled); if (stale_while_revalidate_enabled && !RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag()) UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled); parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding); ScriptableDocumentParser* scriptable_parser = parser_->AsScriptableDocumentParser(); if (scriptable_parser && GetResource()) { scriptable_parser->SetInlineScriptCacheHandler( ToRawResource(GetResource())->InlineScriptCacheHandler()); } WTF::String feature_policy( response_.HttpHeaderField(http_names::kFeaturePolicy)); MergeFeaturesFromOriginPolicy(feature_policy, request_.GetOriginPolicy()); document->ApplyFeaturePolicyFromHeader(feature_policy); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, WebGlobalObjectReusePolicy global_object_reuse_policy, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } const SecurityOrigin* previous_security_origin = nullptr; if (frame_->GetDocument()) { previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); } if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithDocumentLoader(this) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext(), false); if (frame_->IsMainFrame()) frame_->ClearActivation(); if (frame_->HasReceivedUserGestureBeforeNavigation() != had_sticky_activation_) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(global_object_reuse_policy); if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) { if (document->GetSettings() ->GetForceTouchEventFeatureDetectionForInspector()) { OriginTrialContext::FromOrCreate(document)->AddFeature( "ForceTouchEventFeatureDetectionForInspector"); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(http_names::kOriginTrial)); } bool stale_while_revalidate_enabled = origin_trials::StaleWhileRevalidateEnabled(document); fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled); if (stale_while_revalidate_enabled && !RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag()) UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled); parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding); ScriptableDocumentParser* scriptable_parser = parser_->AsScriptableDocumentParser(); if (scriptable_parser && GetResource()) { scriptable_parser->SetInlineScriptCacheHandler( ToRawResource(GetResource())->InlineScriptCacheHandler()); } WTF::String feature_policy( response_.HttpHeaderField(http_names::kFeaturePolicy)); MergeFeaturesFromOriginPolicy(feature_policy, request_.GetOriginPolicy()); document->ApplyFeaturePolicyFromHeader(feature_policy); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); }
173,057
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags) { int status = -1; BYTE descriptor; wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize); if (!stream) return -1; if (Stream_GetRemainingLength(stream) < 1) goto fail; Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */ if (descriptor == ZGFX_SEGMENTED_SINGLE) { if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream))) goto fail; *ppDstData = NULL; if (zgfx->OutputCount > 0) *ppDstData = (BYTE*) malloc(zgfx->OutputCount); if (!*ppDstData) goto fail; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); } else if (descriptor == ZGFX_SEGMENTED_MULTIPART) { UINT32 segmentSize; UINT16 segmentNumber; UINT16 segmentCount; UINT32 uncompressedSize; BYTE* pConcatenated; if (Stream_GetRemainingLength(stream) < 6) goto fail; Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */ Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */ if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32)) goto fail; pConcatenated = (BYTE*) malloc(uncompressedSize); if (!pConcatenated) goto fail; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++) { if (Stream_GetRemainingLength(stream) < sizeof(UINT32)) goto fail; Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */ if (!zgfx_decompress_segment(zgfx, stream, segmentSize)) goto fail; CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount); pConcatenated += zgfx->OutputCount; } } else { goto fail; } status = 1; fail: Stream_Free(stream, FALSE); return status; } Commit Message: Fixed CVE-2018-8785 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-119
int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags) { int status = -1; BYTE descriptor; wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize); if (!stream) return -1; if (Stream_GetRemainingLength(stream) < 1) goto fail; Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */ if (descriptor == ZGFX_SEGMENTED_SINGLE) { if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream))) goto fail; *ppDstData = NULL; if (zgfx->OutputCount > 0) *ppDstData = (BYTE*) malloc(zgfx->OutputCount); if (!*ppDstData) goto fail; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); } else if (descriptor == ZGFX_SEGMENTED_MULTIPART) { UINT32 segmentSize; UINT16 segmentNumber; UINT16 segmentCount; UINT32 uncompressedSize; BYTE* pConcatenated; size_t used = 0; if (Stream_GetRemainingLength(stream) < 6) goto fail; Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */ Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */ if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32)) goto fail; pConcatenated = (BYTE*) malloc(uncompressedSize); if (!pConcatenated) goto fail; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++) { if (Stream_GetRemainingLength(stream) < sizeof(UINT32)) goto fail; Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */ if (!zgfx_decompress_segment(zgfx, stream, segmentSize)) goto fail; if (zgfx->OutputCount > UINT32_MAX - used) goto fail; if (used + zgfx->OutputCount > uncompressedSize) goto fail; CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount); pConcatenated += zgfx->OutputCount; used += zgfx->OutputCount; } } else { goto fail; } status = 1; fail: Stream_Free(stream, FALSE); return status; }
169,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int php_stream_temp_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */ { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; switch(option) { case PHP_STREAM_OPTION_META_DATA_API: if (ts->meta) { zend_hash_copy(Z_ARRVAL_P((zval*)ptrparam), Z_ARRVAL_P(ts->meta), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*)); } return PHP_STREAM_OPTION_RETURN_OK; default: if (ts->innerstream) { return php_stream_set_option(ts->innerstream, option, value, ptrparam); } return PHP_STREAM_OPTION_RETURN_NOTIMPL; } } /* }}} */ Commit Message: CWE ID: CWE-20
static int php_stream_temp_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */ { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; switch(option) { case PHP_STREAM_OPTION_META_DATA_API: if (ts->meta) { zend_hash_copy(Z_ARRVAL_P((zval*)ptrparam), Z_ARRVAL_P(ts->meta), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*)); } return PHP_STREAM_OPTION_RETURN_OK; default: if (ts->innerstream) { return php_stream_set_option(ts->innerstream, option, value, ptrparam); } return PHP_STREAM_OPTION_RETURN_NOTIMPL; } } /* }}} */
165,482
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int MemBackendImpl::DoomEntriesBetween(Time initial_time, Time end_time, const CompletionCallback& callback) { if (end_time.is_null()) end_time = Time::Max(); DCHECK_GE(end_time, initial_time); base::LinkNode<MemEntryImpl>* node = lru_list_.head(); while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time) node = node->next(); while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) { MemEntryImpl* to_doom = node->value(); node = node->next(); to_doom->Doom(); } return net::OK; } Commit Message: [MemCache] Fix bug while iterating LRU list in range doom This is exact same thing as https://chromium-review.googlesource.com/c/chromium/src/+/987919 but on explicit mass-erase rather than eviction. Thanks to nedwilliamson@ (on gmail) for the report and testcase. Bug: 831963 Change-Id: I96a46700c1f058f7feebe038bcf983dc40eb7102 Reviewed-on: https://chromium-review.googlesource.com/1014023 Commit-Queue: Maks Orlovich <[email protected]> Reviewed-by: Josh Karlin <[email protected]> Cr-Commit-Position: refs/heads/master@{#551205} CWE ID: CWE-416
int MemBackendImpl::DoomEntriesBetween(Time initial_time, Time end_time, const CompletionCallback& callback) { if (end_time.is_null()) end_time = Time::Max(); DCHECK_GE(end_time, initial_time); base::LinkNode<MemEntryImpl>* node = lru_list_.head(); while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time) node = node->next(); while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) { MemEntryImpl* to_doom = node->value(); node = NextSkippingChildren(lru_list_, node); to_doom->Doom(); } return net::OK; }
173,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_uint_16(png_bytep buf) { png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) + (png_uint_16)(*(buf + 1))); return (i); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_uint_16(png_bytep buf) { png_uint_16 i = ((png_uint_16)((*(buf )) & 0xff) << 8) + ((png_uint_16)((*(buf + 1)) & 0xff) ); return (i); }
172,174
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: kex_input_newkeys(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; int r; debug("SSH2_MSG_NEWKEYS received"); ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error); if ((r = sshpkt_get_end(ssh)) != 0) return r; kex->done = 1; sshbuf_reset(kex->peer); /* sshbuf_reset(kex->my); */ kex->name = NULL; return 0; } Commit Message: CWE ID: CWE-476
kex_input_newkeys(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; int r; debug("SSH2_MSG_NEWKEYS received"); ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error); if ((r = sshpkt_get_end(ssh)) != 0) return r; if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0) return r; kex->done = 1; sshbuf_reset(kex->peer); /* sshbuf_reset(kex->my); */ kex->name = NULL; return 0; }
165,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) { ut64 addr = 0LL; struct symbol_t *symbols; int i; if (!(symbols = MACH0_(get_symbols) (bin))) { return 0; } for (i = 0; !symbols[i].last; i++) { if (!strcmp (symbols[i].name, "_main")) { addr = symbols[i].addr; break; } } free (symbols); if (!addr && bin->main_cmd.cmd == LC_MAIN) { addr = bin->entry + bin->baddr; } if (!addr) { ut8 b[128]; ut64 entry = addr_to_offset(bin, bin->entry); if (entry > bin->size || entry + sizeof (b) > bin->size) return 0; i = r_buf_read_at (bin->b, entry, b, sizeof (b)); if (i < 1) { return 0; } for (i = 0; i < 64; i++) { if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) { int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24); return bin->entry + i + 5 + delta; } } } return addr; } Commit Message: Fix null deref and uaf in mach0 parser CWE ID: CWE-416
ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) { ut64 addr = 0LL; struct symbol_t *symbols; int i; if (!(symbols = MACH0_(get_symbols) (bin))) { return 0; } for (i = 0; !symbols[i].last; i++) { if (!strcmp (symbols[i].name, "_main")) { addr = symbols[i].addr; break; } } free (symbols); if (!addr && bin->main_cmd.cmd == LC_MAIN) { addr = bin->entry + bin->baddr; } if (!addr) { ut8 b[128]; ut64 entry = addr_to_offset(bin, bin->entry); if (entry > bin->size || entry + sizeof (b) > bin->size) { return 0; } i = r_buf_read_at (bin->b, entry, b, sizeof (b)); if (i < 1) { return 0; } for (i = 0; i < 64; i++) { if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) { int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24); return bin->entry + i + 5 + delta; } } } return addr; }
168,235
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps, struct sock *sk, int tstype) { struct sk_buff *skb; bool tsonly; if (!sk) return; tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY; if (!skb_may_tx_timestamp(sk, tsonly)) return; if (tsonly) { #ifdef CONFIG_INET if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) && sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) skb = tcp_get_timestamping_opt_stats(sk); else #endif skb = alloc_skb(0, GFP_ATOMIC); } else { skb = skb_clone(orig_skb, GFP_ATOMIC); } if (!skb) return; if (tsonly) { skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags; skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey; } if (hwtstamps) *skb_hwtstamps(skb) = *hwtstamps; else skb->tstamp = ktime_get_real(); __skb_complete_tx_timestamp(skb, sk, tstype); } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
void __skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps, struct sock *sk, int tstype) { struct sk_buff *skb; bool tsonly, opt_stats = false; if (!sk) return; tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY; if (!skb_may_tx_timestamp(sk, tsonly)) return; if (tsonly) { #ifdef CONFIG_INET if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) && sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { skb = tcp_get_timestamping_opt_stats(sk); opt_stats = true; } else #endif skb = alloc_skb(0, GFP_ATOMIC); } else { skb = skb_clone(orig_skb, GFP_ATOMIC); } if (!skb) return; if (tsonly) { skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags; skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey; } if (hwtstamps) *skb_hwtstamps(skb) = *hwtstamps; else skb->tstamp = ktime_get_real(); __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats); }
170,072
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; unsigned long i; struct kvm_memory_slot *memslot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* Disallow changing a memory slot's size. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; for (i = 0; i < KVM_MEMORY_SLOTS; ++i) { struct kvm_memory_slot *s = &kvm->memslots->memslots[i]; if (s == memslot || !s->npages) continue; if (!((base_gfn + npages <= s->base_gfn) || (base_gfn >= s->base_gfn + s->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* Allocate if a slot is being created */ if (npages && !old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted * memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); /* * If the new memory slot is created, we need to clear all * mmio sptes. */ if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) kvm_arch_flush_shadow_all(kvm); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; } Commit Message: KVM: perform an invalid memslot step for gpa base change PPC must flush all translations before the new memory slot is visible. Signed-off-by: Marcelo Tosatti <[email protected]> Signed-off-by: Avi Kivity <[email protected]> CWE ID: CWE-399
int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; unsigned long i; struct kvm_memory_slot *memslot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* Disallow changing a memory slot's size. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; for (i = 0; i < KVM_MEMORY_SLOTS; ++i) { struct kvm_memory_slot *s = &kvm->memslots->memslots[i]; if (s == memslot || !s->npages) continue; if (!((base_gfn + npages <= s->base_gfn) || (base_gfn >= s->base_gfn + s->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* Allocate if a slot is being created */ if (npages && !old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); /* * If the new memory slot is created, we need to clear all * mmio sptes. */ if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) kvm_arch_flush_shadow_all(kvm); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; }
165,955
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cib_remote_msg(gpointer data) { const char *value = NULL; xmlNode *command = NULL; cib_client_t *client = data; crm_trace("%s callback", client->encrypted ? "secure" : "clear-text"); command = crm_recv_remote_msg(client->session, client->encrypted); if (command == NULL) { return -1; } value = crm_element_name(command); if (safe_str_neq(value, "cib_command")) { crm_log_xml_trace(command, "Bad command: "); goto bail; } if (client->name == NULL) { value = crm_element_value(command, F_CLIENTNAME); if (value == NULL) { client->name = strdup(client->id); } else { client->name = strdup(value); } } if (client->callback_id == NULL) { value = crm_element_value(command, F_CIB_CALLBACK_TOKEN); if (value != NULL) { client->callback_id = strdup(value); crm_trace("Callback channel for %s is %s", client->id, client->callback_id); } else { client->callback_id = strdup(client->id); } } /* unset dangerous options */ xml_remove_prop(command, F_ORIG); xml_remove_prop(command, F_CIB_HOST); xml_remove_prop(command, F_CIB_GLOBAL_UPDATE); crm_xml_add(command, F_TYPE, T_CIB); crm_xml_add(command, F_CIB_CLIENTID, client->id); crm_xml_add(command, F_CIB_CLIENTNAME, client->name); #if ENABLE_ACL crm_xml_add(command, F_CIB_USER, client->user); #endif if (crm_element_value(command, F_CIB_CALLID) == NULL) { char *call_uuid = crm_generate_uuid(); /* fix the command */ crm_xml_add(command, F_CIB_CALLID, call_uuid); free(call_uuid); } if (crm_element_value(command, F_CIB_CALLOPTS) == NULL) { crm_xml_add_int(command, F_CIB_CALLOPTS, 0); } crm_log_xml_trace(command, "Remote command: "); cib_common_callback_worker(0, 0, command, client, TRUE); bail: free_xml(command); command = NULL; return 0; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_remote_msg(gpointer data) static void cib_handle_remote_msg(cib_client_t *client, xmlNode *command) { const char *value = NULL; value = crm_element_name(command); if (safe_str_neq(value, "cib_command")) { crm_log_xml_trace(command, "Bad command: "); return; } if (client->name == NULL) { value = crm_element_value(command, F_CLIENTNAME); if (value == NULL) { client->name = strdup(client->id); } else { client->name = strdup(value); } } if (client->callback_id == NULL) { value = crm_element_value(command, F_CIB_CALLBACK_TOKEN); if (value != NULL) { client->callback_id = strdup(value); crm_trace("Callback channel for %s is %s", client->id, client->callback_id); } else { client->callback_id = strdup(client->id); } } /* unset dangerous options */ xml_remove_prop(command, F_ORIG); xml_remove_prop(command, F_CIB_HOST); xml_remove_prop(command, F_CIB_GLOBAL_UPDATE); crm_xml_add(command, F_TYPE, T_CIB); crm_xml_add(command, F_CIB_CLIENTID, client->id); crm_xml_add(command, F_CIB_CLIENTNAME, client->name); #if ENABLE_ACL crm_xml_add(command, F_CIB_USER, client->user); #endif if (crm_element_value(command, F_CIB_CALLID) == NULL) { char *call_uuid = crm_generate_uuid(); /* fix the command */ crm_xml_add(command, F_CIB_CALLID, call_uuid); free(call_uuid); } if (crm_element_value(command, F_CIB_CALLOPTS) == NULL) { crm_xml_add_int(command, F_CIB_CALLOPTS, 0); } crm_log_xml_trace(command, "Remote command: "); cib_common_callback_worker(0, 0, command, client, TRUE); } int cib_remote_msg(gpointer data) { xmlNode *command = NULL; cib_client_t *client = data; int disconnected = 0; int timeout = client->remote_auth ? -1 : 1000; crm_trace("%s callback", client->encrypted ? "secure" : "clear-text"); #ifdef HAVE_GNUTLS_GNUTLS_H if (client->encrypted && (client->handshake_complete == FALSE)) { int rc = 0; /* Muliple calls to handshake will be required, this callback * will be invoked once the client sends more handshake data. */ do { rc = gnutls_handshake(*client->session); if (rc < 0 && rc != GNUTLS_E_AGAIN) { crm_err("Remote cib tls handshake failed"); return -1; } } while (rc == GNUTLS_E_INTERRUPTED); if (rc == 0) { crm_debug("Remote cib tls handshake completed"); client->handshake_complete = TRUE; if (client->remote_auth_timeout) { g_source_remove(client->remote_auth_timeout); } /* after handshake, clients must send auth in a few seconds */ client->remote_auth_timeout = g_timeout_add(REMOTE_AUTH_TIMEOUT, remote_auth_timeout_cb, client); } return 0; } #endif crm_recv_remote_msg(client->session, &client->recv_buf, client->encrypted, timeout, &disconnected); /* must pass auth before we will process anything else */ if (client->remote_auth == FALSE) { xmlNode *reg; #if ENABLE_ACL const char *user = NULL; #endif command = crm_parse_remote_buffer(&client->recv_buf); if (cib_remote_auth(command) == FALSE) { free_xml(command); return -1; } crm_debug("remote connection authenticated successfully"); client->remote_auth = TRUE; g_source_remove(client->remote_auth_timeout); client->remote_auth_timeout = 0; client->name = crm_element_value_copy(command, "name"); #if ENABLE_ACL user = crm_element_value(command, "user"); if (user) { new_client->user = strdup(user); } #endif /* send ACK */ reg = create_xml_node(NULL, "cib_result"); crm_xml_add(reg, F_CIB_OPERATION, CRM_OP_REGISTER); crm_xml_add(reg, F_CIB_CLIENTID, client->id); crm_send_remote_msg(client->session, reg, client->encrypted); free_xml(reg); free_xml(command); } command = crm_parse_remote_buffer(&client->recv_buf); while (command) { crm_trace("command received"); cib_handle_remote_msg(client, command); free_xml(command); command = crm_parse_remote_buffer(&client->recv_buf); } if (disconnected) { crm_trace("disconnected while receiving remote cib msg."); return -1; } return 0; }
166,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( const ClientOAuthResult& result, Profile* profile, Profile::CreateStatus status) { if (is_force_sign_in_with_usermanager_) UnlockProfileAndHideLoginUI(profile_->GetPath(), handler_.get()); Browser* browser = NULL; if (handler_) { browser = handler_->GetDesktopBrowser(); } AboutSigninInternals* about_signin_internals = AboutSigninInternalsFactory::GetForProfile(profile_); about_signin_internals->OnRefreshTokenReceived("Successful"); std::string account_id = AccountTrackerServiceFactory::GetForProfile(profile_) ->SeedAccountInfo(gaia_id_, email_); signin_metrics::AccessPoint access_point = signin::GetAccessPointForPromoURL(current_url_); signin_metrics::Reason reason = signin::GetSigninReasonForPromoURL(current_url_); SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_); std::string primary_email = signin_manager->GetAuthenticatedAccountInfo().email; if (gaia::AreEmailsSame(email_, primary_email) && (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || reason == signin_metrics::Reason::REASON_UNLOCK) && !password_.empty() && profiles::IsLockAvailable(profile_)) { LocalAuth::SetLocalAuthCredentials(profile_, password_); } #if defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED) if (!password_.empty()) { scoped_refptr<password_manager::PasswordStore> password_store = PasswordStoreFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS); if (password_store && !primary_email.empty()) { password_store->SaveGaiaPasswordHash( primary_email, base::UTF8ToUTF16(password_), password_manager::metrics_util::SyncPasswordHashChange:: SAVED_ON_CHROME_SIGNIN); } } #endif if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || reason == signin_metrics::Reason::REASON_UNLOCK || reason == signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT) { ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)-> UpdateCredentials(account_id, result.refresh_token); if (signin::IsAutoCloseEnabledInURL(current_url_)) { bool show_account_management = ShouldShowAccountManagement( current_url_, AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile_)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&InlineLoginHandlerImpl::CloseTab, handler_, show_account_management)); } if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || reason == signin_metrics::Reason::REASON_UNLOCK) { signin_manager->MergeSigninCredentialIntoCookieJar(); } LogSigninReason(reason); } else { browser_sync::ProfileSyncService* sync_service = ProfileSyncServiceFactory::GetForProfile(profile_); SigninErrorController* error_controller = SigninErrorControllerFactory::GetForProfile(profile_); OneClickSigninSyncStarter::StartSyncMode start_mode = OneClickSigninSyncStarter::CONFIRM_SYNC_SETTINGS_FIRST; if (access_point == signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS || choose_what_to_sync_) { bool show_settings_without_configure = error_controller->HasError() && sync_service && sync_service->IsFirstSetupComplete(); if (!show_settings_without_configure) start_mode = OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST; } OneClickSigninSyncStarter::ConfirmationRequired confirmation_required = confirm_untrusted_signin_ ? OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN : OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN; bool start_signin = !HandleCrossAccountError( result.refresh_token, confirmation_required, start_mode); if (start_signin) { CreateSyncStarter(browser, current_url_, result.refresh_token, OneClickSigninSyncStarter::CURRENT_PROFILE, start_mode, confirmation_required); base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } } } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} CWE ID: CWE-20
void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( const ClientOAuthResult& result, Profile* profile, Profile::CreateStatus status) { if (is_force_sign_in_with_usermanager_) UnlockProfileAndHideLoginUI(profile_->GetPath(), handler_.get()); Browser* browser = NULL; if (handler_) { browser = handler_->GetDesktopBrowser(); } AboutSigninInternals* about_signin_internals = AboutSigninInternalsFactory::GetForProfile(profile_); about_signin_internals->OnRefreshTokenReceived("Successful"); std::string account_id = AccountTrackerServiceFactory::GetForProfile(profile_) ->SeedAccountInfo(gaia_id_, email_); signin_metrics::AccessPoint access_point = signin::GetAccessPointForPromoURL(current_url_); signin_metrics::Reason reason = signin::GetSigninReasonForPromoURL(current_url_); SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_); std::string primary_email = signin_manager->GetAuthenticatedAccountInfo().email; if (gaia::AreEmailsSame(email_, primary_email) && (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || reason == signin_metrics::Reason::REASON_UNLOCK) && !password_.empty() && profiles::IsLockAvailable(profile_)) { LocalAuth::SetLocalAuthCredentials(profile_, password_); } #if defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED) if (!password_.empty()) { scoped_refptr<password_manager::PasswordStore> password_store = PasswordStoreFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS); if (password_store && !primary_email.empty()) { password_store->SaveGaiaPasswordHash( primary_email, base::UTF8ToUTF16(password_), password_manager::metrics_util::SyncPasswordHashChange:: SAVED_ON_CHROME_SIGNIN); } } #endif if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || reason == signin_metrics::Reason::REASON_UNLOCK || reason == signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT) { ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) ->UpdateCredentials(account_id, result.refresh_token, signin_metrics::SourceForRefreshTokenOperation:: kInlineLoginHandler_Signin); if (signin::IsAutoCloseEnabledInURL(current_url_)) { bool show_account_management = ShouldShowAccountManagement( current_url_, AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile_)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&InlineLoginHandlerImpl::CloseTab, handler_, show_account_management)); } if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || reason == signin_metrics::Reason::REASON_UNLOCK) { signin_manager->MergeSigninCredentialIntoCookieJar(); } LogSigninReason(reason); } else { browser_sync::ProfileSyncService* sync_service = ProfileSyncServiceFactory::GetForProfile(profile_); SigninErrorController* error_controller = SigninErrorControllerFactory::GetForProfile(profile_); OneClickSigninSyncStarter::StartSyncMode start_mode = OneClickSigninSyncStarter::CONFIRM_SYNC_SETTINGS_FIRST; if (access_point == signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS || choose_what_to_sync_) { bool show_settings_without_configure = error_controller->HasError() && sync_service && sync_service->IsFirstSetupComplete(); if (!show_settings_without_configure) start_mode = OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST; } OneClickSigninSyncStarter::ConfirmationRequired confirmation_required = confirm_untrusted_signin_ ? OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN : OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN; bool start_signin = !HandleCrossAccountError( result.refresh_token, confirmation_required, start_mode); if (start_signin) { CreateSyncStarter(browser, current_url_, result.refresh_token, OneClickSigninSyncStarter::CURRENT_PROFILE, start_mode, confirmation_required); base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } } }
172,575
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct file *path_openat(int dfd, struct filename *pathname, struct nameidata *nd, const struct open_flags *op, int flags) { struct file *file; struct path path; int opened = 0; int error; file = get_empty_filp(); if (IS_ERR(file)) return file; file->f_flags = op->open_flag; if (unlikely(file->f_flags & __O_TMPFILE)) { error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened); goto out; } error = path_init(dfd, pathname, flags, nd); if (unlikely(error)) goto out; error = do_last(nd, &path, file, op, &opened, pathname); while (unlikely(error > 0)) { /* trailing symlink */ struct path link = path; void *cookie; if (!(nd->flags & LOOKUP_FOLLOW)) { path_put_conditional(&path, nd); path_put(&nd->path); error = -ELOOP; break; } error = may_follow_link(&link, nd); if (unlikely(error)) break; nd->flags |= LOOKUP_PARENT; nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL); error = follow_link(&link, nd, &cookie); if (unlikely(error)) break; error = do_last(nd, &path, file, op, &opened, pathname); put_link(nd, &link, cookie); } out: path_cleanup(nd); if (!(opened & FILE_OPENED)) { BUG_ON(!error); put_filp(file); } if (unlikely(error)) { if (error == -EOPENSTALE) { if (flags & LOOKUP_RCU) error = -ECHILD; else error = -ESTALE; } file = ERR_PTR(error); } return file; } Commit Message: path_openat(): fix double fput() path_openat() jumps to the wrong place after do_tmpfile() - it has already done path_cleanup() (as part of path_lookupat() called by do_tmpfile()), so doing that again can lead to double fput(). Cc: [email protected] # v3.11+ Signed-off-by: Al Viro <[email protected]> CWE ID:
static struct file *path_openat(int dfd, struct filename *pathname, struct nameidata *nd, const struct open_flags *op, int flags) { struct file *file; struct path path; int opened = 0; int error; file = get_empty_filp(); if (IS_ERR(file)) return file; file->f_flags = op->open_flag; if (unlikely(file->f_flags & __O_TMPFILE)) { error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened); goto out2; } error = path_init(dfd, pathname, flags, nd); if (unlikely(error)) goto out; error = do_last(nd, &path, file, op, &opened, pathname); while (unlikely(error > 0)) { /* trailing symlink */ struct path link = path; void *cookie; if (!(nd->flags & LOOKUP_FOLLOW)) { path_put_conditional(&path, nd); path_put(&nd->path); error = -ELOOP; break; } error = may_follow_link(&link, nd); if (unlikely(error)) break; nd->flags |= LOOKUP_PARENT; nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL); error = follow_link(&link, nd, &cookie); if (unlikely(error)) break; error = do_last(nd, &path, file, op, &opened, pathname); put_link(nd, &link, cookie); } out: path_cleanup(nd); out2: if (!(opened & FILE_OPENED)) { BUG_ON(!error); put_filp(file); } if (unlikely(error)) { if (error == -EOPENSTALE) { if (flags & LOOKUP_RCU) error = -ECHILD; else error = -ESTALE; } file = ERR_PTR(error); } return file; }
166,594
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(interstitial_page); render_manager_.set_interstitial_page(interstitial_page); FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidAttachInterstitialPage()); } Commit Message: Cancel JavaScript dialogs when an interstitial appears. BUG=295695 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/24360011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(interstitial_page); render_manager_.set_interstitial_page(interstitial_page); // Cancel any visible dialogs so that they don't interfere with the // interstitial. if (dialog_manager_) dialog_manager_->CancelActiveAndPendingDialogs(this); FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidAttachInterstitialPage()); }
171,160
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur); } ret = inputPush(ctxt, input); GROW; return(ret); } 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
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur); } ret = inputPush(ctxt, input); if (ctxt->instate == XML_PARSER_EOF) return(-1); GROW; return(ret); }
171,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( const ModelTypeSet enabled_types) { if (initialized_ && enabled_types.Has(syncable::SESSIONS)) { WriteTransaction trans(FROM_HERE, GetUserShare()); WriteNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { LOG(WARNING) << "Unable to set 'sync_tabs' bit because Nigori node not " << "found."; return; } sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics()); specifics.set_sync_tabs(true); node.SetNigoriSpecifics(specifics); } } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( }
170,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WallpaperManagerBase::GetCustomWallpaperInternal( const AccountId& account_id, const WallpaperInfo& info, const base::FilePath& wallpaper_path, bool update_wallpaper, const scoped_refptr<base::SingleThreadTaskRunner>& reply_task_runner, MovableOnDestroyCallbackHolder on_finish, base::WeakPtr<WallpaperManagerBase> weak_ptr) { base::FilePath valid_path = wallpaper_path; if (!base::PathExists(wallpaper_path)) { valid_path = GetCustomWallpaperDir(kOriginalWallpaperSubDir); valid_path = valid_path.Append(info.location); } if (!base::PathExists(valid_path)) { LOG(ERROR) << "Failed to load custom wallpaper from its original fallback " "file path: " << valid_path.value(); const std::string& old_path = account_id.GetUserEmail(); // Migrated valid_path = GetCustomWallpaperPath(kOriginalWallpaperSubDir, WallpaperFilesId::FromString(old_path), info.location); } if (!base::PathExists(valid_path)) { LOG(ERROR) << "Failed to load previously selected custom wallpaper. " << "Fallback to default wallpaper. Expected wallpaper path: " << wallpaper_path.value(); reply_task_runner->PostTask( FROM_HERE, base::Bind(&WallpaperManagerBase::DoSetDefaultWallpaper, weak_ptr, account_id, base::Passed(std::move(on_finish)))); } else { reply_task_runner->PostTask( FROM_HERE, base::Bind(&WallpaperManagerBase::StartLoad, weak_ptr, account_id, info, update_wallpaper, valid_path, base::Passed(std::move(on_finish)))); } } Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982} CWE ID: CWE-200
void WallpaperManagerBase::GetCustomWallpaperInternal( const AccountId& account_id, const WallpaperInfo& info, const base::FilePath& wallpaper_path, bool update_wallpaper, const scoped_refptr<base::SingleThreadTaskRunner>& reply_task_runner, MovableOnDestroyCallbackHolder on_finish, base::WeakPtr<WallpaperManagerBase> weak_ptr) { base::FilePath valid_path = wallpaper_path; if (!base::PathExists(wallpaper_path)) { valid_path = GetCustomWallpaperDir(kOriginalWallpaperSubDir); valid_path = valid_path.Append(info.location); } if (!base::PathExists(valid_path)) { const std::string& old_path = account_id.GetUserEmail(); // Migrated valid_path = GetCustomWallpaperPath(kOriginalWallpaperSubDir, WallpaperFilesId::FromString(old_path), info.location); } if (!base::PathExists(valid_path)) { reply_task_runner->PostTask( FROM_HERE, base::Bind(&WallpaperManagerBase::OnCustomWallpaperFileNotFound, weak_ptr, account_id, wallpaper_path, update_wallpaper, base::Passed(std::move(on_finish)))); } else { reply_task_runner->PostTask( FROM_HERE, base::Bind(&WallpaperManagerBase::StartLoad, weak_ptr, account_id, info, update_wallpaper, valid_path, base::Passed(std::move(on_finish)))); } }
171,972
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int TestOpenProcess(DWORD process_id) { HANDLE process = ::OpenProcess(PROCESS_VM_READ, FALSE, // Do not inherit handle. process_id); if (NULL == process) { if (ERROR_ACCESS_DENIED == ::GetLastError()) { return SBOX_TEST_DENIED; } else { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } } else { ::CloseHandle(process); return SBOX_TEST_SUCCEEDED; } } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
int TestOpenProcess(DWORD process_id) { int TestOpenProcess(DWORD process_id, DWORD access_mask) { HANDLE process = ::OpenProcess(access_mask, FALSE, // Do not inherit handle. process_id); if (NULL == process) { if (ERROR_ACCESS_DENIED == ::GetLastError()) { return SBOX_TEST_DENIED; } else { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } } else { ::CloseHandle(process); return SBOX_TEST_SUCCEEDED; } }
170,915
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl2_generate_key_material(SSL *s) { unsigned int i; EVP_MD_CTX ctx; unsigned char *km; unsigned char c = '0'; const EVP_MD *md5; int md_size; md5 = EVP_md5(); # ifdef CHARSET_EBCDIC c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see * SSLv2 docu */ # endif EVP_MD_CTX_init(&ctx); km = s->s2->key_material; if (s->session->master_key_length < 0 || s->session->master_key_length > (int)sizeof(s->session->master_key)) { SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } md_size = EVP_MD_size(md5); if (md_size < 0) return 0; for (i = 0; i < s->s2->key_material_length; i += md_size) { if (((km - s->s2->key_material) + md_size) > (int)sizeof(s->s2->key_material)) { /* * EVP_DigestFinal_ex() below would write beyond buffer */ SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } EVP_DigestInit_ex(&ctx, md5, NULL); OPENSSL_assert(s->session->master_key_length >= 0 && s->session->master_key_length < (int)sizeof(s->session->master_key)); EVP_DigestUpdate(&ctx, s->session->master_key, s->session->master_key_length); EVP_DigestUpdate(&ctx, &c, 1); c++; EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length); EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length); EVP_DigestFinal_ex(&ctx, km, NULL); km += md_size; } EVP_MD_CTX_cleanup(&ctx); return 1; } Commit Message: CWE ID: CWE-20
int ssl2_generate_key_material(SSL *s) { unsigned int i; EVP_MD_CTX ctx; unsigned char *km; unsigned char c = '0'; const EVP_MD *md5; int md_size; md5 = EVP_md5(); # ifdef CHARSET_EBCDIC c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see * SSLv2 docu */ # endif EVP_MD_CTX_init(&ctx); km = s->s2->key_material; if (s->session->master_key_length < 0 || s->session->master_key_length > (int)sizeof(s->session->master_key)) { SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } md_size = EVP_MD_size(md5); if (md_size < 0) return 0; for (i = 0; i < s->s2->key_material_length; i += md_size) { if (((km - s->s2->key_material) + md_size) > (int)sizeof(s->s2->key_material)) { /* * EVP_DigestFinal_ex() below would write beyond buffer */ SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } EVP_DigestInit_ex(&ctx, md5, NULL); OPENSSL_assert(s->session->master_key_length >= 0 && s->session->master_key_length <= (int)sizeof(s->session->master_key)); EVP_DigestUpdate(&ctx, s->session->master_key, s->session->master_key_length); EVP_DigestUpdate(&ctx, &c, 1); c++; EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length); EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length); EVP_DigestFinal_ex(&ctx, km, NULL); km += md_size; } EVP_MD_CTX_cleanup(&ctx); return 1; }
164,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; vpx_codec_err_t res; VpxVideoReader *reader = NULL; const VpxInterface *decoder = NULL; const VpxVideoInfo *info = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->interface())); res = vpx_codec_dec_init(&codec, decoder->interface(), NULL, VPX_CODEC_USE_POSTPROC); if (res == VPX_CODEC_INCAPABLE) die_codec(&codec, "Postproc not supported by this decoder."); if (res) die_codec(&codec, "Failed to initialize decoder."); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); ++frame_cnt; if (frame_cnt % 30 == 1) { vp8_postproc_cfg_t pp = {0, 0, 0}; if (vpx_codec_control(&codec, VP8_SET_POSTPROC, &pp)) die_codec(&codec, "Failed to turn off postproc."); } else if (frame_cnt % 30 == 16) { vp8_postproc_cfg_t pp = {VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE, 4, 0}; if (vpx_codec_control(&codec, VP8_SET_POSTPROC, &pp)) die_codec(&codec, "Failed to turn on postproc."); }; if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 15000)) die_codec(&codec, "Failed to decode frame"); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { vpx_img_write(img, outfile); } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec"); printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n", info->frame_width, info->frame_height, argv[2]); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; vpx_codec_err_t res; VpxVideoReader *reader = NULL; const VpxInterface *decoder = NULL; const VpxVideoInfo *info = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface())); res = vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL, VPX_CODEC_USE_POSTPROC); if (res == VPX_CODEC_INCAPABLE) die_codec(&codec, "Postproc not supported by this decoder."); if (res) die_codec(&codec, "Failed to initialize decoder."); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); ++frame_cnt; if (frame_cnt % 30 == 1) { vp8_postproc_cfg_t pp = {0, 0, 0}; if (vpx_codec_control(&codec, VP8_SET_POSTPROC, &pp)) die_codec(&codec, "Failed to turn off postproc."); } else if (frame_cnt % 30 == 16) { vp8_postproc_cfg_t pp = {VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE, 4, 0}; if (vpx_codec_control(&codec, VP8_SET_POSTPROC, &pp)) die_codec(&codec, "Failed to turn on postproc."); }; if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 15000)) die_codec(&codec, "Failed to decode frame"); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { vpx_img_write(img, outfile); } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec"); printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n", info->frame_width, info->frame_height, argv[2]); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; }
174,478
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MimeHandlerViewContainer::OnReady() { if (!render_frame() || !is_embedded_) return; blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); blink::WebAssociatedURLLoaderOptions options; DCHECK(!loader_); loader_.reset(frame->CreateAssociatedURLLoader(options)); blink::WebURLRequest request(original_url_); request.SetRequestContext(blink::WebURLRequest::kRequestContextObject); loader_->LoadAsynchronously(request, this); } Commit Message: Skip Service workers in requests for mime handler plugins BUG=808838 TEST=./browser_tests --gtest_filter=*/ServiceWorkerTest.MimeHandlerView* Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: I82e75c200091babbab648a04232db47e2938d914 Reviewed-on: https://chromium-review.googlesource.com/914150 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Istiaque Ahmed <[email protected]> Reviewed-by: Matt Falkenhagen <[email protected]> Cr-Commit-Position: refs/heads/master@{#537386} CWE ID: CWE-20
void MimeHandlerViewContainer::OnReady() { if (!render_frame() || !is_embedded_) return; blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); blink::WebAssociatedURLLoaderOptions options; DCHECK(!loader_); loader_.reset(frame->CreateAssociatedURLLoader(options)); blink::WebURLRequest request(original_url_); request.SetRequestContext(blink::WebURLRequest::kRequestContextObject); // The plugin resource request should skip service workers since "plug-ins // may get their security origins from their own urls". // https://w3c.github.io/ServiceWorker/#implementer-concerns request.SetServiceWorkerMode(blink::WebURLRequest::ServiceWorkerMode::kNone); loader_->LoadAsynchronously(request, this); }
172,702
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: make_error(png_store* volatile psIn, png_byte PNG_CONST colour_type, png_byte bit_depth, int interlace_type, int test, png_const_charp name) { png_store * volatile ps = psIn; context(ps, fault); check_interlace_type(interlace_type); Try { png_structp pp; png_infop pi; pp = set_store_for_write(ps, &pi, name); if (pp == NULL) Throw ps; png_set_IHDR(pp, pi, transform_width(pp, colour_type, bit_depth), transform_height(pp, colour_type, bit_depth), bit_depth, colour_type, interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/); /* Time for a few errors; these are in various optional chunks, the * standard tests test the standard chunks pretty well. */ # define exception__prev exception_prev_1 # define exception__env exception_env_1 Try { /* Expect this to throw: */ ps->expect_error = !error_test[test].warning; ps->expect_warning = error_test[test].warning; ps->saw_warning = 0; error_test[test].fn(pp, pi); /* Normally the error is only detected here: */ png_write_info(pp, pi); /* And handle the case where it was only a warning: */ if (ps->expect_warning && ps->saw_warning) Throw ps; /* If we get here there is a problem, we have success - no error or * no warning - when we shouldn't have success. Log an error. */ store_log(ps, pp, error_test[test].msg, 1 /*error*/); } Catch (fault) ps = fault; /* expected exit, make sure ps is not clobbered */ #undef exception__prev #undef exception__env /* And clear these flags */ ps->expect_error = 0; ps->expect_warning = 0; /* Now write the whole image, just to make sure that the detected, or * undetected, errro has not created problems inside libpng. */ if (png_get_rowbytes(pp, pi) != transform_rowsize(pp, colour_type, bit_depth)) png_error(pp, "row size incorrect"); else { png_uint_32 h = transform_height(pp, colour_type, bit_depth); int npasses = png_set_interlace_handling(pp); int pass; if (npasses != npasses_from_interlace_type(pp, interlace_type)) png_error(pp, "write: png_set_interlace_handling failed"); for (pass=0; pass<npasses; ++pass) { png_uint_32 y; for (y=0; y<h; ++y) { png_byte buffer[TRANSFORM_ROWMAX]; transform_row(pp, buffer, colour_type, bit_depth, y); png_write_row(pp, buffer); } } } png_write_end(pp, pi); /* The following deletes the file that was just written. */ store_write_reset(ps); } Catch(fault) { store_write_reset(fault); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
make_error(png_store* volatile psIn, png_byte PNG_CONST colour_type, make_error(png_store* const ps, png_byte const colour_type, png_byte bit_depth, int interlace_type, int test, png_const_charp name) { context(ps, fault); check_interlace_type(interlace_type); Try { png_infop pi; const png_structp pp = set_store_for_write(ps, &pi, name); png_uint_32 w, h; gnu_volatile(pp) if (pp == NULL) Throw ps; w = transform_width(pp, colour_type, bit_depth); gnu_volatile(w) h = transform_height(pp, colour_type, bit_depth); gnu_volatile(h) png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/); /* Time for a few errors; these are in various optional chunks, the * standard tests test the standard chunks pretty well. */ # define exception__prev exception_prev_1 # define exception__env exception_env_1 Try { gnu_volatile(exception__prev) /* Expect this to throw: */ ps->expect_error = !error_test[test].warning; ps->expect_warning = error_test[test].warning; ps->saw_warning = 0; error_test[test].fn(pp, pi); /* Normally the error is only detected here: */ png_write_info(pp, pi); /* And handle the case where it was only a warning: */ if (ps->expect_warning && ps->saw_warning) Throw ps; /* If we get here there is a problem, we have success - no error or * no warning - when we shouldn't have success. Log an error. */ store_log(ps, pp, error_test[test].msg, 1 /*error*/); } Catch (fault) { /* expected exit */ } #undef exception__prev #undef exception__env /* And clear these flags */ ps->expect_error = 0; ps->expect_warning = 0; /* Now write the whole image, just to make sure that the detected, or * undetected, errro has not created problems inside libpng. */ if (png_get_rowbytes(pp, pi) != transform_rowsize(pp, colour_type, bit_depth)) png_error(pp, "row size incorrect"); else { int npasses = set_write_interlace_handling(pp, interlace_type); int pass; if (npasses != npasses_from_interlace_type(pp, interlace_type)) png_error(pp, "write: png_set_interlace_handling failed"); for (pass=0; pass<npasses; ++pass) { png_uint_32 y; for (y=0; y<h; ++y) { png_byte buffer[TRANSFORM_ROWMAX]; transform_row(pp, buffer, colour_type, bit_depth, y); # if do_own_interlace /* If do_own_interlace *and* the image is interlaced we need a * reduced interlace row; this may be reduced to empty. */ if (interlace_type == PNG_INTERLACE_ADAM7) { /* The row must not be written if it doesn't exist, notice * that there are two conditions here, either the row isn't * ever in the pass or the row would be but isn't wide * enough to contribute any pixels. In fact the wPass test * can be used to skip the whole y loop in this case. */ if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && PNG_PASS_COLS(w, pass) > 0) interlace_row(buffer, buffer, bit_size(pp, colour_type, bit_depth), w, pass, 0/*data always bigendian*/); else continue; } # endif /* do_own_interlace */ png_write_row(pp, buffer); } } } png_write_end(pp, pi); /* The following deletes the file that was just written. */ store_write_reset(ps); } Catch(fault) { store_write_reset(fault); } }
173,661
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int em_ret(struct x86_emulate_ctxt *ctxt) { ctxt->dst.type = OP_REG; ctxt->dst.addr.reg = &ctxt->_eip; ctxt->dst.bytes = ctxt->op_bytes; return em_pop(ctxt); } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static int em_ret(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long eip; rc = emulate_pop(ctxt, &eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; return assign_eip_near(ctxt, eip); }
169,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_strip_alpha(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this, image_transform_png_set_strip_alpha_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_strip_alpha(pp); this->next->set(this->next, that, pp, pi); }
173,653
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *d) { struct cx24116_state *state = fe->demodulator_priv; int i, ret; /* Dump DiSEqC message */ if (debug) { printk(KERN_INFO "cx24116: %s(", __func__); for (i = 0 ; i < d->msg_len ;) { printk(KERN_INFO "0x%02x", d->msg[i]); if (++i < d->msg_len) printk(KERN_INFO ", "); } printk(") toneburst=%d\n", toneburst); } /* Validate length */ if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS)) return -EINVAL; /* DiSEqC message */ for (i = 0; i < d->msg_len; i++) state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i]; /* DiSEqC message length */ state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len; /* Command length */ state->dsec_cmd.len = CX24116_DISEQC_MSGOFS + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN]; /* DiSEqC toneburst */ if (toneburst == CX24116_DISEQC_MESGCACHE) /* Message is cached */ return 0; else if (toneburst == CX24116_DISEQC_TONEOFF) /* Message is sent without burst */ state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0; else if (toneburst == CX24116_DISEQC_TONECACHE) { /* * Message is sent with derived else cached burst * * WRITE PORT GROUP COMMAND 38 * * 0/A/A: E0 10 38 F0..F3 * 1/B/B: E0 10 38 F4..F7 * 2/C/A: E0 10 38 F8..FB * 3/D/B: E0 10 38 FC..FF * * databyte[3]= 8421:8421 * ABCD:WXYZ * CLR :SET * * WX= PORT SELECT 0..3 (X=TONEBURST) * Y = VOLTAGE (0=13V, 1=18V) * Z = BAND (0=LOW, 1=HIGH(22K)) */ if (d->msg_len >= 4 && d->msg[2] == 0x38) state->dsec_cmd.args[CX24116_DISEQC_BURST] = ((d->msg[3] & 4) >> 2); if (debug) dprintk("%s burst=%d\n", __func__, state->dsec_cmd.args[CX24116_DISEQC_BURST]); } /* Wait for LNB ready */ ret = cx24116_wait_for_lnb(fe); if (ret != 0) return ret; /* Wait for voltage/min repeat delay */ msleep(100); /* Command */ ret = cx24116_cmd_execute(fe, &state->dsec_cmd); if (ret != 0) return ret; /* * Wait for send * * Eutelsat spec: * >15ms delay + (XXX determine if FW does this, see set_tone) * 13.5ms per byte + * >15ms delay + * 12.5ms burst + * >15ms delay (XXX determine if FW does this, see set_tone) */ msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + ((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60)); return 0; } Commit Message: [media] cx24116: fix a buffer overflow when checking userspace params The maximum size for a DiSEqC command is 6, according to the userspace API. However, the code allows to write up much more values: drivers/media/dvb-frontends/cx24116.c:983 cx24116_send_diseqc_msg() error: buffer overflow 'd->msg' 6 <= 23 Cc: [email protected] Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *d) { struct cx24116_state *state = fe->demodulator_priv; int i, ret; /* Validate length */ if (d->msg_len > sizeof(d->msg)) return -EINVAL; /* Dump DiSEqC message */ if (debug) { printk(KERN_INFO "cx24116: %s(", __func__); for (i = 0 ; i < d->msg_len ;) { printk(KERN_INFO "0x%02x", d->msg[i]); if (++i < d->msg_len) printk(KERN_INFO ", "); } printk(") toneburst=%d\n", toneburst); } /* DiSEqC message */ for (i = 0; i < d->msg_len; i++) state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i]; /* DiSEqC message length */ state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len; /* Command length */ state->dsec_cmd.len = CX24116_DISEQC_MSGOFS + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN]; /* DiSEqC toneburst */ if (toneburst == CX24116_DISEQC_MESGCACHE) /* Message is cached */ return 0; else if (toneburst == CX24116_DISEQC_TONEOFF) /* Message is sent without burst */ state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0; else if (toneburst == CX24116_DISEQC_TONECACHE) { /* * Message is sent with derived else cached burst * * WRITE PORT GROUP COMMAND 38 * * 0/A/A: E0 10 38 F0..F3 * 1/B/B: E0 10 38 F4..F7 * 2/C/A: E0 10 38 F8..FB * 3/D/B: E0 10 38 FC..FF * * databyte[3]= 8421:8421 * ABCD:WXYZ * CLR :SET * * WX= PORT SELECT 0..3 (X=TONEBURST) * Y = VOLTAGE (0=13V, 1=18V) * Z = BAND (0=LOW, 1=HIGH(22K)) */ if (d->msg_len >= 4 && d->msg[2] == 0x38) state->dsec_cmd.args[CX24116_DISEQC_BURST] = ((d->msg[3] & 4) >> 2); if (debug) dprintk("%s burst=%d\n", __func__, state->dsec_cmd.args[CX24116_DISEQC_BURST]); } /* Wait for LNB ready */ ret = cx24116_wait_for_lnb(fe); if (ret != 0) return ret; /* Wait for voltage/min repeat delay */ msleep(100); /* Command */ ret = cx24116_cmd_execute(fe, &state->dsec_cmd); if (ret != 0) return ret; /* * Wait for send * * Eutelsat spec: * >15ms delay + (XXX determine if FW does this, see set_tone) * 13.5ms per byte + * >15ms delay + * 12.5ms burst + * >15ms delay (XXX determine if FW does this, see set_tone) */ msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + ((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60)); return 0; }
169,867
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltCopyOf(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemCopyOfPtr comp = (xsltStyleItemCopyOfPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xmlXPathObjectPtr res = NULL; xmlNodeSetPtr list = NULL; int i; xmlDocPtr oldXPContextDoc; xmlNsPtr *oldXPNamespaces; xmlNodePtr oldXPContextNode; int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; xmlXPathContextPtr xpctxt; if ((ctxt == NULL) || (node == NULL) || (inst == NULL)) return; if ((comp == NULL) || (comp->select == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "xsl:copy-of : compilation failed\n"); return; } /* * SPEC XSLT 1.0: * "The xsl:copy-of element can be used to insert a result tree * fragment into the result tree, without first converting it to * a string as xsl:value-of does (see [7.6.1 Generating Text with * xsl:value-of]). The required select attribute contains an * expression. When the result of evaluating the expression is a * result tree fragment, the complete fragment is copied into the * result tree. When the result is a node-set, all the nodes in the * set are copied in document order into the result tree; copying * an element node copies the attribute nodes, namespace nodes and * children of the element node as well as the element node itself; * a root node is copied by copying its children. When the result * is neither a node-set nor a result tree fragment, the result is * converted to a string and then inserted into the result tree, * as with xsl:value-of. */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: select %s\n", comp->select)); #endif /* * Evaluate the "select" expression. */ xpctxt = ctxt->xpathCtxt; oldXPContextDoc = xpctxt->doc; oldXPContextNode = xpctxt->node; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; xpctxt->node = node; if (comp != NULL) { #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } res = xmlXPathCompiledEval(comp->comp, xpctxt); xpctxt->doc = oldXPContextDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; if (res != NULL) { if (res->type == XPATH_NODESET) { /* * Node-set * -------- */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result is a node set\n")); #endif list = res->nodesetval; if (list != NULL) { xmlNodePtr cur; /* * The list is already sorted in document order by XPath. * Append everything in this order under ctxt->insert. */ for (i = 0;i < list->nodeNr;i++) { cur = list->nodeTab[i]; if (cur == NULL) continue; if ((cur->type == XML_DOCUMENT_NODE) || (cur->type == XML_HTML_DOCUMENT_NODE)) { xsltCopyTreeList(ctxt, inst, cur->children, ctxt->insert, 0, 0); } else if (cur->type == XML_ATTRIBUTE_NODE) { xsltShallowCopyAttr(ctxt, inst, ctxt->insert, (xmlAttrPtr) cur); } else { xsltCopyTreeInternal(ctxt, inst, cur, ctxt->insert, 0, 0); } } } } else if (res->type == XPATH_XSLT_TREE) { /* * Result tree fragment * -------------------- * E.g. via <xsl:variable ...><foo/></xsl:variable> * Note that the root node of such trees is an xmlDocPtr in Libxslt. */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result is a result tree fragment\n")); #endif list = res->nodesetval; if ((list != NULL) && (list->nodeTab != NULL) && (list->nodeTab[0] != NULL) && (IS_XSLT_REAL_NODE(list->nodeTab[0]))) { xsltCopyTreeList(ctxt, inst, list->nodeTab[0]->children, ctxt->insert, 0, 0); } } else { xmlChar *value = NULL; /* * Convert to a string. */ value = xmlXPathCastToString(res); if (value == NULL) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltCopyOf(): " "failed to cast an XPath object to string.\n"); ctxt->state = XSLT_STATE_STOPPED; } else { if (value[0] != 0) { /* * Append content as text node. */ xsltCopyTextString(ctxt, ctxt->insert, value, 0); } xmlFree(value); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result %s\n", res->stringval)); #endif } } } else { ctxt->state = XSLT_STATE_STOPPED; } if (res != NULL) xmlXPathFreeObject(res); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltCopyOf(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemCopyOfPtr comp = (xsltStyleItemCopyOfPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xmlXPathObjectPtr res = NULL; xmlNodeSetPtr list = NULL; int i; if ((ctxt == NULL) || (node == NULL) || (inst == NULL)) return; if ((comp == NULL) || (comp->select == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "xsl:copy-of : compilation failed\n"); return; } /* * SPEC XSLT 1.0: * "The xsl:copy-of element can be used to insert a result tree * fragment into the result tree, without first converting it to * a string as xsl:value-of does (see [7.6.1 Generating Text with * xsl:value-of]). The required select attribute contains an * expression. When the result of evaluating the expression is a * result tree fragment, the complete fragment is copied into the * result tree. When the result is a node-set, all the nodes in the * set are copied in document order into the result tree; copying * an element node copies the attribute nodes, namespace nodes and * children of the element node as well as the element node itself; * a root node is copied by copying its children. When the result * is neither a node-set nor a result tree fragment, the result is * converted to a string and then inserted into the result tree, * as with xsl:value-of. */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: select %s\n", comp->select)); #endif /* * Evaluate the "select" expression. */ res = xsltPreCompEval(ctxt, node, comp); if (res != NULL) { if (res->type == XPATH_NODESET) { /* * Node-set * -------- */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result is a node set\n")); #endif list = res->nodesetval; if (list != NULL) { xmlNodePtr cur; /* * The list is already sorted in document order by XPath. * Append everything in this order under ctxt->insert. */ for (i = 0;i < list->nodeNr;i++) { cur = list->nodeTab[i]; if (cur == NULL) continue; if ((cur->type == XML_DOCUMENT_NODE) || (cur->type == XML_HTML_DOCUMENT_NODE)) { xsltCopyTreeList(ctxt, inst, cur->children, ctxt->insert, 0, 0); } else if (cur->type == XML_ATTRIBUTE_NODE) { xsltShallowCopyAttr(ctxt, inst, ctxt->insert, (xmlAttrPtr) cur); } else { xsltCopyTreeInternal(ctxt, inst, cur, ctxt->insert, 0, 0); } } } } else if (res->type == XPATH_XSLT_TREE) { /* * Result tree fragment * -------------------- * E.g. via <xsl:variable ...><foo/></xsl:variable> * Note that the root node of such trees is an xmlDocPtr in Libxslt. */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result is a result tree fragment\n")); #endif list = res->nodesetval; if ((list != NULL) && (list->nodeTab != NULL) && (list->nodeTab[0] != NULL) && (IS_XSLT_REAL_NODE(list->nodeTab[0]))) { xsltCopyTreeList(ctxt, inst, list->nodeTab[0]->children, ctxt->insert, 0, 0); } } else { xmlChar *value = NULL; /* * Convert to a string. */ value = xmlXPathCastToString(res); if (value == NULL) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltCopyOf(): " "failed to cast an XPath object to string.\n"); ctxt->state = XSLT_STATE_STOPPED; } else { if (value[0] != 0) { /* * Append content as text node. */ xsltCopyTextString(ctxt, ctxt->insert, value, 0); } xmlFree(value); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result %s\n", res->stringval)); #endif } } } else { ctxt->state = XSLT_STATE_STOPPED; } if (res != NULL) xmlXPathFreeObject(res); }
173,322
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_delete_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { OM_uint32 ret = GSS_S_COMPLETE; spnego_gss_ctx_id_t *ctx = (spnego_gss_ctx_id_t *)context_handle; *minor_status = 0; if (context_handle == NULL) return (GSS_S_FAILURE); if (*ctx == NULL) return (GSS_S_COMPLETE); /* * If this is still an SPNEGO mech, release it locally. */ if ((*ctx)->magic_num == SPNEGO_MAGIC_ID) { (void) gss_delete_sec_context(minor_status, &(*ctx)->ctx_handle, output_token); (void) release_spnego_ctx(ctx); } else { ret = gss_delete_sec_context(minor_status, context_handle, output_token); } 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_delete_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { OM_uint32 ret = GSS_S_COMPLETE; spnego_gss_ctx_id_t *ctx = (spnego_gss_ctx_id_t *)context_handle; *minor_status = 0; if (context_handle == NULL) return (GSS_S_FAILURE); if (*ctx == NULL) return (GSS_S_COMPLETE); (void) gss_delete_sec_context(minor_status, &(*ctx)->ctx_handle, output_token); (void) release_spnego_ctx(ctx); return (ret); }
166,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: setkey_principal3_2_svc(setkey3_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->keyblocks, arg->n_keys); } else { log_unauth("kadm5_setkey_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setkey_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
setkey_principal3_2_svc(setkey3_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->keyblocks, arg->n_keys); } else { log_unauth("kadm5_setkey_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setkey_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,525
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TransportTexture::OnTexturesCreated(std::vector<int> textures) { bool ret = decoder_->MakeCurrent(); if (!ret) { LOG(ERROR) << "Failed to switch context"; return; } output_textures_->clear(); for (size_t i = 0; i < textures.size(); ++i) { uint32 gl_texture = 0; ret = decoder_->GetServiceTextureId(textures[i], &gl_texture); DCHECK(ret) << "Cannot translate client texture ID to service ID"; output_textures_->push_back(gl_texture); texture_map_.insert(std::make_pair(gl_texture, textures[i])); } create_task_->Run(); create_task_.reset(); output_textures_ = NULL; } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void TransportTexture::OnTexturesCreated(std::vector<int> textures) { void TransportTexture::OnTexturesCreated(const std::vector<int>& textures) { bool ret = decoder_->MakeCurrent(); if (!ret) { LOG(ERROR) << "Failed to switch context"; return; } output_textures_->clear(); for (size_t i = 0; i < textures.size(); ++i) { uint32 gl_texture = 0; ret = decoder_->GetServiceTextureId(textures[i], &gl_texture); DCHECK(ret) << "Cannot translate client texture ID to service ID"; output_textures_->push_back(gl_texture); texture_map_.insert(std::make_pair(gl_texture, textures[i])); } create_task_->Run(); create_task_.reset(); output_textures_ = NULL; }
170,313
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int fetch_uidl(char *line, void *data) { int i, index; struct Context *ctx = (struct Context *) data; struct PopData *pop_data = (struct PopData *) ctx->data; char *endp = NULL; errno = 0; index = strtol(line, &endp, 10); if (errno) return -1; while (*endp == ' ') endp++; memmove(line, endp, strlen(endp) + 1); for (i = 0; i < ctx->msgcount; i++) if (mutt_str_strcmp(line, ctx->hdrs[i]->data) == 0) break; if (i == ctx->msgcount) { mutt_debug(1, "new header %d %s\n", index, line); if (i >= ctx->hdrmax) mx_alloc_memory(ctx); ctx->msgcount++; ctx->hdrs[i] = mutt_header_new(); ctx->hdrs[i]->data = mutt_str_strdup(line); } else if (ctx->hdrs[i]->index != index - 1) pop_data->clear_cache = true; ctx->hdrs[i]->refno = index; ctx->hdrs[i]->index = index - 1; return 0; } Commit Message: Ensure UID in fetch_uidl CWE ID: CWE-824
static int fetch_uidl(char *line, void *data) { int i, index; struct Context *ctx = (struct Context *) data; struct PopData *pop_data = (struct PopData *) ctx->data; char *endp = NULL; errno = 0; index = strtol(line, &endp, 10); if (errno) return -1; while (*endp == ' ') endp++; memmove(line, endp, strlen(endp) + 1); /* uid must be at least be 1 byte */ if (strlen(line) == 0) return -1; for (i = 0; i < ctx->msgcount; i++) if (mutt_str_strcmp(line, ctx->hdrs[i]->data) == 0) break; if (i == ctx->msgcount) { mutt_debug(1, "new header %d %s\n", index, line); if (i >= ctx->hdrmax) mx_alloc_memory(ctx); ctx->msgcount++; ctx->hdrs[i] = mutt_header_new(); ctx->hdrs[i]->data = mutt_str_strdup(line); } else if (ctx->hdrs[i]->index != index - 1) pop_data->clear_cache = true; ctx->hdrs[i]->refno = index; ctx->hdrs[i]->index = index - 1; return 0; }
169,136
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck( const KURL& current_src) { DCHECK(IsMainThread()); return Context()->GetSecurityOrigin() && Context()->GetSecurityOrigin()->CanRequest(current_src); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
bool MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck( // Test to see if the current media URL taint the origin of the audio context? return Context()->WouldTaintOrigin(MediaElement()->currentSrc()); }
173,148