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: static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_hash rhash;
snprintf(rhash.type, CRYPTO_MAX_ALG_NAME, "%s", "ahash");
rhash.blocksize = alg->cra_blocksize;
rhash.digestsize = __crypto_hash_alg_common(alg)->digestsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_HASH,
sizeof(struct crypto_report_hash), &rhash))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Steffen Klassert <steffen.klassert@secunet.com>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
CWE ID: CWE-310
|
static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_hash rhash;
strncpy(rhash.type, "ahash", sizeof(rhash.type));
rhash.blocksize = alg->cra_blocksize;
rhash.digestsize = __crypto_hash_alg_common(alg)->digestsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_HASH,
sizeof(struct crypto_report_hash), &rhash))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 166,065
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline int object_common2(UNSERIALIZE_PARAMETER, long elements)
{
zval *retval_ptr = NULL;
zval fname;
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) {
/* We've got partially constructed object on our hands here. Wipe it. */
if(Z_TYPE_PP(rval) == IS_OBJECT) {
zend_hash_clean(Z_OBJPROP_PP(rval));
}
ZVAL_NULL(*rval);
return 0;
}
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY &&
zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) {
INIT_PZVAL(&fname);
ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0);
BG(serialize_lock)++;
call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC);
BG(serialize_lock)--;
}
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction
CWE ID: CWE-119
|
static inline int object_common2(UNSERIALIZE_PARAMETER, long elements)
{
zval *retval_ptr = NULL;
zval fname;
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) {
/* We've got partially constructed object on our hands here. Wipe it. */
if(Z_TYPE_PP(rval) == IS_OBJECT) {
zend_hash_clean(Z_OBJPROP_PP(rval));
zend_object_store_ctor_failed(*rval TSRMLS_CC);
}
ZVAL_NULL(*rval);
return 0;
}
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY &&
zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) {
INIT_PZVAL(&fname);
ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0);
BG(serialize_lock)++;
call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC);
BG(serialize_lock)--;
}
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
| 166,940
|
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 ihevcd_parse_sei_payload(codec_t *ps_codec,
UWORD32 u4_payload_type,
UWORD32 u4_payload_size,
WORD8 i1_nal_type)
{
parse_ctxt_t *ps_parse = &ps_codec->s_parse;
bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm;
WORD32 payload_bits_remaining = 0;
sps_t *ps_sps;
UWORD32 i;
for(i = 0; i < MAX_SPS_CNT; i++)
{
ps_sps = ps_codec->ps_sps_base + i;
if(ps_sps->i1_sps_valid)
{
break;
}
}
if(NULL == ps_sps)
{
return;
}
if(NAL_PREFIX_SEI == i1_nal_type)
{
switch(u4_payload_type)
{
case SEI_BUFFERING_PERIOD:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_buffering_period_sei(ps_codec, ps_sps);
break;
case SEI_PICTURE_TIMING:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_pic_timing_sei(ps_codec, ps_sps);
break;
case SEI_TIME_CODE:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_time_code_sei(ps_codec);
break;
case SEI_MASTERING_DISPLAY_COLOUR_VOLUME:
ps_parse->s_sei_params.i4_sei_mastering_disp_colour_vol_params_present_flags = 1;
ihevcd_parse_mastering_disp_params_sei(ps_codec);
break;
case SEI_USER_DATA_REGISTERED_ITU_T_T35:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_user_data_registered_itu_t_t35(ps_codec,
u4_payload_size);
break;
default:
for(i = 0; i < u4_payload_size; i++)
{
ihevcd_bits_flush(ps_bitstrm, 8);
}
break;
}
}
else /* NAL_SUFFIX_SEI */
{
switch(u4_payload_type)
{
case SEI_USER_DATA_REGISTERED_ITU_T_T35:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_user_data_registered_itu_t_t35(ps_codec,
u4_payload_size);
break;
default:
for(i = 0; i < u4_payload_size; i++)
{
ihevcd_bits_flush(ps_bitstrm, 8);
}
break;
}
}
/**
* By definition the underlying bitstream terminates in a byte-aligned manner.
* 1. Extract all bar the last MIN(bitsremaining,nine) bits as reserved_payload_extension_data
* 2. Examine the final 8 bits to determine the payload_bit_equal_to_one marker
* 3. Extract the remainingreserved_payload_extension_data bits.
*
* If there are fewer than 9 bits available, extract them.
*/
payload_bits_remaining = ihevcd_bits_num_bits_remaining(ps_bitstrm);
if(payload_bits_remaining) /* more_data_in_payload() */
{
WORD32 final_bits;
WORD32 final_payload_bits = 0;
WORD32 mask = 0xFF;
UWORD32 u4_dummy;
UWORD32 u4_reserved_payload_extension_data;
UNUSED(u4_dummy);
UNUSED(u4_reserved_payload_extension_data);
while(payload_bits_remaining > 9)
{
BITS_PARSE("reserved_payload_extension_data",
u4_reserved_payload_extension_data, ps_bitstrm, 1);
payload_bits_remaining--;
}
final_bits = ihevcd_bits_nxt(ps_bitstrm, payload_bits_remaining);
while(final_bits & (mask >> final_payload_bits))
{
final_payload_bits++;
continue;
}
while(payload_bits_remaining > (9 - final_payload_bits))
{
BITS_PARSE("reserved_payload_extension_data",
u4_reserved_payload_extension_data, ps_bitstrm, 1);
payload_bits_remaining--;
}
BITS_PARSE("payload_bit_equal_to_one", u4_dummy, ps_bitstrm, 1);
payload_bits_remaining--;
while(payload_bits_remaining)
{
BITS_PARSE("payload_bit_equal_to_zero", u4_dummy, ps_bitstrm, 1);
payload_bits_remaining--;
}
}
return;
}
Commit Message: Fix overflow in sei user data parsing
Bug: 37968960
Bug: 65484460
Test: ran POC post-patch
Change-Id: I73e91b4b2976b954b5fd4f29182d6072abbc7f70
CWE ID: CWE-190
|
void ihevcd_parse_sei_payload(codec_t *ps_codec,
UWORD32 u4_payload_type,
UWORD32 u4_payload_size,
WORD8 i1_nal_type)
{
parse_ctxt_t *ps_parse = &ps_codec->s_parse;
bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm;
WORD32 payload_bits_remaining = 0;
sps_t *ps_sps;
UWORD32 i;
for(i = 0; i < MAX_SPS_CNT; i++)
{
ps_sps = ps_codec->ps_sps_base + i;
if(ps_sps->i1_sps_valid)
{
break;
}
}
if(NULL == ps_sps)
{
return;
}
if(NAL_PREFIX_SEI == i1_nal_type)
{
switch(u4_payload_type)
{
case SEI_BUFFERING_PERIOD:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_buffering_period_sei(ps_codec, ps_sps);
break;
case SEI_PICTURE_TIMING:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_pic_timing_sei(ps_codec, ps_sps);
break;
case SEI_TIME_CODE:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
ihevcd_parse_time_code_sei(ps_codec);
break;
case SEI_MASTERING_DISPLAY_COLOUR_VOLUME:
ps_parse->s_sei_params.i4_sei_mastering_disp_colour_vol_params_present_flags = 1;
ihevcd_parse_mastering_disp_params_sei(ps_codec);
break;
case SEI_USER_DATA_REGISTERED_ITU_T_T35:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
if(ps_parse->s_sei_params.i4_sei_user_data_cnt >= USER_DATA_MAX)
{
for(i = 0; i < u4_payload_size / 4; i++)
{
ihevcd_bits_flush(ps_bitstrm, 4 * 8);
}
ihevcd_bits_flush(ps_bitstrm, (u4_payload_size - i * 4) * 8);
}
else
{
ihevcd_parse_user_data_registered_itu_t_t35(ps_codec,
u4_payload_size);
}
break;
default:
for(i = 0; i < u4_payload_size; i++)
{
ihevcd_bits_flush(ps_bitstrm, 8);
}
break;
}
}
else /* NAL_SUFFIX_SEI */
{
switch(u4_payload_type)
{
case SEI_USER_DATA_REGISTERED_ITU_T_T35:
ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1;
if(ps_parse->s_sei_params.i4_sei_user_data_cnt >= USER_DATA_MAX)
{
for(i = 0; i < u4_payload_size / 4; i++)
{
ihevcd_bits_flush(ps_bitstrm, 4 * 8);
}
ihevcd_bits_flush(ps_bitstrm, (u4_payload_size - i * 4) * 8);
}
else
{
ihevcd_parse_user_data_registered_itu_t_t35(ps_codec,
u4_payload_size);
}
break;
default:
for(i = 0; i < u4_payload_size; i++)
{
ihevcd_bits_flush(ps_bitstrm, 8);
}
break;
}
}
/**
* By definition the underlying bitstream terminates in a byte-aligned manner.
* 1. Extract all bar the last MIN(bitsremaining,nine) bits as reserved_payload_extension_data
* 2. Examine the final 8 bits to determine the payload_bit_equal_to_one marker
* 3. Extract the remainingreserved_payload_extension_data bits.
*
* If there are fewer than 9 bits available, extract them.
*/
payload_bits_remaining = ihevcd_bits_num_bits_remaining(ps_bitstrm);
if(payload_bits_remaining) /* more_data_in_payload() */
{
WORD32 final_bits;
WORD32 final_payload_bits = 0;
WORD32 mask = 0xFF;
UWORD32 u4_dummy;
UWORD32 u4_reserved_payload_extension_data;
UNUSED(u4_dummy);
UNUSED(u4_reserved_payload_extension_data);
while(payload_bits_remaining > 9)
{
BITS_PARSE("reserved_payload_extension_data",
u4_reserved_payload_extension_data, ps_bitstrm, 1);
payload_bits_remaining--;
}
final_bits = ihevcd_bits_nxt(ps_bitstrm, payload_bits_remaining);
while(final_bits & (mask >> final_payload_bits))
{
final_payload_bits++;
continue;
}
while(payload_bits_remaining > (9 - final_payload_bits))
{
BITS_PARSE("reserved_payload_extension_data",
u4_reserved_payload_extension_data, ps_bitstrm, 1);
payload_bits_remaining--;
}
BITS_PARSE("payload_bit_equal_to_one", u4_dummy, ps_bitstrm, 1);
payload_bits_remaining--;
while(payload_bits_remaining)
{
BITS_PARSE("payload_bit_equal_to_zero", u4_dummy, ps_bitstrm, 1);
payload_bits_remaining--;
}
}
return;
}
| 174,102
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int32 CommandBufferProxyImpl::RegisterTransferBuffer(
base::SharedMemory* shared_memory,
size_t size,
int32 id_request) {
if (last_state_.error != gpu::error::kNoError)
return -1;
int32 id;
if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(
route_id_,
shared_memory->handle(), // Returns FileDescriptor with auto_close off.
size,
id_request,
&id))) {
return -1;
}
return id;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
int32 CommandBufferProxyImpl::RegisterTransferBuffer(
base::SharedMemory* shared_memory,
size_t size,
int32 id_request) {
if (last_state_.error != gpu::error::kNoError)
return -1;
// Returns FileDescriptor with auto_close off.
base::SharedMemoryHandle handle = shared_memory->handle();
#if defined(OS_WIN)
// Windows needs to explicitly duplicate the handle out to another process.
if (!sandbox::BrokerDuplicateHandle(handle, channel_->gpu_pid(),
&handle, FILE_MAP_WRITE, 0)) {
return -1;
}
#endif
int32 id;
if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(
route_id_,
handle,
size,
id_request,
&id))) {
return -1;
}
return id;
}
| 170,927
|
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 usage_exit() {
fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n",
exec_name);
exit(EXIT_FAILURE);
}
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
|
void usage_exit() {
void usage_exit(void) {
fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n",
exec_name);
exit(EXIT_FAILURE);
}
| 174,486
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void LocalFileSystem::deleteFileSystemInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
FileSystemType type,
PassRefPtr<CallbackWrapper> callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString());
fileSystem()->deleteFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release());
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
void LocalFileSystem::deleteFileSystemInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
FileSystemType type,
CallbackWrapper* callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString());
fileSystem()->deleteFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release());
}
| 171,425
|
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 SegmentInfo::Parse()
{
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop)
{
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x0AD7B1) //Timecode Scale
{
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0489) //Segment duration
{
const long status = UnserializeFloat(
pReader,
pos,
size,
m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0D80) //MuxingApp
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pMuxingAppAsUTF8);
if (status)
return status;
}
else if (id == 0x1741) //WritingApp
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pWritingAppAsUTF8);
if (status)
return status;
}
else if (id == 0x3BA9) //Title
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long SegmentInfo::Parse()
| 174,404
|
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_finalize (GObject *object)
{
MyObject *mobject = MY_OBJECT (object);
g_free (mobject->this_is_a_string);
(G_OBJECT_CLASS (my_object_parent_class)->finalize) (object);
}
Commit Message:
CWE ID: CWE-264
|
my_object_finalize (GObject *object)
| 165,099
|
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 BrowserMainParts::PostMainMessageLoopRun() {
CompositorUtils::GetInstance()->Shutdown();
}
Commit Message:
CWE ID: CWE-20
|
void BrowserMainParts::PostMainMessageLoopRun() {
WebContentsUnloader::GetInstance()->Shutdown();
BrowserContextDestroyer::Shutdown();
BrowserContext::AssertNoContextsExist();
CompositorUtils::GetInstance()->Shutdown();
}
| 165,423
|
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: privsep_preauth(Authctxt *authctxt)
{
int status, r;
pid_t pid;
struct ssh_sandbox *box = NULL;
/* Set up unprivileged child process to deal with network data */
pmonitor = monitor_init();
/* Store a pointer to the kex for later rekeying */
pmonitor->m_pkex = &active_state->kex;
if (use_privsep == PRIVSEP_ON)
box = ssh_sandbox_init();
pid = fork();
if (pid == -1) {
fatal("fork of unprivileged child failed");
} else if (pid != 0) {
debug2("Network child is on pid %ld", (long)pid);
pmonitor->m_pid = pid;
if (have_agent) {
r = ssh_get_authentication_socket(&auth_sock);
if (r != 0) {
error("Could not get agent socket: %s",
ssh_err(r));
have_agent = 0;
}
}
if (box != NULL)
ssh_sandbox_parent_preauth(box, pid);
monitor_child_preauth(authctxt, pmonitor);
/* Sync memory */
monitor_sync(pmonitor);
/* Wait for the child's exit status */
while (waitpid(pid, &status, 0) < 0) {
if (errno == EINTR)
continue;
pmonitor->m_pid = -1;
fatal("%s: waitpid: %s", __func__, strerror(errno));
}
privsep_is_preauth = 0;
pmonitor->m_pid = -1;
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) != 0)
fatal("%s: preauth child exited with status %d",
__func__, WEXITSTATUS(status));
} else if (WIFSIGNALED(status))
fatal("%s: preauth child terminated by signal %d",
__func__, WTERMSIG(status));
if (box != NULL)
ssh_sandbox_parent_finish(box);
return 1;
} else {
/* child */
close(pmonitor->m_sendfd);
close(pmonitor->m_log_recvfd);
/* Arrange for logging to be sent to the monitor */
set_log_handler(mm_log_handler, pmonitor);
privsep_preauth_child();
setproctitle("%s", "[net]");
if (box != NULL)
ssh_sandbox_child(box);
return 0;
}
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
|
privsep_preauth(Authctxt *authctxt)
{
int status, r;
pid_t pid;
struct ssh_sandbox *box = NULL;
/* Set up unprivileged child process to deal with network data */
pmonitor = monitor_init();
/* Store a pointer to the kex for later rekeying */
pmonitor->m_pkex = &active_state->kex;
if (use_privsep == PRIVSEP_ON)
box = ssh_sandbox_init();
pid = fork();
if (pid == -1) {
fatal("fork of unprivileged child failed");
} else if (pid != 0) {
debug2("Network child is on pid %ld", (long)pid);
pmonitor->m_pid = pid;
if (have_agent) {
r = ssh_get_authentication_socket(&auth_sock);
if (r != 0) {
error("Could not get agent socket: %s",
ssh_err(r));
have_agent = 0;
}
}
if (box != NULL)
ssh_sandbox_parent_preauth(box, pid);
monitor_child_preauth(authctxt, pmonitor);
/* Wait for the child's exit status */
while (waitpid(pid, &status, 0) < 0) {
if (errno == EINTR)
continue;
pmonitor->m_pid = -1;
fatal("%s: waitpid: %s", __func__, strerror(errno));
}
privsep_is_preauth = 0;
pmonitor->m_pid = -1;
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) != 0)
fatal("%s: preauth child exited with status %d",
__func__, WEXITSTATUS(status));
} else if (WIFSIGNALED(status))
fatal("%s: preauth child terminated by signal %d",
__func__, WTERMSIG(status));
if (box != NULL)
ssh_sandbox_parent_finish(box);
return 1;
} else {
/* child */
close(pmonitor->m_sendfd);
close(pmonitor->m_log_recvfd);
/* Arrange for logging to be sent to the monitor */
set_log_handler(mm_log_handler, pmonitor);
privsep_preauth_child();
setproctitle("%s", "[net]");
if (box != NULL)
ssh_sandbox_child(box);
return 0;
}
}
| 168,659
|
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 skt_write(int fd, const void *p, size_t len)
{
int sent;
struct pollfd pfd;
FNLOG();
pfd.fd = fd;
pfd.events = POLLOUT;
/* poll for 500 ms */
/* send time out */
if (poll(&pfd, 1, 500) == 0)
return 0;
ts_log("skt_write", len, NULL);
if ((sent = send(fd, p, len, MSG_NOSIGNAL)) == -1)
{
ERROR("write failed with errno=%d\n", errno);
return -1;
}
return sent;
}
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 skt_write(int fd, const void *p, size_t len)
{
int sent;
struct pollfd pfd;
FNLOG();
pfd.fd = fd;
pfd.events = POLLOUT;
/* poll for 500 ms */
/* send time out */
if (TEMP_FAILURE_RETRY(poll(&pfd, 1, 500)) == 0)
return 0;
ts_log("skt_write", len, NULL);
if ((sent = TEMP_FAILURE_RETRY(send(fd, p, len, MSG_NOSIGNAL))) == -1)
{
ERROR("write failed with errno=%d\n", errno);
return -1;
}
return sent;
}
| 173,429
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int b_unpack (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1);
size_t ld;
const char *data = luaL_checklstring(L, 2, &ld);
size_t pos = luaL_optinteger(L, 3, 1) - 1;
int n = 0; /* number of results */
defaultoptions(&h);
while (*fmt) {
int opt = *fmt++;
size_t size = optsize(L, opt, &fmt);
pos += gettoalign(pos, &h, opt, size);
luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
/* stack space for item + next position */
luaL_checkstack(L, 2, "too many results");
switch (opt) {
case 'b': case 'B': case 'h': case 'H':
case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
int issigned = islower(opt);
lua_Number res = getinteger(data+pos, h.endian, issigned, size);
lua_pushnumber(L, res); n++;
break;
}
case 'x': {
break;
}
case 'f': {
float f;
memcpy(&f, data+pos, size);
correctbytes((char *)&f, sizeof(f), h.endian);
lua_pushnumber(L, f); n++;
break;
}
case 'd': {
double d;
memcpy(&d, data+pos, size);
correctbytes((char *)&d, sizeof(d), h.endian);
lua_pushnumber(L, d); n++;
break;
}
case 'c': {
if (size == 0) {
if (n == 0 || !lua_isnumber(L, -1))
luaL_error(L, "format 'c0' needs a previous size");
size = lua_tonumber(L, -1);
lua_pop(L, 1); n--;
luaL_argcheck(L, size <= ld && pos <= ld - size,
2, "data string too short");
}
lua_pushlstring(L, data+pos, size); n++;
break;
}
case 's': {
const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
if (e == NULL)
luaL_error(L, "unfinished string in data");
size = (e - (data+pos)) + 1;
lua_pushlstring(L, data+pos, size - 1); n++;
break;
}
default: controloptions(L, opt, &fmt, &h);
}
pos += size;
}
lua_pushinteger(L, pos + 1); /* next position */
return n + 1;
}
Commit Message: Security: fix Lua struct package offset handling.
After the first fix to the struct package I found another similar
problem, which is fixed by this patch. It could be reproduced easily by
running the following script:
return struct.unpack('f', "xxxxxxxxxxxxx",-3)
The above will access bytes before the 'data' pointer.
CWE ID: CWE-190
|
static int b_unpack (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1);
size_t ld;
const char *data = luaL_checklstring(L, 2, &ld);
size_t pos = luaL_optinteger(L, 3, 1);
luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater");
pos--; /* Lua indexes are 1-based, but here we want 0-based for C
* pointer math. */
int n = 0; /* number of results */
defaultoptions(&h);
while (*fmt) {
int opt = *fmt++;
size_t size = optsize(L, opt, &fmt);
pos += gettoalign(pos, &h, opt, size);
luaL_argcheck(L, size <= ld && pos <= ld - size,
2, "data string too short");
/* stack space for item + next position */
luaL_checkstack(L, 2, "too many results");
switch (opt) {
case 'b': case 'B': case 'h': case 'H':
case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
int issigned = islower(opt);
lua_Number res = getinteger(data+pos, h.endian, issigned, size);
lua_pushnumber(L, res); n++;
break;
}
case 'x': {
break;
}
case 'f': {
float f;
memcpy(&f, data+pos, size);
correctbytes((char *)&f, sizeof(f), h.endian);
lua_pushnumber(L, f); n++;
break;
}
case 'd': {
double d;
memcpy(&d, data+pos, size);
correctbytes((char *)&d, sizeof(d), h.endian);
lua_pushnumber(L, d); n++;
break;
}
case 'c': {
if (size == 0) {
if (n == 0 || !lua_isnumber(L, -1))
luaL_error(L, "format 'c0' needs a previous size");
size = lua_tonumber(L, -1);
lua_pop(L, 1); n--;
luaL_argcheck(L, size <= ld && pos <= ld - size,
2, "data string too short");
}
lua_pushlstring(L, data+pos, size); n++;
break;
}
case 's': {
const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
if (e == NULL)
luaL_error(L, "unfinished string in data");
size = (e - (data+pos)) + 1;
lua_pushlstring(L, data+pos, size - 1); n++;
break;
}
default: controloptions(L, opt, &fmt, &h);
}
pos += size;
}
lua_pushinteger(L, pos + 1); /* next position */
return n + 1;
}
| 169,237
|
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: ScriptPromise BluetoothRemoteGATTServer::getPrimaryServicesImpl(
ScriptState* scriptState,
mojom::blink::WebBluetoothGATTQueryQuantity quantity,
String servicesUUID) {
if (!connected()) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(NetworkError, kGATTServerNotConnected));
}
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
AddToActiveAlgorithms(resolver);
mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service();
WTF::Optional<String> uuid = WTF::nullopt;
if (!servicesUUID.isEmpty())
uuid = servicesUUID;
service->RemoteServerGetPrimaryServices(
device()->id(), quantity, uuid,
convertToBaseCallback(
WTF::bind(&BluetoothRemoteGATTServer::GetPrimaryServicesCallback,
wrapPersistent(this), quantity, wrapPersistent(resolver))));
return promise;
}
Commit Message: Allow serialization of empty bluetooth uuids.
This change allows the passing WTF::Optional<String> types as
bluetooth.mojom.UUID optional parameter without needing to ensure the passed
object isn't empty.
BUG=None
R=juncai, dcheng
Review-Url: https://codereview.chromium.org/2646613003
Cr-Commit-Position: refs/heads/master@{#445809}
CWE ID: CWE-119
|
ScriptPromise BluetoothRemoteGATTServer::getPrimaryServicesImpl(
ScriptState* scriptState,
mojom::blink::WebBluetoothGATTQueryQuantity quantity,
String servicesUUID) {
if (!connected()) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(NetworkError, kGATTServerNotConnected));
}
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
AddToActiveAlgorithms(resolver);
mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service();
service->RemoteServerGetPrimaryServices(
device()->id(), quantity, servicesUUID,
convertToBaseCallback(
WTF::bind(&BluetoothRemoteGATTServer::GetPrimaryServicesCallback,
wrapPersistent(this), quantity, wrapPersistent(resolver))));
return promise;
}
| 172,022
|
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 WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 nInterpolatedSample;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* get last two samples generated */
/*lint -e{704} <avoid divide for performance>*/
tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18;
/*lint -e{704} <avoid divide for performance>*/
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
/* generate a buffer of noise */
while (numSamples--) {
nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac));
nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac);
*pOutputBuffer++ = (EAS_PCM) nInterpolatedSample;
/* update PRNG */
pWTVoice->phaseFrac += (EAS_U32) phaseInc;
if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) {
tmp0 = tmp1;
pWTVoice->phaseAccum = pWTVoice->loopEnd;
pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1);
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac);
}
}
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
|
void WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 nInterpolatedSample;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* get last two samples generated */
/*lint -e{704} <avoid divide for performance>*/
tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18;
/*lint -e{704} <avoid divide for performance>*/
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
/* generate a buffer of noise */
while (numSamples--) {
nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac));
nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac);
*pOutputBuffer++ = (EAS_PCM) nInterpolatedSample;
/* update PRNG */
pWTVoice->phaseFrac += (EAS_U32) phaseInc;
if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) {
tmp0 = tmp1;
pWTVoice->phaseAccum = pWTVoice->loopEnd;
pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1);
tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18;
pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac);
}
}
}
| 173,920
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
}
Commit Message: Fixed bug #72227: imagescale out-of-bounds read
Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a
CWE ID: CWE-125
|
static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
}
| 170,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: store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg)
{
if (pp != NULL)
png_error(pp, msg);
/* Else we have to do it ourselves. png_error eventually calls store_log,
* above. store_log accepts a NULL png_structp - it just changes what gets
* output by store_message.
*/
store_log(ps, pp, msg, 1 /* error */);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg)
store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
{
if (pp != NULL)
png_error(pp, msg);
/* Else we have to do it ourselves. png_error eventually calls store_log,
* above. store_log accepts a NULL png_structp - it just changes what gets
* output by store_message.
*/
store_log(ps, pp, msg, 1 /* error */);
}
| 173,708
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: tt_cmap10_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_ULong length, count;
if ( table + 20 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
p = table + 16;
count = TT_NEXT_ULONG( p );
if ( table + length > valid->limit || length < 20 + count * 2 )
FT_INVALID_TOO_SHORT;
/* check glyph indices */
{
FT_UInt gindex;
for ( ; count > 0; count-- )
{
gindex = TT_NEXT_USHORT( p );
if ( gindex >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
return SFNT_Err_Ok;
}
Commit Message:
CWE ID: CWE-189
|
tt_cmap10_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_ULong length, count;
if ( table + 20 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
p = table + 16;
count = TT_NEXT_ULONG( p );
if ( length > (FT_ULong)( valid->limit - table ) ||
length < 20 + count * 2 )
FT_INVALID_TOO_SHORT;
/* check glyph indices */
{
FT_UInt gindex;
for ( ; count > 0; count-- )
{
gindex = TT_NEXT_USHORT( p );
if ( gindex >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
return SFNT_Err_Ok;
}
| 164,739
|
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: explicit ElementsAccessorBase(const char* name)
: ElementsAccessor(name) { }
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
|
explicit ElementsAccessorBase(const char* name)
| 174,095
|
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 CallbackAndDie(bool succeeded) {
v8::Isolate* isolate = context_->isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Value> args[] = {v8::Boolean::New(isolate, succeeded)};
context_->CallFunction(v8::Local<v8::Function>::New(isolate, callback_),
arraysize(args), args);
delete this;
}
Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated
BUG=585268,568130
Review URL: https://codereview.chromium.org/1684953002
Cr-Commit-Position: refs/heads/master@{#374758}
CWE ID:
|
void CallbackAndDie(bool succeeded) {
// Use PostTask to avoid running user scripts while handling this
// DidFailProvisionalLoad notification.
base::MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback_, false));
delete this;
}
| 172,144
|
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 skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
if (copy_file("/etc/skel/.zshrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.zshrc");
}
}
else { //
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR);
fclose(fp);
fs_logger2("touch", fname);
}
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
if (copy_file("/etc/skel/.cshrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.cshrc");
}
}
else { //
/* coverity[toctou] */
FILE *fp = fopen(fname, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, u, g, S_IRUSR | S_IWUSR);
fclose(fp);
fs_logger2("touch", fname);
}
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
if (copy_file("/etc/skel/.bashrc", fname, u, g, 0644) == 0) {
fs_logger("clone /etc/skel/.bashrc");
}
}
free(fname);
}
}
Commit Message: replace copy_file with copy_file_as_user
CWE ID: CWE-269
|
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
| 170,093
|
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 WorkerProcessLauncherTest::KillProcess(DWORD exit_code) {
exit_code_ = exit_code;
BOOL result = SetEvent(process_exit_event_);
EXPECT_TRUE(result);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) {
BOOL result = SetEvent(process_exit_event_);
EXPECT_TRUE(result);
}
| 171,550
|
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 DelayedExecutor::delayedExecute(const QString &udi)
{
Solid::Device device(udi);
QString exec = m_service.exec();
MacroExpander mx(device);
mx.expandMacros(exec);
KRun::runCommand(exec, QString(), m_service.icon(), 0);
deleteLater();
}
Commit Message:
CWE ID: CWE-78
|
void DelayedExecutor::delayedExecute(const QString &udi)
{
Solid::Device device(udi);
QString exec = m_service.exec();
MacroExpander mx(device);
mx.expandMacrosShellQuote(exec);
KRun::runCommand(exec, QString(), m_service.icon(), 0);
deleteLater();
}
| 165,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: void BluetoothDeviceChromeOS::Cancel() {
DCHECK(agent_.get());
VLOG(1) << object_path_.value() << ": Cancel";
DCHECK(pairing_delegate_);
pairing_delegate_->DismissDisplayOrConfirm();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BluetoothDeviceChromeOS::Cancel() {
| 171,218
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: unsigned int get_random_int(void)
{
struct keydata *keyptr;
__u32 *hash = get_cpu_var(get_random_int_hash);
int ret;
keyptr = get_keyptr();
hash[0] += current->pid + jiffies + get_cycles();
ret = half_md4_transform(hash, keyptr->secret);
put_cpu_var(get_random_int_hash);
return ret;
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <dan@doxpara.com>
Tested-by: Willy Tarreau <w@1wt.eu>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID:
|
unsigned int get_random_int(void)
{
__u32 *hash = get_cpu_var(get_random_int_hash);
unsigned int ret;
hash[0] += current->pid + jiffies + get_cycles();
md5_transform(hash, random_int_secret);
ret = hash[0];
put_cpu_var(get_random_int_hash);
return ret;
}
| 165,761
|
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 AXARIAGridCell::isAriaColumnHeader() const {
const AtomicString& role = getAttribute(HTMLNames::roleAttr);
return equalIgnoringCase(role, "columnheader");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXARIAGridCell::isAriaColumnHeader() const {
const AtomicString& role = getAttribute(HTMLNames::roleAttr);
return equalIgnoringASCIICase(role, "columnheader");
}
| 171,901
|
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: htmlParseElementInternal(htmlParserCtxtPtr ctxt) {
const xmlChar *name;
const htmlElemDesc * info;
htmlParserNodeInfo node_info = { 0, };
int failed;
if ((ctxt == NULL) || (ctxt->input == NULL)) {
htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
"htmlParseElementInternal: context error\n", NULL, NULL);
return;
}
if (ctxt->instate == XML_PARSER_EOF)
return;
/* Capture start position */
if (ctxt->record_info) {
node_info.begin_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.begin_line = ctxt->input->line;
}
failed = htmlParseStartTag(ctxt);
name = ctxt->name;
if ((failed == -1) || (name == NULL)) {
if (CUR == '>')
NEXT;
return;
}
/*
* Lookup the info for that element.
*/
info = htmlTagLookup(name);
if (info == NULL) {
htmlParseErr(ctxt, XML_HTML_UNKNOWN_TAG,
"Tag %s invalid\n", name, NULL);
}
/*
* Check for an Empty Element labeled the XML/SGML way
*/
if ((CUR == '/') && (NXT(1) == '>')) {
SKIP(2);
if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
ctxt->sax->endElement(ctxt->userData, name);
htmlnamePop(ctxt);
return;
}
if (CUR == '>') {
NEXT;
} else {
htmlParseErr(ctxt, XML_ERR_GT_REQUIRED,
"Couldn't find end of Start Tag %s\n", name, NULL);
/*
* end of parsing of this node.
*/
if (xmlStrEqual(name, ctxt->name)) {
nodePop(ctxt);
htmlnamePop(ctxt);
}
if (ctxt->record_info)
htmlNodeInfoPush(ctxt, &node_info);
htmlParserFinishElementParsing(ctxt);
return;
}
/*
* Check for an Empty Element from DTD definition
*/
if ((info != NULL) && (info->empty)) {
if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
ctxt->sax->endElement(ctxt->userData, name);
htmlnamePop(ctxt);
return;
}
if (ctxt->record_info)
htmlNodeInfoPush(ctxt, &node_info);
}
Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9
Removes a few patches fixed upstream:
https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3
https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882
Stops using the NOXXE flag which was reverted upstream:
https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d
Changes the patch to uri.c to not add limits.h, which is included
upstream.
Bug: 722079
Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac
Reviewed-on: https://chromium-review.googlesource.com/535233
Reviewed-by: Scott Graham <scottmg@chromium.org>
Commit-Queue: Dominic Cooney <dominicc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#480755}
CWE ID: CWE-787
|
htmlParseElementInternal(htmlParserCtxtPtr ctxt) {
const xmlChar *name;
const htmlElemDesc * info;
htmlParserNodeInfo node_info = { NULL, 0, 0, 0, 0 };
int failed;
if ((ctxt == NULL) || (ctxt->input == NULL)) {
htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
"htmlParseElementInternal: context error\n", NULL, NULL);
return;
}
if (ctxt->instate == XML_PARSER_EOF)
return;
/* Capture start position */
if (ctxt->record_info) {
node_info.begin_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.begin_line = ctxt->input->line;
}
failed = htmlParseStartTag(ctxt);
name = ctxt->name;
if ((failed == -1) || (name == NULL)) {
if (CUR == '>')
NEXT;
return;
}
/*
* Lookup the info for that element.
*/
info = htmlTagLookup(name);
if (info == NULL) {
htmlParseErr(ctxt, XML_HTML_UNKNOWN_TAG,
"Tag %s invalid\n", name, NULL);
}
/*
* Check for an Empty Element labeled the XML/SGML way
*/
if ((CUR == '/') && (NXT(1) == '>')) {
SKIP(2);
if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
ctxt->sax->endElement(ctxt->userData, name);
htmlnamePop(ctxt);
return;
}
if (CUR == '>') {
NEXT;
} else {
htmlParseErr(ctxt, XML_ERR_GT_REQUIRED,
"Couldn't find end of Start Tag %s\n", name, NULL);
/*
* end of parsing of this node.
*/
if (xmlStrEqual(name, ctxt->name)) {
nodePop(ctxt);
htmlnamePop(ctxt);
}
if (ctxt->record_info)
htmlNodeInfoPush(ctxt, &node_info);
htmlParserFinishElementParsing(ctxt);
return;
}
/*
* Check for an Empty Element from DTD definition
*/
if ((info != NULL) && (info->empty)) {
if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
ctxt->sax->endElement(ctxt->userData, name);
htmlnamePop(ctxt);
return;
}
if (ctxt->record_info)
htmlNodeInfoPush(ctxt, &node_info);
}
| 172,947
|
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: const SeekHead* Segment::GetSeekHead() const
{
return m_pSeekHead;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const SeekHead* Segment::GetSeekHead() const
| 174,353
|
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 FileUtilProxy::Write(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
const char* buffer,
int bytes_to_write,
WriteCallback* callback) {
if (bytes_to_write <= 0)
return false;
return Start(FROM_HERE, message_loop_proxy,
new RelayWrite(file, offset, buffer, bytes_to_write, callback));
}
Commit Message: Fix a small leak in FileUtilProxy
BUG=none
TEST=green mem bots
Review URL: http://codereview.chromium.org/7669046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool FileUtilProxy::Write(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
const char* buffer,
int bytes_to_write,
WriteCallback* callback) {
if (bytes_to_write <= 0) {
delete callback;
return false;
}
return Start(FROM_HERE, message_loop_proxy,
new RelayWrite(file, offset, buffer, bytes_to_write, callback));
}
| 170,274
|
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: json_t *json_object(void)
{
json_object_t *object = jsonp_malloc(sizeof(json_object_t));
if(!object)
return NULL;
json_init(&object->json, JSON_OBJECT);
if(hashtable_init(&object->hashtable))
{
jsonp_free(object);
return NULL;
}
object->serial = 0;
object->visited = 0;
return &object->json;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310
|
json_t *json_object(void)
{
json_object_t *object = jsonp_malloc(sizeof(json_object_t));
if(!object)
return NULL;
if (!hashtable_seed) {
/* Autoseed */
json_object_seed(0);
}
json_init(&object->json, JSON_OBJECT);
if(hashtable_init(&object->hashtable))
{
jsonp_free(object);
return NULL;
}
object->serial = 0;
object->visited = 0;
return &object->json;
}
| 166,535
|
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: do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
unsigned char arg[128];
int ret = 0;
unsigned int copylen;
struct net *net = sock_net(sk);
struct netns_ipvs *ipvs = net_ipvs(net);
BUG_ON(!net);
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
return -EINVAL;
if (*len < get_arglen[GET_CMDID(cmd)]) {
pr_err("get_ctl: len %u < %u\n",
*len, get_arglen[GET_CMDID(cmd)]);
return -EINVAL;
}
copylen = get_arglen[GET_CMDID(cmd)];
if (copylen > 128)
return -EINVAL;
if (copy_from_user(arg, user, copylen) != 0)
return -EFAULT;
/*
* Handle daemons first since it has its own locking
*/
if (cmd == IP_VS_SO_GET_DAEMON) {
struct ip_vs_daemon_user d[2];
memset(&d, 0, sizeof(d));
if (mutex_lock_interruptible(&ipvs->sync_mutex))
return -ERESTARTSYS;
if (ipvs->sync_state & IP_VS_STATE_MASTER) {
d[0].state = IP_VS_STATE_MASTER;
strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn,
sizeof(d[0].mcast_ifn));
d[0].syncid = ipvs->master_syncid;
}
if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
d[1].state = IP_VS_STATE_BACKUP;
strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn,
sizeof(d[1].mcast_ifn));
d[1].syncid = ipvs->backup_syncid;
}
if (copy_to_user(user, &d, sizeof(d)) != 0)
ret = -EFAULT;
mutex_unlock(&ipvs->sync_mutex);
return ret;
}
if (mutex_lock_interruptible(&__ip_vs_mutex))
return -ERESTARTSYS;
switch (cmd) {
case IP_VS_SO_GET_VERSION:
{
char buf[64];
sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
ret = -EFAULT;
goto out;
}
*len = strlen(buf)+1;
}
break;
case IP_VS_SO_GET_INFO:
{
struct ip_vs_getinfo info;
info.version = IP_VS_VERSION_CODE;
info.size = ip_vs_conn_tab_size;
info.num_services = ipvs->num_services;
if (copy_to_user(user, &info, sizeof(info)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_SERVICES:
{
struct ip_vs_get_services *get;
int size;
get = (struct ip_vs_get_services *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_service_entry) * get->num_services;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_service_entries(net, get, user);
}
break;
case IP_VS_SO_GET_SERVICE:
{
struct ip_vs_service_entry *entry;
struct ip_vs_service *svc;
union nf_inet_addr addr;
entry = (struct ip_vs_service_entry *)arg;
addr.ip = entry->addr;
if (entry->fwmark)
svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark);
else
svc = __ip_vs_service_find(net, AF_INET,
entry->protocol, &addr,
entry->port);
if (svc) {
ip_vs_copy_service(entry, svc);
if (copy_to_user(user, entry, sizeof(*entry)) != 0)
ret = -EFAULT;
} else
ret = -ESRCH;
}
break;
case IP_VS_SO_GET_DESTS:
{
struct ip_vs_get_dests *get;
int size;
get = (struct ip_vs_get_dests *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_dest_entry) * get->num_dests;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_dest_entries(net, get, user);
}
break;
case IP_VS_SO_GET_TIMEOUT:
{
struct ip_vs_timeout_user t;
__ip_vs_get_timeouts(net, &t);
if (copy_to_user(user, &t, sizeof(t)) != 0)
ret = -EFAULT;
}
break;
default:
ret = -EINVAL;
}
out:
mutex_unlock(&__ip_vs_mutex);
return ret;
}
Commit Message: ipvs: fix info leak in getsockopt(IP_VS_SO_GET_TIMEOUT)
If at least one of CONFIG_IP_VS_PROTO_TCP or CONFIG_IP_VS_PROTO_UDP is
not set, __ip_vs_get_timeouts() does not fully initialize the structure
that gets copied to userland and that for leaks up to 12 bytes of kernel
stack. Add an explicit memset(0) before passing the structure to
__ip_vs_get_timeouts() to avoid the info leak.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Wensong Zhang <wensong@linux-vs.org>
Cc: Simon Horman <horms@verge.net.au>
Cc: Julian Anastasov <ja@ssi.bg>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
unsigned char arg[128];
int ret = 0;
unsigned int copylen;
struct net *net = sock_net(sk);
struct netns_ipvs *ipvs = net_ipvs(net);
BUG_ON(!net);
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
return -EINVAL;
if (*len < get_arglen[GET_CMDID(cmd)]) {
pr_err("get_ctl: len %u < %u\n",
*len, get_arglen[GET_CMDID(cmd)]);
return -EINVAL;
}
copylen = get_arglen[GET_CMDID(cmd)];
if (copylen > 128)
return -EINVAL;
if (copy_from_user(arg, user, copylen) != 0)
return -EFAULT;
/*
* Handle daemons first since it has its own locking
*/
if (cmd == IP_VS_SO_GET_DAEMON) {
struct ip_vs_daemon_user d[2];
memset(&d, 0, sizeof(d));
if (mutex_lock_interruptible(&ipvs->sync_mutex))
return -ERESTARTSYS;
if (ipvs->sync_state & IP_VS_STATE_MASTER) {
d[0].state = IP_VS_STATE_MASTER;
strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn,
sizeof(d[0].mcast_ifn));
d[0].syncid = ipvs->master_syncid;
}
if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
d[1].state = IP_VS_STATE_BACKUP;
strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn,
sizeof(d[1].mcast_ifn));
d[1].syncid = ipvs->backup_syncid;
}
if (copy_to_user(user, &d, sizeof(d)) != 0)
ret = -EFAULT;
mutex_unlock(&ipvs->sync_mutex);
return ret;
}
if (mutex_lock_interruptible(&__ip_vs_mutex))
return -ERESTARTSYS;
switch (cmd) {
case IP_VS_SO_GET_VERSION:
{
char buf[64];
sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
ret = -EFAULT;
goto out;
}
*len = strlen(buf)+1;
}
break;
case IP_VS_SO_GET_INFO:
{
struct ip_vs_getinfo info;
info.version = IP_VS_VERSION_CODE;
info.size = ip_vs_conn_tab_size;
info.num_services = ipvs->num_services;
if (copy_to_user(user, &info, sizeof(info)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_SERVICES:
{
struct ip_vs_get_services *get;
int size;
get = (struct ip_vs_get_services *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_service_entry) * get->num_services;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_service_entries(net, get, user);
}
break;
case IP_VS_SO_GET_SERVICE:
{
struct ip_vs_service_entry *entry;
struct ip_vs_service *svc;
union nf_inet_addr addr;
entry = (struct ip_vs_service_entry *)arg;
addr.ip = entry->addr;
if (entry->fwmark)
svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark);
else
svc = __ip_vs_service_find(net, AF_INET,
entry->protocol, &addr,
entry->port);
if (svc) {
ip_vs_copy_service(entry, svc);
if (copy_to_user(user, entry, sizeof(*entry)) != 0)
ret = -EFAULT;
} else
ret = -ESRCH;
}
break;
case IP_VS_SO_GET_DESTS:
{
struct ip_vs_get_dests *get;
int size;
get = (struct ip_vs_get_dests *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_dest_entry) * get->num_dests;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_dest_entries(net, get, user);
}
break;
case IP_VS_SO_GET_TIMEOUT:
{
struct ip_vs_timeout_user t;
memset(&t, 0, sizeof(t));
__ip_vs_get_timeouts(net, &t);
if (copy_to_user(user, &t, sizeof(t)) != 0)
ret = -EFAULT;
}
break;
default:
ret = -EINVAL;
}
out:
mutex_unlock(&__ip_vs_mutex);
return ret;
}
| 166,186
|
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 GLES2DecoderImpl::TexStorageImpl(GLenum target,
GLsizei levels,
GLenum internal_format,
GLsizei width,
GLsizei height,
GLsizei depth,
ContextState::Dimension dimension,
const char* function_name) {
if (levels == 0) {
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "levels == 0");
return;
}
bool is_compressed_format = IsCompressedTextureFormat(internal_format);
if (is_compressed_format && target == GL_TEXTURE_3D) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "target invalid for format");
return;
}
bool is_invalid_texstorage_size = width < 1 || height < 1 || depth < 1;
if (!texture_manager()->ValidForTarget(target, 0, width, height, depth) ||
is_invalid_texstorage_size ||
TextureManager::ComputeMipMapCount(target, width, height, depth) <
levels) {
LOCAL_SET_GL_ERROR(
GL_INVALID_VALUE, function_name, "dimensions out of range");
return;
}
TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget(
&state_, target);
if (!texture_ref) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "unknown texture for target");
return;
}
Texture* texture = texture_ref->texture();
if (texture->IsAttachedToFramebuffer()) {
framebuffer_state_.clear_state_dirty = true;
}
if (texture->IsImmutable()) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "texture is immutable");
return;
}
GLenum format = TextureManager::ExtractFormatFromStorageFormat(
internal_format);
GLenum type = TextureManager::ExtractTypeFromStorageFormat(internal_format);
{
GLsizei level_width = width;
GLsizei level_height = height;
GLsizei level_depth = depth;
base::CheckedNumeric<uint32_t> estimated_size(0);
PixelStoreParams params;
params.alignment = 1;
for (int ii = 0; ii < levels; ++ii) {
uint32_t size;
if (is_compressed_format) {
GLsizei level_size;
if (!GetCompressedTexSizeInBytes(
function_name, level_width, level_height, level_depth,
internal_format, &level_size, state_.GetErrorState())) {
return;
}
size = static_cast<uint32_t>(level_size);
} else {
if (!GLES2Util::ComputeImageDataSizesES3(level_width,
level_height,
level_depth,
format, type,
params,
&size,
nullptr, nullptr,
nullptr, nullptr)) {
LOCAL_SET_GL_ERROR(
GL_OUT_OF_MEMORY, function_name, "dimensions too large");
return;
}
}
estimated_size += size;
level_width = std::max(1, level_width >> 1);
level_height = std::max(1, level_height >> 1);
if (target == GL_TEXTURE_3D)
level_depth = std::max(1, level_depth >> 1);
}
if (!estimated_size.IsValid()) {
LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, function_name, "out of memory");
return;
}
}
GLenum compatibility_internal_format =
texture_manager()->AdjustTexStorageFormat(feature_info_.get(),
internal_format);
const CompressedFormatInfo* format_info =
GetCompressedFormatInfo(internal_format);
if (format_info != nullptr && !format_info->support_check(*feature_info_)) {
compatibility_internal_format = format_info->decompressed_internal_format;
}
if (workarounds().reset_base_mipmap_level_before_texstorage &&
texture->base_level() > 0)
api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0);
if (dimension == ContextState::k2D) {
api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format,
width, height);
} else {
api()->glTexStorage3DFn(target, levels, compatibility_internal_format,
width, height, depth);
}
if (workarounds().reset_base_mipmap_level_before_texstorage &&
texture->base_level() > 0)
api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL,
texture->base_level());
{
GLsizei level_width = width;
GLsizei level_height = height;
GLsizei level_depth = depth;
GLenum adjusted_internal_format =
feature_info_->IsWebGL1OrES2Context() ? format : internal_format;
for (int ii = 0; ii < levels; ++ii) {
if (target == GL_TEXTURE_CUBE_MAP) {
for (int jj = 0; jj < 6; ++jj) {
GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X + jj;
texture_manager()->SetLevelInfo(
texture_ref, face, ii, adjusted_internal_format, level_width,
level_height, 1, 0, format, type, gfx::Rect());
}
} else {
texture_manager()->SetLevelInfo(
texture_ref, target, ii, adjusted_internal_format, level_width,
level_height, level_depth, 0, format, type, gfx::Rect());
}
level_width = std::max(1, level_width >> 1);
level_height = std::max(1, level_height >> 1);
if (target == GL_TEXTURE_3D)
level_depth = std::max(1, level_depth >> 1);
}
texture->ApplyFormatWorkarounds(feature_info_.get());
texture->SetImmutable(true);
}
}
Commit Message: Implement immutable texture base/max level clamping
It seems some drivers fail to handle that gracefully, so let's always clamp
to be on the safe side.
BUG=877874
TEST=test case in the bug, gpu_unittests
R=kbr@chromium.org
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: I6d93cb9389ea70525df4604112223604577582a2
Reviewed-on: https://chromium-review.googlesource.com/1194994
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Commit-Queue: Zhenyao Mo <zmo@chromium.org>
Cr-Commit-Position: refs/heads/master@{#587264}
CWE ID: CWE-119
|
void GLES2DecoderImpl::TexStorageImpl(GLenum target,
GLsizei levels,
GLenum internal_format,
GLsizei width,
GLsizei height,
GLsizei depth,
ContextState::Dimension dimension,
const char* function_name) {
if (levels == 0) {
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "levels == 0");
return;
}
bool is_compressed_format = IsCompressedTextureFormat(internal_format);
if (is_compressed_format && target == GL_TEXTURE_3D) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "target invalid for format");
return;
}
bool is_invalid_texstorage_size = width < 1 || height < 1 || depth < 1;
if (!texture_manager()->ValidForTarget(target, 0, width, height, depth) ||
is_invalid_texstorage_size ||
TextureManager::ComputeMipMapCount(target, width, height, depth) <
levels) {
LOCAL_SET_GL_ERROR(
GL_INVALID_VALUE, function_name, "dimensions out of range");
return;
}
TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget(
&state_, target);
if (!texture_ref) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "unknown texture for target");
return;
}
Texture* texture = texture_ref->texture();
if (texture->IsAttachedToFramebuffer()) {
framebuffer_state_.clear_state_dirty = true;
}
if (texture->IsImmutable()) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "texture is immutable");
return;
}
GLenum format = TextureManager::ExtractFormatFromStorageFormat(
internal_format);
GLenum type = TextureManager::ExtractTypeFromStorageFormat(internal_format);
{
GLsizei level_width = width;
GLsizei level_height = height;
GLsizei level_depth = depth;
base::CheckedNumeric<uint32_t> estimated_size(0);
PixelStoreParams params;
params.alignment = 1;
for (int ii = 0; ii < levels; ++ii) {
uint32_t size;
if (is_compressed_format) {
GLsizei level_size;
if (!GetCompressedTexSizeInBytes(
function_name, level_width, level_height, level_depth,
internal_format, &level_size, state_.GetErrorState())) {
return;
}
size = static_cast<uint32_t>(level_size);
} else {
if (!GLES2Util::ComputeImageDataSizesES3(level_width,
level_height,
level_depth,
format, type,
params,
&size,
nullptr, nullptr,
nullptr, nullptr)) {
LOCAL_SET_GL_ERROR(
GL_OUT_OF_MEMORY, function_name, "dimensions too large");
return;
}
}
estimated_size += size;
level_width = std::max(1, level_width >> 1);
level_height = std::max(1, level_height >> 1);
if (target == GL_TEXTURE_3D)
level_depth = std::max(1, level_depth >> 1);
}
if (!estimated_size.IsValid()) {
LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, function_name, "out of memory");
return;
}
}
GLenum compatibility_internal_format =
texture_manager()->AdjustTexStorageFormat(feature_info_.get(),
internal_format);
const CompressedFormatInfo* format_info =
GetCompressedFormatInfo(internal_format);
if (format_info != nullptr && !format_info->support_check(*feature_info_)) {
compatibility_internal_format = format_info->decompressed_internal_format;
}
{
GLsizei level_width = width;
GLsizei level_height = height;
GLsizei level_depth = depth;
GLenum adjusted_internal_format =
feature_info_->IsWebGL1OrES2Context() ? format : internal_format;
for (int ii = 0; ii < levels; ++ii) {
if (target == GL_TEXTURE_CUBE_MAP) {
for (int jj = 0; jj < 6; ++jj) {
GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X + jj;
texture_manager()->SetLevelInfo(
texture_ref, face, ii, adjusted_internal_format, level_width,
level_height, 1, 0, format, type, gfx::Rect());
}
} else {
texture_manager()->SetLevelInfo(
texture_ref, target, ii, adjusted_internal_format, level_width,
level_height, level_depth, 0, format, type, gfx::Rect());
}
level_width = std::max(1, level_width >> 1);
level_height = std::max(1, level_height >> 1);
if (target == GL_TEXTURE_3D)
level_depth = std::max(1, level_depth >> 1);
}
texture->ApplyFormatWorkarounds(feature_info_.get());
texture->SetImmutable(true);
}
if (workarounds().reset_base_mipmap_level_before_texstorage &&
texture->base_level() > 0)
api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0);
// TODO(zmo): We might need to emulate TexStorage using TexImage or
// CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying
// driver is lower than 4.2 and ARB_texture_storage extension doesn't exist.
if (dimension == ContextState::k2D) {
api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format,
width, height);
} else {
api()->glTexStorage3DFn(target, levels, compatibility_internal_format,
width, height, depth);
}
if (workarounds().reset_base_mipmap_level_before_texstorage &&
texture->base_level() > 0) {
// Note base_level is already clamped due to texture->SetImmutable(true).
// This is necessary for certain NVidia Linux drivers; otherwise they
// may trigger segmentation fault. See https://crbug.com/877874.
api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL,
texture->base_level());
}
}
| 172,659
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void svc_rdma_put_req_map(struct svcxprt_rdma *xprt,
struct svc_rdma_req_map *map)
{
spin_lock(&xprt->sc_map_lock);
list_add(&map->free, &xprt->sc_maps);
spin_unlock(&xprt->sc_map_lock);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
void svc_rdma_put_req_map(struct svcxprt_rdma *xprt,
| 168,183
|
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 AppCacheDatabase::ReadCacheRecord(
const sql::Statement& statement, CacheRecord* record) {
record->cache_id = statement.ColumnInt64(0);
record->group_id = statement.ColumnInt64(1);
record->online_wildcard = statement.ColumnBool(2);
record->update_time =
base::Time::FromInternalValue(statement.ColumnInt64(3));
record->cache_size = statement.ColumnInt64(4);
}
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 <staphany@chromium.org>
> Reviewed-by: Victor Costan <pwnall@chromium.org>
> Reviewed-by: Marijn Kruisselbrink <mek@chromium.org>
> 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 <pwnall@chromium.org>
Commit-Queue: Staphany Park <staphany@chromium.org>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200
|
void AppCacheDatabase::ReadCacheRecord(
const sql::Statement& statement, CacheRecord* record) {
record->cache_id = statement.ColumnInt64(0);
record->group_id = statement.ColumnInt64(1);
record->online_wildcard = statement.ColumnBool(2);
record->update_time =
base::Time::FromInternalValue(statement.ColumnInt64(3));
record->cache_size = statement.ColumnInt64(4);
record->padding_size = statement.ColumnInt64(5);
}
| 172,981
|
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: StorageHandler::IndexedDBObserver* StorageHandler::GetIndexedDBObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!indexed_db_observer_) {
indexed_db_observer_ = std::make_unique<IndexedDBObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<IndexedDBContextImpl*>(
process_->GetStoragePartition()->GetIndexedDBContext()));
}
return indexed_db_observer_.get();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
StorageHandler::IndexedDBObserver* StorageHandler::GetIndexedDBObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!indexed_db_observer_) {
indexed_db_observer_ = std::make_unique<IndexedDBObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<IndexedDBContextImpl*>(
storage_partition_->GetIndexedDBContext()));
}
return indexed_db_observer_.get();
}
| 172,772
|
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 BN_hex2bn(BIGNUM **bn, const char *a)
{
BIGNUM *ret = NULL;
BN_ULONG l = 0;
int neg = 0, h, m, i, j, k, c;
int num;
if ((a == NULL) || (*a == '\0'))
return (0);
if (*a == '-') {
neg = 1;
a++;
a++;
}
for (i = 0; isxdigit((unsigned char)a[i]); i++) ;
num = i + neg;
if (bn == NULL)
return (0);
} else {
ret = *bn;
BN_zero(ret);
}
Commit Message:
CWE ID:
|
int BN_hex2bn(BIGNUM **bn, const char *a)
{
BIGNUM *ret = NULL;
BN_ULONG l = 0;
int neg = 0, h, m, i, j, k, c;
int num;
if ((a == NULL) || (*a == '\0'))
return (0);
if (*a == '-') {
neg = 1;
a++;
a++;
}
for (i = 0; i <= (INT_MAX/4) && isxdigit((unsigned char)a[i]); i++)
continue;
if (i > INT_MAX/4)
goto err;
num = i + neg;
if (bn == NULL)
return (0);
} else {
ret = *bn;
BN_zero(ret);
}
| 165,250
|
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: lldp_private_8023_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8023_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8023_SUBTYPE_MACPHY:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)",
bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)",
bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)),
EXTRACT_16BITS(tptr + 5)));
ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)",
tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)),
EXTRACT_16BITS(tptr + 7)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s",
bittok2str(lldp_mdi_values, "none", *(tptr+4)),
tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)),
tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6))));
break;
case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u",
bittok2str(lldp_aggregation_values, "none", *(tptr+4)),
EXTRACT_32BITS(tptr + 5)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MTU:
ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
Commit Message: CVE-2017-13054/LLDP: add a missing length check
In lldp_private_8023_print() the case block for subtype 4 (Maximum Frame
Size TLV, IEEE 802.3bc-2009 Section 79.3.4) did not include the length
check and could over-read the input buffer, put it right.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
lldp_private_8023_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8023_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8023_SUBTYPE_MACPHY:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)",
bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)",
bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)),
EXTRACT_16BITS(tptr + 5)));
ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)",
tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)),
EXTRACT_16BITS(tptr + 7)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s",
bittok2str(lldp_mdi_values, "none", *(tptr+4)),
tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)),
tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6))));
break;
case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u",
bittok2str(lldp_aggregation_values, "none", *(tptr+4)),
EXTRACT_32BITS(tptr + 5)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MTU:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
| 167,819
|
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 GraphicsContext::clip(const Path& path)
{
#ifdef __WXMAC__
if (paintingDisabled())
return;
wxGraphicsContext* gc = m_data->context->GetGraphicsContext();
CGContextRef context = (CGContextRef)gc->GetNativeContext();
if (!context)
return;
CGPathRef nativePath = (CGPathRef)path.platformPath()->GetNativePath();
if (path.isEmpty())
CGContextClipToRect(context, CGRectZero);
else if (nativePath) {
CGContextBeginPath(context);
CGContextAddPath(context, nativePath);
CGContextClip(context);
}
#else
notImplemented();
#endif
}
Commit Message: Reviewed by Kevin Ollivier.
[wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support.
https://bugs.webkit.org/show_bug.cgi?id=60847
git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
void GraphicsContext::clip(const Path& path)
{
if (paintingDisabled())
return;
// if the path is empty, we clip against a zero rect to reduce the clipping region to
// nothing - which is the intended behavior of clip() if the path is empty.
if (path.isEmpty())
m_data->context->SetClippingRegion(0, 0, 0, 0);
else
clipPath(path, RULE_NONZERO);
}
| 170,421
|
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: mainloop_destroy_trigger(crm_trigger_t * source)
{
source->trigger = FALSE;
if (source->id > 0) {
g_source_remove(source->id);
}
return TRUE;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
mainloop_destroy_trigger(crm_trigger_t * source)
{
source->trigger = FALSE;
if (source->id > 0) {
g_source_remove(source->id);
source->id = 0;
}
return TRUE;
}
| 166,157
|
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 OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event,
bool in_drag) {
const ui::OSExchangeData& data = event.data();
if (data.HasURL()) {
GURL url;
string16 title;
if (data.GetURLAndTitle(&url, &title)) {
string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec())));
SetUserText(text);
if (url.spec().length() == text.length())
model()->AcceptInput(CURRENT_TAB, true);
return CopyOrLinkDragOperation(event.source_operations());
}
} else if (data.HasString()) {
int string_drop_position = drop_highlight_position();
string16 text;
if ((string_drop_position != -1 || !in_drag) && data.GetString(&text)) {
DCHECK(string_drop_position == -1 ||
((string_drop_position >= 0) &&
(string_drop_position <= GetTextLength())));
if (in_drag) {
if (event.source_operations()== ui::DragDropTypes::DRAG_MOVE)
MoveSelectedText(string_drop_position);
else
InsertText(string_drop_position, text);
} else {
PasteAndGo(CollapseWhitespace(text, true));
}
return CopyOrLinkDragOperation(event.source_operations());
}
}
return ui::DragDropTypes::DRAG_NONE;
}
Commit Message: Change omnibox behavior when stripping javascript schema to navigate after stripping the schema on drag drop.
BUG=109245
TEST=N/A
Review URL: http://codereview.chromium.org/9116016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116692 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
int OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event,
bool in_drag) {
const ui::OSExchangeData& data = event.data();
if (data.HasURL()) {
GURL url;
string16 title;
if (data.GetURLAndTitle(&url, &title)) {
string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec())));
SetUserText(text);
model()->AcceptInput(CURRENT_TAB, true);
return CopyOrLinkDragOperation(event.source_operations());
}
} else if (data.HasString()) {
int string_drop_position = drop_highlight_position();
string16 text;
if ((string_drop_position != -1 || !in_drag) && data.GetString(&text)) {
DCHECK(string_drop_position == -1 ||
((string_drop_position >= 0) &&
(string_drop_position <= GetTextLength())));
if (in_drag) {
if (event.source_operations()== ui::DragDropTypes::DRAG_MOVE)
MoveSelectedText(string_drop_position);
else
InsertText(string_drop_position, text);
} else {
PasteAndGo(CollapseWhitespace(text, true));
}
return CopyOrLinkDragOperation(event.source_operations());
}
}
return ui::DragDropTypes::DRAG_NONE;
}
| 170,973
|
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: OneClickSigninSyncStarter::OneClickSigninSyncStarter(
Profile* profile,
Browser* browser,
const std::string& session_index,
const std::string& email,
const std::string& password,
StartSyncMode start_mode,
bool force_same_tab_navigation,
ConfirmationRequired confirmation_required)
: start_mode_(start_mode),
force_same_tab_navigation_(force_same_tab_navigation),
confirmation_required_(confirmation_required),
weak_pointer_factory_(this) {
DCHECK(profile);
BrowserList::AddObserver(this);
Initialize(profile, browser);
SigninManager* manager = SigninManagerFactory::GetForProfile(profile_);
SigninManager::OAuthTokenFetchedCallback callback;
callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin,
weak_pointer_factory_.GetWeakPtr());
manager->StartSignInWithCredentials(session_index, email, password, callback);
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
OneClickSigninSyncStarter::OneClickSigninSyncStarter(
Profile* profile,
Browser* browser,
const std::string& session_index,
const std::string& email,
const std::string& password,
StartSyncMode start_mode,
bool force_same_tab_navigation,
ConfirmationRequired confirmation_required,
SyncPromoUI::Source source)
: start_mode_(start_mode),
force_same_tab_navigation_(force_same_tab_navigation),
confirmation_required_(confirmation_required),
source_(source),
weak_pointer_factory_(this) {
DCHECK(profile);
BrowserList::AddObserver(this);
Initialize(profile, browser);
SigninManager* manager = SigninManagerFactory::GetForProfile(profile_);
SigninManager::OAuthTokenFetchedCallback callback;
callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin,
weak_pointer_factory_.GetWeakPtr());
manager->StartSignInWithCredentials(session_index, email, password, callback);
}
| 171,245
|
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 DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) {
wchar_t argument[50];
for (int i = 0; argument_c[i]; ++i)
argument[i] = argument_c[i];
int argument_len = lstrlen(argument);
int command_line_len = lstrlen(command_line);
while (command_line_len > argument_len) {
wchar_t first_char = command_line[0];
wchar_t last_char = command_line[argument_len+1];
if ((first_char == L'-' || first_char == L'/') &&
(last_char == L' ' || last_char == 0 || last_char == L'=')) {
command_line[argument_len+1] = 0;
if (lstrcmpi(command_line+1, argument) == 0) {
command_line[argument_len+1] = last_char;
return true;
}
command_line[argument_len+1] = last_char;
}
++command_line;
--command_line_len;
}
return false;
}
Commit Message: Fix null-termination on string copy in debug-on-start code.
BUG=73740
Review URL: http://codereview.chromium.org/6549019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75629 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) {
wchar_t argument[50] = {};
for (int i = 0; argument_c[i]; ++i)
argument[i] = argument_c[i];
int argument_len = lstrlen(argument);
int command_line_len = lstrlen(command_line);
while (command_line_len > argument_len) {
wchar_t first_char = command_line[0];
wchar_t last_char = command_line[argument_len+1];
if ((first_char == L'-' || first_char == L'/') &&
(last_char == L' ' || last_char == 0 || last_char == L'=')) {
command_line[argument_len+1] = 0;
if (lstrcmpi(command_line+1, argument) == 0) {
command_line[argument_len+1] = last_char;
return true;
}
command_line[argument_len+1] = last_char;
}
++command_line;
--command_line_len;
}
return false;
}
| 170,650
|
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: standard_info_part2(standard_display *dp, png_const_structp pp,
png_const_infop pi, int nImages)
{
/* Record cbRow now that it can be found. */
dp->pixel_size = bit_size(pp, png_get_color_type(pp, pi),
png_get_bit_depth(pp, pi));
dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
dp->cbRow = png_get_rowbytes(pp, pi);
/* Validate the rowbytes here again. */
if (dp->cbRow != (dp->bit_width+7)/8)
png_error(pp, "bad png_get_rowbytes calculation");
/* Then ensure there is enough space for the output image(s). */
store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
standard_info_part2(standard_display *dp, png_const_structp pp,
png_const_infop pi, int nImages)
{
/* Record cbRow now that it can be found. */
{
png_byte ct = png_get_color_type(pp, pi);
png_byte bd = png_get_bit_depth(pp, pi);
if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
dp->filler)
ct |= 4; /* handle filler as faked alpha channel */
dp->pixel_size = bit_size(pp, ct, bd);
}
dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
dp->cbRow = png_get_rowbytes(pp, pi);
/* Validate the rowbytes here again. */
if (dp->cbRow != (dp->bit_width+7)/8)
png_error(pp, "bad png_get_rowbytes calculation");
/* Then ensure there is enough space for the output image(s). */
store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
}
| 173,699
|
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: ProcRenderAddGlyphs (ClientPtr client)
{
GlyphSetPtr glyphSet;
REQUEST(xRenderAddGlyphsReq);
GlyphNewRec glyphsLocal[NLOCALGLYPH];
GlyphNewPtr glyphsBase, glyphs, glyph_new;
int remain, nglyphs;
CARD32 *gids;
xGlyphInfo *gi;
CARD8 *bits;
unsigned int size;
int err;
int i, screen;
PicturePtr pSrc = NULL, pDst = NULL;
PixmapPtr pSrcPix = NULL, pDstPix = NULL;
CARD32 component_alpha;
REQUEST_AT_LEAST_SIZE(xRenderAddGlyphsReq);
err = dixLookupResourceByType((pointer *)&glyphSet, stuff->glyphset, GlyphSetType,
client, DixAddAccess);
if (err != Success)
{
client->errorValue = stuff->glyphset;
return err;
}
err = BadAlloc;
nglyphs = stuff->nglyphs;
if (nglyphs > UINT32_MAX / sizeof(GlyphNewRec))
return BadAlloc;
component_alpha = NeedsComponent (glyphSet->format->format);
if (nglyphs <= NLOCALGLYPH) {
memset (glyphsLocal, 0, sizeof (glyphsLocal));
glyphsBase = glyphsLocal;
}
else
{
glyphsBase = (GlyphNewPtr)calloc(nglyphs, sizeof (GlyphNewRec));
if (!glyphsBase)
return BadAlloc;
}
remain = (client->req_len << 2) - sizeof (xRenderAddGlyphsReq);
glyphs = glyphsBase;
gids = (CARD32 *) (stuff + 1);
gi = (xGlyphInfo *) (gids + nglyphs);
bits = (CARD8 *) (gi + nglyphs);
remain -= (sizeof (CARD32) + sizeof (xGlyphInfo)) * nglyphs;
for (i = 0; i < nglyphs; i++)
{
size_t padded_width;
size = gi[i].height * padded_width;
if (remain < size)
break;
err = HashGlyph (&gi[i], bits, size, glyph_new->sha1);
if (err)
goto bail;
glyph_new->glyph = FindGlyphByHash (glyph_new->sha1,
glyphSet->fdepth);
if (glyph_new->glyph && glyph_new->glyph != DeletedGlyph)
{
glyph_new->found = TRUE;
}
else
{
GlyphPtr glyph;
glyph_new->found = FALSE;
glyph_new->glyph = glyph = AllocateGlyph (&gi[i], glyphSet->fdepth);
if (! glyph)
{
err = BadAlloc;
goto bail;
}
for (screen = 0; screen < screenInfo.numScreens; screen++)
{
int width = gi[i].width;
int height = gi[i].height;
int depth = glyphSet->format->depth;
ScreenPtr pScreen;
int error;
/* Skip work if it's invisibly small anyway */
if (!width || !height)
break;
pScreen = screenInfo.screens[screen];
pSrcPix = GetScratchPixmapHeader (pScreen,
width, height,
depth, depth,
-1, bits);
if (! pSrcPix)
{
err = BadAlloc;
goto bail;
}
pSrc = CreatePicture (0, &pSrcPix->drawable,
glyphSet->format, 0, NULL,
serverClient, &error);
if (! pSrc)
{
err = BadAlloc;
goto bail;
}
pDstPix = (pScreen->CreatePixmap) (pScreen,
width, height, depth,
CREATE_PIXMAP_USAGE_GLYPH_PICTURE);
if (!pDstPix)
{
err = BadAlloc;
goto bail;
}
GlyphPicture (glyph)[screen] = pDst =
CreatePicture (0, &pDstPix->drawable,
glyphSet->format,
CPComponentAlpha, &component_alpha,
serverClient, &error);
/* The picture takes a reference to the pixmap, so we
drop ours. */
(pScreen->DestroyPixmap) (pDstPix);
pDstPix = NULL;
if (! pDst)
{
err = BadAlloc;
goto bail;
}
CompositePicture (PictOpSrc,
pSrc,
None,
pDst,
0, 0,
0, 0,
0, 0,
width, height);
FreePicture ((pointer) pSrc, 0);
pSrc = NULL;
FreeScratchPixmapHeader (pSrcPix);
pSrcPix = NULL;
}
memcpy (glyph_new->glyph->sha1, glyph_new->sha1, 20);
}
glyph_new->id = gids[i];
if (size & 3)
size += 4 - (size & 3);
bits += size;
remain -= size;
}
if (remain || i < nglyphs)
{
err = BadLength;
goto bail;
}
if (!ResizeGlyphSet (glyphSet, nglyphs))
{
err = BadAlloc;
goto bail;
}
for (i = 0; i < nglyphs; i++)
AddGlyph (glyphSet, glyphs[i].glyph, glyphs[i].id);
if (glyphsBase != glyphsLocal)
free(glyphsBase);
return Success;
bail:
if (pSrc)
FreePicture ((pointer) pSrc, 0);
if (pSrcPix)
FreeScratchPixmapHeader (pSrcPix);
for (i = 0; i < nglyphs; i++)
if (glyphs[i].glyph && ! glyphs[i].found)
free(glyphs[i].glyph);
if (glyphsBase != glyphsLocal)
free(glyphsBase);
return err;
}
Commit Message:
CWE ID: CWE-20
|
ProcRenderAddGlyphs (ClientPtr client)
{
GlyphSetPtr glyphSet;
REQUEST(xRenderAddGlyphsReq);
GlyphNewRec glyphsLocal[NLOCALGLYPH];
GlyphNewPtr glyphsBase, glyphs, glyph_new;
int remain, nglyphs;
CARD32 *gids;
xGlyphInfo *gi;
CARD8 *bits;
unsigned int size;
int err;
int i, screen;
PicturePtr pSrc = NULL, pDst = NULL;
PixmapPtr pSrcPix = NULL, pDstPix = NULL;
CARD32 component_alpha;
REQUEST_AT_LEAST_SIZE(xRenderAddGlyphsReq);
err = dixLookupResourceByType((pointer *)&glyphSet, stuff->glyphset, GlyphSetType,
client, DixAddAccess);
if (err != Success)
{
client->errorValue = stuff->glyphset;
return err;
}
err = BadAlloc;
nglyphs = stuff->nglyphs;
if (nglyphs > UINT32_MAX / sizeof(GlyphNewRec))
return BadAlloc;
component_alpha = NeedsComponent (glyphSet->format->format);
if (nglyphs <= NLOCALGLYPH) {
memset (glyphsLocal, 0, sizeof (glyphsLocal));
glyphsBase = glyphsLocal;
}
else
{
glyphsBase = (GlyphNewPtr)calloc(nglyphs, sizeof (GlyphNewRec));
if (!glyphsBase)
return BadAlloc;
}
remain = (client->req_len << 2) - sizeof (xRenderAddGlyphsReq);
glyphs = glyphsBase;
gids = (CARD32 *) (stuff + 1);
gi = (xGlyphInfo *) (gids + nglyphs);
bits = (CARD8 *) (gi + nglyphs);
remain -= (sizeof (CARD32) + sizeof (xGlyphInfo)) * nglyphs;
/* protect against bad nglyphs */
if (gi < stuff || gi > ((CARD32 *)stuff + client->req_len) ||
bits < stuff || bits > ((CARD32 *)stuff + client->req_len)) {
err = BadLength;
goto bail;
}
for (i = 0; i < nglyphs; i++)
{
size_t padded_width;
size = gi[i].height * padded_width;
if (remain < size)
break;
err = HashGlyph (&gi[i], bits, size, glyph_new->sha1);
if (err)
goto bail;
glyph_new->glyph = FindGlyphByHash (glyph_new->sha1,
glyphSet->fdepth);
if (glyph_new->glyph && glyph_new->glyph != DeletedGlyph)
{
glyph_new->found = TRUE;
}
else
{
GlyphPtr glyph;
glyph_new->found = FALSE;
glyph_new->glyph = glyph = AllocateGlyph (&gi[i], glyphSet->fdepth);
if (! glyph)
{
err = BadAlloc;
goto bail;
}
for (screen = 0; screen < screenInfo.numScreens; screen++)
{
int width = gi[i].width;
int height = gi[i].height;
int depth = glyphSet->format->depth;
ScreenPtr pScreen;
int error;
/* Skip work if it's invisibly small anyway */
if (!width || !height)
break;
pScreen = screenInfo.screens[screen];
pSrcPix = GetScratchPixmapHeader (pScreen,
width, height,
depth, depth,
-1, bits);
if (! pSrcPix)
{
err = BadAlloc;
goto bail;
}
pSrc = CreatePicture (0, &pSrcPix->drawable,
glyphSet->format, 0, NULL,
serverClient, &error);
if (! pSrc)
{
err = BadAlloc;
goto bail;
}
pDstPix = (pScreen->CreatePixmap) (pScreen,
width, height, depth,
CREATE_PIXMAP_USAGE_GLYPH_PICTURE);
if (!pDstPix)
{
err = BadAlloc;
goto bail;
}
GlyphPicture (glyph)[screen] = pDst =
CreatePicture (0, &pDstPix->drawable,
glyphSet->format,
CPComponentAlpha, &component_alpha,
serverClient, &error);
/* The picture takes a reference to the pixmap, so we
drop ours. */
(pScreen->DestroyPixmap) (pDstPix);
pDstPix = NULL;
if (! pDst)
{
err = BadAlloc;
goto bail;
}
CompositePicture (PictOpSrc,
pSrc,
None,
pDst,
0, 0,
0, 0,
0, 0,
width, height);
FreePicture ((pointer) pSrc, 0);
pSrc = NULL;
FreeScratchPixmapHeader (pSrcPix);
pSrcPix = NULL;
}
memcpy (glyph_new->glyph->sha1, glyph_new->sha1, 20);
}
glyph_new->id = gids[i];
if (size & 3)
size += 4 - (size & 3);
bits += size;
remain -= size;
}
if (remain || i < nglyphs)
{
err = BadLength;
goto bail;
}
if (!ResizeGlyphSet (glyphSet, nglyphs))
{
err = BadAlloc;
goto bail;
}
for (i = 0; i < nglyphs; i++)
AddGlyph (glyphSet, glyphs[i].glyph, glyphs[i].id);
if (glyphsBase != glyphsLocal)
free(glyphsBase);
return Success;
bail:
if (pSrc)
FreePicture ((pointer) pSrc, 0);
if (pSrcPix)
FreeScratchPixmapHeader (pSrcPix);
for (i = 0; i < nglyphs; i++)
if (glyphs[i].glyph && ! glyphs[i].found)
free(glyphs[i].glyph);
if (glyphsBase != glyphsLocal)
free(glyphsBase);
return err;
}
| 165,268
|
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 rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct bt_security sec;
int len, err = 0;
BT_DBG("sk %p", sk);
if (level == SOL_RFCOMM)
return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen);
if (level != SOL_BLUETOOTH)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case BT_SECURITY:
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
break;
}
sec.level = rfcomm_pi(sk)->sec_level;
len = min_t(unsigned int, len, sizeof(sec));
if (copy_to_user(optval, (char *) &sec, len))
err = -EFAULT;
break;
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags),
(u32 __user *) optval))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
Commit Message: Bluetooth: RFCOMM - Fix info leak in getsockopt(BT_SECURITY)
The RFCOMM code fails to initialize the key_size member of struct
bt_security before copying it to userland -- that for leaking one
byte kernel stack. Initialize key_size with 0 to avoid the info
leak.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Marcel Holtmann <marcel@holtmann.org>
Cc: Gustavo Padovan <gustavo@padovan.org>
Cc: Johan Hedberg <johan.hedberg@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct bt_security sec;
int len, err = 0;
BT_DBG("sk %p", sk);
if (level == SOL_RFCOMM)
return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen);
if (level != SOL_BLUETOOTH)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case BT_SECURITY:
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
break;
}
sec.level = rfcomm_pi(sk)->sec_level;
sec.key_size = 0;
len = min_t(unsigned int, len, sizeof(sec));
if (copy_to_user(optval, (char *) &sec, len))
err = -EFAULT;
break;
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags),
(u32 __user *) optval))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
| 169,897
|
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 RunExtremalCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int max_error = 0;
int total_error = 0;
const int count_test_block = 100000;
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < 64; ++j) {
src[j] = rnd.Rand8() % 2 ? 255 : 0;
dst[j] = src[j] > 0 ? 0 : 255;
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(
RunFwdTxfm(test_input_block, test_temp_block, pitch_));
REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < 64; ++j) {
const int diff = dst[j] - src[j];
const int error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
EXPECT_GE(1, max_error)
<< "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has"
<< "an individual roundtrip error > 1";
EXPECT_GE(count_test_block/5, total_error)
<< "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has average"
<< " roundtrip error > 1/5 per block";
}
}
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
|
void RunExtremalCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int max_error = 0;
int total_error = 0;
int total_coeff_error = 0;
const int count_test_block = 100000;
DECLARE_ALIGNED(16, int16_t, test_input_block[64]);
DECLARE_ALIGNED(16, tran_low_t, test_temp_block[64]);
DECLARE_ALIGNED(16, tran_low_t, ref_temp_block[64]);
DECLARE_ALIGNED(16, uint8_t, dst[64]);
DECLARE_ALIGNED(16, uint8_t, src[64]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[64]);
DECLARE_ALIGNED(16, uint16_t, src16[64]);
#endif
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < 64; ++j) {
if (bit_depth_ == VPX_BITS_8) {
if (i == 0) {
src[j] = 255;
dst[j] = 0;
} else if (i == 1) {
src[j] = 0;
dst[j] = 255;
} else {
src[j] = rnd.Rand8() % 2 ? 255 : 0;
dst[j] = rnd.Rand8() % 2 ? 255 : 0;
}
test_input_block[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
if (i == 0) {
src16[j] = mask_;
dst16[j] = 0;
} else if (i == 1) {
src16[j] = 0;
dst16[j] = mask_;
} else {
src16[j] = rnd.Rand8() % 2 ? mask_ : 0;
dst16[j] = rnd.Rand8() % 2 ? mask_ : 0;
}
test_input_block[j] = src16[j] - dst16[j];
#endif
}
}
ASM_REGISTER_STATE_CHECK(
RunFwdTxfm(test_input_block, test_temp_block, pitch_));
ASM_REGISTER_STATE_CHECK(
fwd_txfm_ref(test_input_block, ref_temp_block, pitch_, tx_type_));
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, dst, pitch_));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_));
#endif
}
for (int j = 0; j < 64; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const int diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
const int diff = dst[j] - src[j];
#endif
const int error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
const int coeff_diff = test_temp_block[j] - ref_temp_block[j];
total_coeff_error += abs(coeff_diff);
}
EXPECT_GE(1 << 2 * (bit_depth_ - 8), max_error)
<< "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has"
<< "an individual roundtrip error > 1";
EXPECT_GE((count_test_block << 2 * (bit_depth_ - 8))/5, total_error)
<< "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has average"
<< " roundtrip error > 1/5 per block";
EXPECT_EQ(0, total_coeff_error)
<< "Error: Extremal 8x8 FDCT/FHT has"
<< "overflow issues in the intermediate steps > 1";
}
}
| 174,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: void serialize(const char* url)
{
WebURLRequest urlRequest;
urlRequest.initialize();
urlRequest.setURL(KURL(m_baseUrl, url));
m_webViewImpl->mainFrame()->loadRequest(urlRequest);
Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
runPendingTasks();
Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
PageSerializer serializer(&m_resources,
m_rewriteURLs.isEmpty() ? 0: &m_rewriteURLs, m_rewriteFolder);
serializer.serialize(m_webViewImpl->mainFrameImpl()->frame()->page());
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> R=abarth@chromium.org
>
> Review URL: https://codereview.chromium.org/68613003
TBR=tiger@opera.com
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
void serialize(const char* url)
{
WebURLRequest urlRequest;
urlRequest.initialize();
urlRequest.setURL(KURL(m_baseUrl, url));
m_webViewImpl->mainFrame()->loadRequest(urlRequest);
Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
runPendingTasks();
Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
PageSerializer serializer(&m_resources);
serializer.serialize(m_webViewImpl->mainFrameImpl()->frame()->page());
}
| 171,576
|
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: get_princs_2_svc(gprincs_arg *arg, struct svc_req *rqstp)
{
static gprincs_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_gprincs_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;
}
prime_arg = arg->exp;
if (prime_arg == NULL)
prime_arg = "*";
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_LIST,
NULL,
NULL)) {
ret.code = KADM5_AUTH_LIST;
log_unauth("kadm5_get_principals", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_principals((void *)handle,
arg->exp, &ret.princs,
&ret.count);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_principals", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
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
|
get_princs_2_svc(gprincs_arg *arg, struct svc_req *rqstp)
{
static gprincs_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_gprincs_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;
}
prime_arg = arg->exp;
if (prime_arg == NULL)
prime_arg = "*";
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_LIST,
NULL,
NULL)) {
ret.code = KADM5_AUTH_LIST;
log_unauth("kadm5_get_principals", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_principals((void *)handle,
arg->exp, &ret.princs,
&ret.count);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_principals", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,516
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void LauncherView::CalculateIdealBounds(IdealBounds* bounds) {
int available_size = primary_axis_coordinate(width(), height());
if (!available_size)
return;
int x = primary_axis_coordinate(kLeadingInset, 0);
int y = primary_axis_coordinate(0, kLeadingInset);
for (int i = 0; i < view_model_->view_size(); ++i) {
view_model_->set_ideal_bounds(i, gfx::Rect(
x, y, kLauncherPreferredSize, kLauncherPreferredSize));
x = primary_axis_coordinate(x + kLauncherPreferredSize + kButtonSpacing, 0);
y = primary_axis_coordinate(0, y + kLauncherPreferredSize + kButtonSpacing);
}
if (view_model_->view_size() > 0) {
view_model_->set_ideal_bounds(0, gfx::Rect(gfx::Size(
primary_axis_coordinate(kLeadingInset + kLauncherPreferredSize,
kLauncherPreferredSize),
primary_axis_coordinate(kLauncherPreferredSize,
kLeadingInset + kLauncherPreferredSize))));
}
bounds->overflow_bounds.set_size(
gfx::Size(kLauncherPreferredSize, kLauncherPreferredSize));
last_visible_index_ = DetermineLastVisibleIndex(
available_size - kLeadingInset - kLauncherPreferredSize -
kButtonSpacing - kLauncherPreferredSize);
int app_list_index = view_model_->view_size() - 1;
bool show_overflow = (last_visible_index_ + 1 < app_list_index);
for (int i = 0; i < view_model_->view_size(); ++i) {
view_model_->view_at(i)->SetVisible(
i == app_list_index || i <= last_visible_index_);
}
overflow_button_->SetVisible(show_overflow);
if (show_overflow) {
DCHECK_NE(0, view_model_->view_size());
if (last_visible_index_ == -1) {
x = primary_axis_coordinate(kLeadingInset, 0);
y = primary_axis_coordinate(0, kLeadingInset);
} else {
x = primary_axis_coordinate(
view_model_->ideal_bounds(last_visible_index_).right(), 0);
y = primary_axis_coordinate(0,
view_model_->ideal_bounds(last_visible_index_).bottom());
}
gfx::Rect app_list_bounds = view_model_->ideal_bounds(app_list_index);
app_list_bounds.set_x(x);
app_list_bounds.set_y(y);
view_model_->set_ideal_bounds(app_list_index, app_list_bounds);
x = primary_axis_coordinate(x + kLauncherPreferredSize + kButtonSpacing, 0);
y = primary_axis_coordinate(0, y + kLauncherPreferredSize + kButtonSpacing);
bounds->overflow_bounds.set_x(x);
bounds->overflow_bounds.set_y(y);
}
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void LauncherView::CalculateIdealBounds(IdealBounds* bounds) {
int available_size = primary_axis_coordinate(width(), height());
if (!available_size)
return;
int x = primary_axis_coordinate(leading_inset(), 0);
int y = primary_axis_coordinate(0, leading_inset());
for (int i = 0; i < view_model_->view_size(); ++i) {
if (i < first_visible_index_) {
view_model_->set_ideal_bounds(i, gfx::Rect(x, y, 0, 0));
continue;
}
view_model_->set_ideal_bounds(i, gfx::Rect(
x, y, kLauncherPreferredSize, kLauncherPreferredSize));
x = primary_axis_coordinate(x + kLauncherPreferredSize + kButtonSpacing, 0);
y = primary_axis_coordinate(0, y + kLauncherPreferredSize + kButtonSpacing);
}
int app_list_index = view_model_->view_size() - 1;
if (is_overflow_mode()) {
last_visible_index_ = app_list_index - 1;
for (int i = 0; i < view_model_->view_size(); ++i) {
view_model_->view_at(i)->SetVisible(
i >= first_visible_index_ && i <= last_visible_index_);
}
return;
}
if (view_model_->view_size() > 0) {
view_model_->set_ideal_bounds(0, gfx::Rect(gfx::Size(
primary_axis_coordinate(leading_inset() + kLauncherPreferredSize,
kLauncherPreferredSize),
primary_axis_coordinate(kLauncherPreferredSize,
leading_inset() + kLauncherPreferredSize))));
}
bounds->overflow_bounds.set_size(
gfx::Size(kLauncherPreferredSize, kLauncherPreferredSize));
last_visible_index_ = DetermineLastVisibleIndex(
available_size - leading_inset() - kLauncherPreferredSize -
kButtonSpacing - kLauncherPreferredSize);
bool show_overflow = (last_visible_index_ + 1 < app_list_index);
for (int i = 0; i < view_model_->view_size(); ++i) {
view_model_->view_at(i)->SetVisible(
i == app_list_index || i <= last_visible_index_);
}
overflow_button_->SetVisible(show_overflow);
if (show_overflow) {
DCHECK_NE(0, view_model_->view_size());
if (last_visible_index_ == -1) {
x = primary_axis_coordinate(leading_inset(), 0);
y = primary_axis_coordinate(0, leading_inset());
} else {
x = primary_axis_coordinate(
view_model_->ideal_bounds(last_visible_index_).right(), 0);
y = primary_axis_coordinate(0,
view_model_->ideal_bounds(last_visible_index_).bottom());
}
gfx::Rect app_list_bounds = view_model_->ideal_bounds(app_list_index);
bounds->overflow_bounds.set_x(x);
bounds->overflow_bounds.set_y(y);
x = primary_axis_coordinate(x + kLauncherPreferredSize + kButtonSpacing, 0);
y = primary_axis_coordinate(0, y + kLauncherPreferredSize + kButtonSpacing);
app_list_bounds.set_x(x);
app_list_bounds.set_y(y);
view_model_->set_ideal_bounds(app_list_index, app_list_bounds);
} else {
if (overflow_bubble_.get())
overflow_bubble_->Hide();
}
}
| 170,888
|
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 BluetoothDeviceChromeOS::RejectPairing() {
RunPairingCallbacks(REJECTED);
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BluetoothDeviceChromeOS::RejectPairing() {
if (!pairing_context_.get())
return;
pairing_context_->RejectPairing();
}
| 171,232
|
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: CursorImpl::IDBThreadHelper::~IDBThreadHelper() {
cursor_->RemoveCursorFromTransaction();
}
Commit Message: [IndexedDB] Fix Cursor UAF
If the connection is closed before we return a cursor, it dies in
IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on
the correct thread, but we also need to makes sure to remove it from its
transaction.
To make things simpler, we have the cursor remove itself from its
transaction on destruction.
R: pwnall@chromium.org
Bug: 728887
Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2
Reviewed-on: https://chromium-review.googlesource.com/526284
Commit-Queue: Daniel Murphy <dmurph@chromium.org>
Reviewed-by: Victor Costan <pwnall@chromium.org>
Cr-Commit-Position: refs/heads/master@{#477504}
CWE ID: CWE-416
|
CursorImpl::IDBThreadHelper::~IDBThreadHelper() {
| 172,306
|
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 EnqueueData() {
scoped_array<uint8> audio_data(new uint8[kRawDataSize]);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_channel(), 0u);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_frame(), 0u);
size_t length = kRawDataSize / algorithm_.bytes_per_channel();
switch (algorithm_.bytes_per_channel()) {
case 4:
WriteFakeData<int32>(audio_data.get(), length);
break;
case 2:
WriteFakeData<int16>(audio_data.get(), length);
break;
case 1:
WriteFakeData<uint8>(audio_data.get(), length);
break;
default:
NOTREACHED() << "Unsupported audio bit depth in crossfade.";
}
algorithm_.EnqueueBuffer(new DataBuffer(audio_data.Pass(), kRawDataSize));
bytes_enqueued_ += kRawDataSize;
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void EnqueueData() {
scoped_array<uint8> audio_data(new uint8[kRawDataSize]);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_channel(), 0u);
CHECK_EQ(kRawDataSize % algorithm_.bytes_per_frame(), 0u);
// The value of the data is meaningless; we just want non-zero data to
// differentiate it from muted data.
memset(audio_data.get(), 1, kRawDataSize);
algorithm_.EnqueueBuffer(new DataBuffer(audio_data.Pass(), kRawDataSize));
bytes_enqueued_ += kRawDataSize;
}
| 171,532
|
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 dev_get_valid_name(struct net *net,
struct net_device *dev,
const char *name)
{
BUG_ON(!net);
if (!dev_valid_name(name))
return -EINVAL;
if (strchr(name, '%'))
return dev_alloc_name_ns(net, dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
Commit Message: tun: call dev_get_valid_name() before register_netdevice()
register_netdevice() could fail early when we have an invalid
dev name, in which case ->ndo_uninit() is not called. For tun
device, this is a problem because a timer etc. are already
initialized and it expects ->ndo_uninit() to clean them up.
We could move these initializations into a ->ndo_init() so
that register_netdevice() knows better, however this is still
complicated due to the logic in tun_detach().
Therefore, I choose to just call dev_get_valid_name() before
register_netdevice(), which is quicker and much easier to audit.
And for this specific case, it is already enough.
Fixes: 96442e42429e ("tuntap: choose the txq based on rxq")
Reported-by: Dmitry Alexeev <avekceeb@gmail.com>
Cc: Jason Wang <jasowang@redhat.com>
Cc: "Michael S. Tsirkin" <mst@redhat.com>
Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-476
|
static int dev_get_valid_name(struct net *net,
int dev_get_valid_name(struct net *net, struct net_device *dev,
const char *name)
{
BUG_ON(!net);
if (!dev_valid_name(name))
return -EINVAL;
if (strchr(name, '%'))
return dev_alloc_name_ns(net, dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
| 169,855
|
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: _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
if (overflow2(sizeof(t_chunk_info), nc)) {
goto fail1;
}
sidx = sizeof (t_chunk_info) * nc;
if (sidx <= 0) {
goto fail1;
}
cidx = gdCalloc (sidx, 1);
if (cidx == NULL) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
if (cidx[i].offset < 0 || cidx[i].size < 0)
goto fail2;
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
Commit Message: Fix #354: Signed Integer Overflow gd_io.c
GD2 stores the number of horizontal and vertical chunks as words (i.e. 2
byte unsigned). These values are multiplied and assigned to an int when
reading the image, what can cause integer overflows. We have to avoid
that, and also make sure that either chunk count is actually greater
than zero. If illegal chunk counts are detected, we bail out from
reading the image.
CWE ID: CWE-190
|
_gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
if (*ncx <= 0 || *ncy <= 0 || *ncx > INT_MAX / *ncy) {
GD2_DBG(printf ("Illegal chunk counts: %d * %d\n", *ncx, *ncy));
goto fail1;
}
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
if (overflow2(sizeof(t_chunk_info), nc)) {
goto fail1;
}
sidx = sizeof (t_chunk_info) * nc;
if (sidx <= 0) {
goto fail1;
}
cidx = gdCalloc (sidx, 1);
if (cidx == NULL) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
if (cidx[i].offset < 0 || cidx[i].size < 0)
goto fail2;
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
| 168,509
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,
rpmpsm psm, char ** failedFile)
{
FD_t payload = rpmtePayload(te);
rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE);
rpmfs fs = rpmteGetFileStates(te);
rpmPlugins plugins = rpmtsPlugins(ts);
struct stat sb;
int saveerrno = errno;
int rc = 0;
int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0;
int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0;
int firsthardlink = -1;
int skip;
rpmFileAction action;
char *tid = NULL;
const char *suffix;
char *fpath = NULL;
if (fi == NULL) {
rc = RPMERR_BAD_MAGIC;
goto exit;
}
/* transaction id used for temporary path suffix while installing */
rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts));
/* Detect and create directories not explicitly in package. */
rc = fsmMkdirs(files, fs, plugins);
while (!rc) {
/* Read next payload header. */
rc = rpmfiNext(fi);
if (rc < 0) {
if (rc == RPMERR_ITER_END)
rc = 0;
break;
}
action = rpmfsGetAction(fs, rpmfiFX(fi));
skip = XFA_SKIPPING(action);
suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid;
if (action != FA_TOUCH) {
fpath = fsmFsPath(fi, suffix);
} else {
fpath = fsmFsPath(fi, "");
}
/* Remap file perms, owner, and group. */
rc = rpmfiStat(fi, 1, &sb);
fsmDebug(fpath, action, &sb);
/* Exit on error. */
if (rc)
break;
/* Run fsm file pre hook for all plugins */
rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath,
sb.st_mode, action);
if (rc) {
skip = 1;
} else {
setFileState(fs, rpmfiFX(fi));
}
if (!skip) {
int setmeta = 1;
/* Directories replacing something need early backup */
if (!suffix) {
rc = fsmBackup(fi, action);
}
/* Assume file does't exist when tmp suffix is in use */
if (!suffix) {
rc = fsmVerify(fpath, fi);
} else {
rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT;
}
if (S_ISREG(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmMkfile(fi, fpath, files, psm, nodigest,
&setmeta, &firsthardlink);
}
} else if (S_ISDIR(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
mode_t mode = sb.st_mode;
mode &= ~07777;
mode |= 00700;
rc = fsmMkdir(fpath, mode);
}
} else if (S_ISLNK(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmSymlink(rpmfiFLink(fi), fpath);
}
} else if (S_ISFIFO(sb.st_mode)) {
/* This mimics cpio S_ISSOCK() behavior but probably isn't right */
if (rc == RPMERR_ENOENT) {
rc = fsmMkfifo(fpath, 0000);
}
} else if (S_ISCHR(sb.st_mode) ||
S_ISBLK(sb.st_mode) ||
S_ISSOCK(sb.st_mode))
{
if (rc == RPMERR_ENOENT) {
rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev);
}
} else {
/* XXX Special case /dev/log, which shouldn't be packaged anyways */
if (!IS_DEV_LOG(fpath))
rc = RPMERR_UNKNOWN_FILETYPE;
}
/* Set permissions, timestamps etc for non-hardlink entries */
if (!rc && setmeta) {
rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps);
}
} else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) {
/* we skip the hard linked file containing the content */
/* write the content to the first used instead */
char *fn = rpmfilesFN(files, firsthardlink);
rc = expandRegular(fi, fn, psm, 0, nodigest, 0);
firsthardlink = -1;
free(fn);
}
if (rc) {
if (!skip) {
/* XXX only erase if temp fn w suffix is in use */
if (suffix && (action != FA_TOUCH)) {
(void) fsmRemove(fpath, sb.st_mode);
}
errno = saveerrno;
}
} else {
/* Notify on success. */
rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi));
if (!skip) {
/* Backup file if needed. Directories are handled earlier */
if (suffix)
rc = fsmBackup(fi, action);
if (!rc)
rc = fsmCommit(&fpath, fi, action, suffix);
}
}
if (rc)
*failedFile = xstrdup(fpath);
/* Run fsm file post hook for all plugins */
rpmpluginsCallFsmFilePost(plugins, fi, fpath,
sb.st_mode, action, rc);
fpath = _free(fpath);
}
rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ));
rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST));
exit:
/* No need to bother with close errors on read */
rpmfiArchiveClose(fi);
rpmfiFree(fi);
Fclose(payload);
free(tid);
free(fpath);
return rc;
}
Commit Message: Restrict following symlinks to directories by ownership (CVE-2017-7500)
Only follow directory symlinks owned by target directory owner or root.
This prevents privilege escalation from user-writable directories via
directory symlinks to privileged directories on package upgrade, while
still allowing admin to arrange disk usage with symlinks.
The rationale is that if you can create symlinks owned by user X you *are*
user X (or root), and if you also own directory Y you can do whatever with
it already, including change permissions. So when you create a symlink to
that directory, the link ownership acts as a simple stamp of authority that
you indeed want rpm to treat this symlink as it were the directory that
you own. Such a permission can only be given by you or root, which
is just the way we want it. Plus it's almost ridiculously simple as far
as rules go, compared to trying to calculate something from the
source vs destination directory permissions etc.
In the normal case, the user arranging diskspace with symlinks is indeed
root so nothing changes, the only real change here is to links created by
non-privileged users which should be few and far between in practise.
Unfortunately our test-suite runs as a regular user via fakechroot and
thus the testcase for this fails under the new rules. Adjust the testcase
to get the ownership straight and add a second case for the illegal
behavior, basically the same as the old one but with different expectations.
CWE ID: CWE-59
|
int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,
rpmpsm psm, char ** failedFile)
{
FD_t payload = rpmtePayload(te);
rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE);
rpmfs fs = rpmteGetFileStates(te);
rpmPlugins plugins = rpmtsPlugins(ts);
struct stat sb;
int saveerrno = errno;
int rc = 0;
int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0;
int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0;
int firsthardlink = -1;
int skip;
rpmFileAction action;
char *tid = NULL;
const char *suffix;
char *fpath = NULL;
if (fi == NULL) {
rc = RPMERR_BAD_MAGIC;
goto exit;
}
/* transaction id used for temporary path suffix while installing */
rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts));
/* Detect and create directories not explicitly in package. */
rc = fsmMkdirs(files, fs, plugins);
while (!rc) {
/* Read next payload header. */
rc = rpmfiNext(fi);
if (rc < 0) {
if (rc == RPMERR_ITER_END)
rc = 0;
break;
}
action = rpmfsGetAction(fs, rpmfiFX(fi));
skip = XFA_SKIPPING(action);
suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid;
if (action != FA_TOUCH) {
fpath = fsmFsPath(fi, suffix);
} else {
fpath = fsmFsPath(fi, "");
}
/* Remap file perms, owner, and group. */
rc = rpmfiStat(fi, 1, &sb);
fsmDebug(fpath, action, &sb);
/* Exit on error. */
if (rc)
break;
/* Run fsm file pre hook for all plugins */
rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath,
sb.st_mode, action);
if (rc) {
skip = 1;
} else {
setFileState(fs, rpmfiFX(fi));
}
if (!skip) {
int setmeta = 1;
/* Directories replacing something need early backup */
if (!suffix) {
rc = fsmBackup(fi, action);
}
/* Assume file does't exist when tmp suffix is in use */
if (!suffix) {
rc = fsmVerify(fpath, fi, &sb);
} else {
rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT;
}
if (S_ISREG(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmMkfile(fi, fpath, files, psm, nodigest,
&setmeta, &firsthardlink);
}
} else if (S_ISDIR(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
mode_t mode = sb.st_mode;
mode &= ~07777;
mode |= 00700;
rc = fsmMkdir(fpath, mode);
}
} else if (S_ISLNK(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmSymlink(rpmfiFLink(fi), fpath);
}
} else if (S_ISFIFO(sb.st_mode)) {
/* This mimics cpio S_ISSOCK() behavior but probably isn't right */
if (rc == RPMERR_ENOENT) {
rc = fsmMkfifo(fpath, 0000);
}
} else if (S_ISCHR(sb.st_mode) ||
S_ISBLK(sb.st_mode) ||
S_ISSOCK(sb.st_mode))
{
if (rc == RPMERR_ENOENT) {
rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev);
}
} else {
/* XXX Special case /dev/log, which shouldn't be packaged anyways */
if (!IS_DEV_LOG(fpath))
rc = RPMERR_UNKNOWN_FILETYPE;
}
/* Set permissions, timestamps etc for non-hardlink entries */
if (!rc && setmeta) {
rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps);
}
} else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) {
/* we skip the hard linked file containing the content */
/* write the content to the first used instead */
char *fn = rpmfilesFN(files, firsthardlink);
rc = expandRegular(fi, fn, psm, 0, nodigest, 0);
firsthardlink = -1;
free(fn);
}
if (rc) {
if (!skip) {
/* XXX only erase if temp fn w suffix is in use */
if (suffix && (action != FA_TOUCH)) {
(void) fsmRemove(fpath, sb.st_mode);
}
errno = saveerrno;
}
} else {
/* Notify on success. */
rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi));
if (!skip) {
/* Backup file if needed. Directories are handled earlier */
if (suffix)
rc = fsmBackup(fi, action);
if (!rc)
rc = fsmCommit(&fpath, fi, action, suffix);
}
}
if (rc)
*failedFile = xstrdup(fpath);
/* Run fsm file post hook for all plugins */
rpmpluginsCallFsmFilePost(plugins, fi, fpath,
sb.st_mode, action, rc);
fpath = _free(fpath);
}
rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ));
rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST));
exit:
/* No need to bother with close errors on read */
rpmfiArchiveClose(fi);
rpmfiFree(fi);
Fclose(payload);
free(tid);
free(fpath);
return rc;
}
| 170,177
|
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 InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
{
setDeviceOrientationOverride(error, 0, 0, 0);
}
Commit Message: DevTools: remove references to modules/device_orientation from core
BUG=340221
Review URL: https://codereview.chromium.org/150913003
git-svn-id: svn://svn.chromium.org/blink/trunk@166493 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
| 171,402
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
{
assert(memory_info != (MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
if (memory_info->blob != (void *) NULL)
switch (memory_info->type)
{
case AlignedVirtualMemory:
{
memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
RelinquishMagickResource(MemoryResource,memory_info->length);
break;
}
case MapVirtualMemory:
{
(void) UnmapBlob(memory_info->blob,memory_info->length);
memory_info->blob=NULL;
RelinquishMagickResource(MapResource,memory_info->length);
if (*memory_info->filename != '\0')
(void) RelinquishUniqueFileResource(memory_info->filename);
break;
}
case UnalignedVirtualMemory:
default:
{
memory_info->blob=RelinquishMagickMemory(memory_info->blob);
break;
}
}
memory_info->signature=(~MagickSignature);
memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
return(memory_info);
}
Commit Message:
CWE ID: CWE-189
|
MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
{
assert(memory_info != (MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
if (memory_info->blob != (void *) NULL)
switch (memory_info->type)
{
case AlignedVirtualMemory:
{
memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
RelinquishMagickResource(MemoryResource,memory_info->length);
break;
}
case MapVirtualMemory:
{
(void) UnmapBlob(memory_info->blob,memory_info->length);
memory_info->blob=NULL;
RelinquishMagickResource(MapResource,memory_info->length);
if (*memory_info->filename != '\0')
{
(void) RelinquishUniqueFileResource(memory_info->filename);
RelinquishMagickResource(DiskResource,memory_info->length);
}
break;
}
case UnalignedVirtualMemory:
default:
{
memory_info->blob=RelinquishMagickMemory(memory_info->blob);
break;
}
}
memory_info->signature=(~MagickSignature);
memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
return(memory_info);
}
| 168,860
|
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 WtsSessionProcessDelegate::Core::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
CommandLine command_line(CommandLine::NO_PROGRAM);
if (launch_elevated_) {
if (!job_.IsValid()) {
return false;
}
FilePath daemon_binary;
if (!GetInstalledBinaryPath(kDaemonBinaryName, &daemon_binary))
return false;
command_line.SetProgram(daemon_binary);
command_line.AppendSwitchPath(kElevateSwitchName, binary_path_);
CHECK(ResetEvent(process_exit_event_));
} else {
command_line.SetProgram(binary_path_);
}
scoped_ptr<IPC::ChannelProxy> channel;
std::string channel_name = GenerateIpcChannelName(this);
if (!CreateIpcChannel(channel_name, channel_security_, io_task_runner_,
delegate, &channel))
return false;
command_line.AppendSwitchNative(kDaemonPipeSwitchName,
UTF8ToWide(channel_name));
command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(),
kCopiedSwitchNames,
arraysize(kCopiedSwitchNames));
ScopedHandle worker_process;
ScopedHandle worker_thread;
if (!LaunchProcessWithToken(command_line.GetProgram(),
command_line.GetCommandLineString(),
session_token_,
false,
CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB,
&worker_process,
&worker_thread)) {
return false;
}
HANDLE local_process_exit_event;
if (launch_elevated_) {
if (!AssignProcessToJobObject(job_, worker_process)) {
LOG_GETLASTERROR(ERROR)
<< "Failed to assign the worker to the job object";
TerminateProcess(worker_process, CONTROL_C_EXIT);
return false;
}
local_process_exit_event = process_exit_event_;
} else {
worker_process_ = worker_process.Pass();
local_process_exit_event = worker_process_;
}
if (!ResumeThread(worker_thread)) {
LOG_GETLASTERROR(ERROR) << "Failed to resume the worker thread";
KillProcess(CONTROL_C_EXIT);
return false;
}
ScopedHandle process_exit_event;
if (!DuplicateHandle(GetCurrentProcess(),
local_process_exit_event,
GetCurrentProcess(),
process_exit_event.Receive(),
SYNCHRONIZE,
FALSE,
0)) {
LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle";
KillProcess(CONTROL_C_EXIT);
return false;
}
channel_ = channel.Pass();
*process_exit_event_out = process_exit_event.Pass();
return true;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool WtsSessionProcessDelegate::Core::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
CommandLine command_line(CommandLine::NO_PROGRAM);
if (launch_elevated_) {
if (!job_.IsValid()) {
return false;
}
FilePath daemon_binary;
if (!GetInstalledBinaryPath(kDaemonBinaryName, &daemon_binary))
return false;
command_line.SetProgram(daemon_binary);
command_line.AppendSwitchPath(kElevateSwitchName, binary_path_);
CHECK(ResetEvent(process_exit_event_));
} else {
command_line.SetProgram(binary_path_);
}
std::string channel_name = GenerateIpcChannelName(this);
ScopedHandle pipe;
if (!CreateIpcChannel(channel_name, channel_security_, &pipe))
return false;
// Wrap the pipe into an IPC channel.
scoped_ptr<IPC::ChannelProxy> channel(new IPC::ChannelProxy(
IPC::ChannelHandle(pipe),
IPC::Channel::MODE_SERVER,
delegate,
io_task_runner_));
command_line.AppendSwitchNative(kDaemonPipeSwitchName,
UTF8ToWide(channel_name));
command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(),
kCopiedSwitchNames,
arraysize(kCopiedSwitchNames));
ScopedHandle worker_process;
ScopedHandle worker_thread;
if (!LaunchProcessWithToken(command_line.GetProgram(),
command_line.GetCommandLineString(),
session_token_,
false,
CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB,
&worker_process,
&worker_thread)) {
return false;
}
HANDLE local_process_exit_event;
if (launch_elevated_) {
if (!AssignProcessToJobObject(job_, worker_process)) {
LOG_GETLASTERROR(ERROR)
<< "Failed to assign the worker to the job object";
TerminateProcess(worker_process, CONTROL_C_EXIT);
return false;
}
local_process_exit_event = process_exit_event_;
} else {
worker_process_ = worker_process.Pass();
local_process_exit_event = worker_process_;
}
if (!ResumeThread(worker_thread)) {
LOG_GETLASTERROR(ERROR) << "Failed to resume the worker thread";
KillProcess(CONTROL_C_EXIT);
return false;
}
ScopedHandle process_exit_event;
if (!DuplicateHandle(GetCurrentProcess(),
local_process_exit_event,
GetCurrentProcess(),
process_exit_event.Receive(),
SYNCHRONIZE,
FALSE,
0)) {
LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle";
KillProcess(CONTROL_C_EXIT);
return false;
}
channel_ = channel.Pass();
pipe_ = pipe.Pass();
*process_exit_event_out = process_exit_event.Pass();
return true;
}
| 171,560
|
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: jbig2_sd_cat(Jbig2Ctx *ctx, int n_dicts, Jbig2SymbolDict **dicts)
{
int i, j, k, symbols;
Jbig2SymbolDict *new = NULL;
/* count the imported symbols and allocate a new array */
symbols = 0;
for (i = 0; i < n_dicts; i++)
symbols += dicts[i]->n_symbols;
/* fill a new array with cloned glyph pointers */
new = jbig2_sd_new(ctx, symbols);
if (new != NULL) {
k = 0;
for (i = 0; i < n_dicts; i++)
for (j = 0; j < dicts[i]->n_symbols; j++)
new->glyphs[k++] = jbig2_image_clone(ctx, dicts[i]->glyphs[j]);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate new symbol dictionary");
}
return new;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_sd_cat(Jbig2Ctx *ctx, int n_dicts, Jbig2SymbolDict **dicts)
jbig2_sd_cat(Jbig2Ctx *ctx, uint32_t n_dicts, Jbig2SymbolDict **dicts)
{
uint32_t i, j, k, symbols;
Jbig2SymbolDict *new_dict = NULL;
/* count the imported symbols and allocate a new array */
symbols = 0;
for (i = 0; i < n_dicts; i++)
symbols += dicts[i]->n_symbols;
/* fill a new array with cloned glyph pointers */
new_dict = jbig2_sd_new(ctx, symbols);
if (new_dict != NULL) {
k = 0;
for (i = 0; i < n_dicts; i++)
for (j = 0; j < dicts[i]->n_symbols; j++)
new_dict->glyphs[k++] = jbig2_image_clone(ctx, dicts[i]->glyphs[j]);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate new symbol dictionary");
}
return new_dict;
}
| 165,499
|
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 load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
struct tss_segment_16 *tss)
{
int ret;
u8 cpl;
ctxt->_eip = tss->ip;
ctxt->eflags = tss->flag | 2;
*reg_write(ctxt, VCPU_REGS_RAX) = tss->ax;
*reg_write(ctxt, VCPU_REGS_RCX) = tss->cx;
*reg_write(ctxt, VCPU_REGS_RDX) = tss->dx;
*reg_write(ctxt, VCPU_REGS_RBX) = tss->bx;
*reg_write(ctxt, VCPU_REGS_RSP) = tss->sp;
*reg_write(ctxt, VCPU_REGS_RBP) = tss->bp;
*reg_write(ctxt, VCPU_REGS_RSI) = tss->si;
*reg_write(ctxt, VCPU_REGS_RDI) = tss->di;
/*
* SDM says that segment selectors are loaded before segment
* descriptors
*/
set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR);
set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
cpl = tss->cs & 3;
/*
* Now load segment descriptors. If fault happens at this stage
* it is handled in a context of new task
*/
ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: stable@vger.kernel.org
Signed-off-by: Nadav Amit <namit@cs.technion.ac.il>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID: CWE-264
|
static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
struct tss_segment_16 *tss)
{
int ret;
u8 cpl;
ctxt->_eip = tss->ip;
ctxt->eflags = tss->flag | 2;
*reg_write(ctxt, VCPU_REGS_RAX) = tss->ax;
*reg_write(ctxt, VCPU_REGS_RCX) = tss->cx;
*reg_write(ctxt, VCPU_REGS_RDX) = tss->dx;
*reg_write(ctxt, VCPU_REGS_RBX) = tss->bx;
*reg_write(ctxt, VCPU_REGS_RSP) = tss->sp;
*reg_write(ctxt, VCPU_REGS_RBP) = tss->bp;
*reg_write(ctxt, VCPU_REGS_RSI) = tss->si;
*reg_write(ctxt, VCPU_REGS_RDI) = tss->di;
/*
* SDM says that segment selectors are loaded before segment
* descriptors
*/
set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR);
set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
cpl = tss->cs & 3;
/*
* Now load segment descriptors. If fault happens at this stage
* it is handled in a context of new task
*/
ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
return X86EMUL_CONTINUE;
}
| 166,342
|
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 SADs(unsigned int *results) {
const uint8_t* refs[] = {GetReference(0), GetReference(1),
GetReference(2), GetReference(3)};
REGISTER_STATE_CHECK(GET_PARAM(2)(source_data_, source_stride_,
refs, reference_stride_,
results));
}
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
|
void SADs(unsigned int *results) {
const uint8_t *references[] = {GetReference(0), GetReference(1),
GetReference(2), GetReference(3)};
ASM_REGISTER_STATE_CHECK(GET_PARAM(2)(source_data_, source_stride_,
references, reference_stride_,
results));
}
| 174,576
|
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 hashtable_do_rehash(hashtable_t *hashtable)
{
list_t *list, *next;
pair_t *pair;
size_t i, index, new_size;
jsonp_free(hashtable->buckets);
hashtable->num_buckets++;
new_size = num_buckets(hashtable);
hashtable->buckets = jsonp_malloc(new_size * sizeof(bucket_t));
if(!hashtable->buckets)
return -1;
for(i = 0; i < num_buckets(hashtable); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
}
list = hashtable->list.next;
list_init(&hashtable->list);
for(; list != &hashtable->list; list = next) {
next = list->next;
pair = list_to_pair(list);
index = pair->hash % new_size;
insert_to_bucket(hashtable, &hashtable->buckets[index], &pair->list);
}
return 0;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310
|
static int hashtable_do_rehash(hashtable_t *hashtable)
{
list_t *list, *next;
pair_t *pair;
size_t i, index, new_size;
jsonp_free(hashtable->buckets);
hashtable->order++;
new_size = hashsize(hashtable->order);
hashtable->buckets = jsonp_malloc(new_size * sizeof(bucket_t));
if(!hashtable->buckets)
return -1;
for(i = 0; i < hashsize(hashtable->order); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
}
list = hashtable->list.next;
list_init(&hashtable->list);
for(; list != &hashtable->list; list = next) {
next = list->next;
pair = list_to_pair(list);
index = pair->hash % new_size;
insert_to_bucket(hashtable, &hashtable->buckets[index], &pair->list);
}
return 0;
}
| 166,529
|
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: ExtensionFunction::ResponseAction UsbFindDevicesFunction::Run() {
scoped_ptr<extensions::core_api::usb::FindDevices::Params> parameters =
FindDevices::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
vendor_id_ = parameters->options.vendor_id;
product_id_ = parameters->options.product_id;
interface_id_ = parameters->options.interface_id.get()
? *parameters->options.interface_id.get()
: UsbDevicePermissionData::ANY_INTERFACE;
UsbDevicePermission::CheckParam param(vendor_id_, product_id_, interface_id_);
if (!extension()->permissions_data()->CheckAPIPermissionWithParam(
APIPermission::kUsbDevice, ¶m)) {
return RespondNow(Error(kErrorPermissionDenied));
}
UsbService* service = device::DeviceClient::Get()->GetUsbService();
if (!service) {
return RespondNow(Error(kErrorInitService));
}
service->GetDevices(
base::Bind(&UsbFindDevicesFunction::OnGetDevicesComplete, this));
return RespondLater();
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399
|
ExtensionFunction::ResponseAction UsbFindDevicesFunction::Run() {
scoped_ptr<extensions::core_api::usb::FindDevices::Params> parameters =
FindDevices::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
vendor_id_ = parameters->options.vendor_id;
product_id_ = parameters->options.product_id;
int interface_id = parameters->options.interface_id.get()
? *parameters->options.interface_id.get()
: UsbDevicePermissionData::ANY_INTERFACE;
UsbDevicePermission::CheckParam param(vendor_id_, product_id_, interface_id);
if (!extension()->permissions_data()->CheckAPIPermissionWithParam(
APIPermission::kUsbDevice, ¶m)) {
return RespondNow(Error(kErrorPermissionDenied));
}
UsbService* service = device::DeviceClient::Get()->GetUsbService();
if (!service) {
return RespondNow(Error(kErrorInitService));
}
service->GetDevices(
base::Bind(&UsbFindDevicesFunction::OnGetDevicesComplete, this));
return RespondLater();
}
| 171,704
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(locale_accept_from_http)
{
UEnumeration *available;
char *http_accept = NULL;
int http_accept_len;
UErrorCode status = 0;
int len;
char resultLocale[INTL_MAX_LOCALE_LEN+1];
UAcceptResult outResult;
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC );
RETURN_FALSE;
}
available = ures_openAvailableLocales(NULL, &status);
INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list");
len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN,
&outResult, http_accept, available, &status);
uenum_close(available);
INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale");
if (len < 0 || outResult == ULOC_ACCEPT_FAILED) {
RETURN_FALSE;
}
RETURN_STRINGL(resultLocale, len, 1);
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
PHP_FUNCTION(locale_accept_from_http)
{
UEnumeration *available;
char *http_accept = NULL;
int http_accept_len;
UErrorCode status = 0;
int len;
char resultLocale[INTL_MAX_LOCALE_LEN+1];
UAcceptResult outResult;
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC );
RETURN_FALSE;
}
available = ures_openAvailableLocales(NULL, &status);
INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list");
len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN,
&outResult, http_accept, available, &status);
uenum_close(available);
INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale");
if (len < 0 || outResult == ULOC_ACCEPT_FAILED) {
RETURN_FALSE;
}
RETURN_STRINGL(resultLocale, len, 1);
}
| 167,195
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void FindBarController::ChangeTabContents(TabContentsWrapper* contents) {
if (tab_contents_) {
registrar_.RemoveAll();
find_bar_->StopAnimation();
}
tab_contents_ = contents;
if (find_bar_->IsFindBarVisible() &&
(!tab_contents_ || !tab_contents_->GetFindManager()->find_ui_active())) {
find_bar_->Hide(false);
}
if (!tab_contents_)
return;
registrar_.Add(this, NotificationType::FIND_RESULT_AVAILABLE,
Source<TabContents>(tab_contents_->tab_contents()));
registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
Source<NavigationController>(&tab_contents_->controller()));
MaybeSetPrepopulateText();
if (tab_contents_->GetFindManager()->find_ui_active()) {
find_bar_->Show(false);
}
UpdateFindBarForCurrentResult();
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void FindBarController::ChangeTabContents(TabContentsWrapper* contents) {
if (tab_contents_) {
registrar_.RemoveAll();
find_bar_->StopAnimation();
}
tab_contents_ = contents;
if (find_bar_->IsFindBarVisible() &&
(!tab_contents_ || !tab_contents_->find_tab_helper()->find_ui_active())) {
find_bar_->Hide(false);
}
if (!tab_contents_)
return;
registrar_.Add(this, NotificationType::FIND_RESULT_AVAILABLE,
Source<TabContents>(tab_contents_->tab_contents()));
registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
Source<NavigationController>(&tab_contents_->controller()));
MaybeSetPrepopulateText();
if (tab_contents_->find_tab_helper()->find_ui_active()) {
find_bar_->Show(false);
}
UpdateFindBarForCurrentResult();
}
| 170,657
|
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 NetworkHandler::ContinueInterceptedRequest(
const std::string& interception_id,
Maybe<std::string> error_reason,
Maybe<std::string> base64_raw_response,
Maybe<std::string> url,
Maybe<std::string> method,
Maybe<std::string> post_data,
Maybe<protocol::Network::Headers> headers,
Maybe<protocol::Network::AuthChallengeResponse> auth_challenge_response,
std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(
process_->GetBrowserContext());
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
base::Optional<std::string> raw_response;
if (base64_raw_response.isJust()) {
std::string decoded;
if (!base::Base64Decode(base64_raw_response.fromJust(), &decoded)) {
callback->sendFailure(Response::InvalidParams("Invalid rawResponse."));
return;
}
raw_response = decoded;
}
base::Optional<net::Error> error;
bool mark_as_canceled = false;
if (error_reason.isJust()) {
bool ok;
error = NetErrorFromString(error_reason.fromJust(), &ok);
if (!ok) {
callback->sendFailure(Response::InvalidParams("Invalid errorReason."));
return;
}
mark_as_canceled = true;
}
interceptor->ContinueInterceptedRequest(
interception_id,
std::make_unique<DevToolsURLRequestInterceptor::Modifications>(
std::move(error), std::move(raw_response), std::move(url),
std::move(method), std::move(post_data), std::move(headers),
std::move(auth_challenge_response), mark_as_canceled),
std::move(callback));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void NetworkHandler::ContinueInterceptedRequest(
const std::string& interception_id,
Maybe<std::string> error_reason,
Maybe<std::string> base64_raw_response,
Maybe<std::string> url,
Maybe<std::string> method,
Maybe<std::string> post_data,
Maybe<protocol::Network::Headers> headers,
Maybe<protocol::Network::AuthChallengeResponse> auth_challenge_response,
std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(browser_context_);
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
base::Optional<std::string> raw_response;
if (base64_raw_response.isJust()) {
std::string decoded;
if (!base::Base64Decode(base64_raw_response.fromJust(), &decoded)) {
callback->sendFailure(Response::InvalidParams("Invalid rawResponse."));
return;
}
raw_response = decoded;
}
base::Optional<net::Error> error;
bool mark_as_canceled = false;
if (error_reason.isJust()) {
bool ok;
error = NetErrorFromString(error_reason.fromJust(), &ok);
if (!ok) {
callback->sendFailure(Response::InvalidParams("Invalid errorReason."));
return;
}
mark_as_canceled = true;
}
interceptor->ContinueInterceptedRequest(
interception_id,
std::make_unique<DevToolsURLRequestInterceptor::Modifications>(
std::move(error), std::move(raw_response), std::move(url),
std::move(method), std::move(post_data), std::move(headers),
std::move(auth_challenge_response), mark_as_canceled),
std::move(callback));
}
| 172,754
|
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 BluetoothDeviceChooserController::OnBluetoothChooserEvent(
BluetoothChooser::Event event,
const std::string& device_address) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(chooser_.get());
switch (event) {
case BluetoothChooser::Event::RESCAN:
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
device_ids_.clear();
PopulateConnectedDevices();
DCHECK(chooser_);
StartDeviceDiscovery();
return;
case BluetoothChooser::Event::DENIED_PERMISSION:
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(blink::mojom::WebBluetoothResult::
CHOOSER_NOT_SHOWN_USER_DENIED_PERMISSION_TO_SCAN);
break;
case BluetoothChooser::Event::CANCELLED:
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED);
break;
case BluetoothChooser::Event::SHOW_OVERVIEW_HELP:
DVLOG(1) << "Overview Help link pressed.";
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED);
break;
case BluetoothChooser::Event::SHOW_ADAPTER_OFF_HELP:
DVLOG(1) << "Adapter Off Help link pressed.";
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED);
break;
case BluetoothChooser::Event::SHOW_NEED_LOCATION_HELP:
DVLOG(1) << "Need Location Help link pressed.";
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED);
break;
case BluetoothChooser::Event::SELECTED:
RecordNumOfDevices(options_->accept_all_devices, device_ids_.size());
PostSuccessCallback(device_address);
break;
}
chooser_.reset();
}
Commit Message: bluetooth: Implement getAvailability()
This change implements the getAvailability() method for
navigator.bluetooth as defined in the specification.
Bug: 707640
Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516
Reviewed-by: Chris Harrelson <chrishtr@chromium.org>
Reviewed-by: Giovanni Ortuño Urquidi <ortuno@chromium.org>
Reviewed-by: Kinuko Yasuda <kinuko@chromium.org>
Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org>
Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org>
Cr-Commit-Position: refs/heads/master@{#688987}
CWE ID: CWE-119
|
void BluetoothDeviceChooserController::OnBluetoothChooserEvent(
BluetoothChooser::Event event,
const std::string& device_address) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(chooser_.get());
switch (event) {
case BluetoothChooser::Event::RESCAN:
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
device_ids_.clear();
PopulateConnectedDevices();
DCHECK(chooser_);
StartDeviceDiscovery();
return;
case BluetoothChooser::Event::DENIED_PERMISSION:
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(
WebBluetoothResult::CHOOSER_NOT_SHOWN_USER_DENIED_PERMISSION_TO_SCAN);
break;
case BluetoothChooser::Event::CANCELLED:
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(WebBluetoothResult::CHOOSER_CANCELLED);
break;
case BluetoothChooser::Event::SHOW_OVERVIEW_HELP:
DVLOG(1) << "Overview Help link pressed.";
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(WebBluetoothResult::CHOOSER_CANCELLED);
break;
case BluetoothChooser::Event::SHOW_ADAPTER_OFF_HELP:
DVLOG(1) << "Adapter Off Help link pressed.";
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(WebBluetoothResult::CHOOSER_CANCELLED);
break;
case BluetoothChooser::Event::SHOW_NEED_LOCATION_HELP:
DVLOG(1) << "Need Location Help link pressed.";
RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event));
PostErrorCallback(WebBluetoothResult::CHOOSER_CANCELLED);
break;
case BluetoothChooser::Event::SELECTED:
RecordNumOfDevices(options_->accept_all_devices, device_ids_.size());
PostSuccessCallback(device_address);
break;
}
chooser_.reset();
}
| 172,444
|
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 TaskService::UnbindInstance() {
{
base::AutoLock lock(lock_);
if (bound_instance_id_ == kInvalidInstanceId)
return false;
bound_instance_id_ = kInvalidInstanceId;
DCHECK(default_task_runner_);
default_task_runner_ = nullptr;
}
base::subtle::AutoWriteLock task_lock(task_lock_);
return true;
}
Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService
There are non-trivial performance implications of using shared
SRWLocking on Windows as more state has to be checked.
Since there are only two uses of the ReadWriteLock in Chromium after
over 1 year, the decision is to remove it.
BUG=758721
Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80
Reviewed-on: https://chromium-review.googlesource.com/634423
Commit-Queue: Robert Liao <robliao@chromium.org>
Reviewed-by: Takashi Toyoshima <toyoshim@chromium.org>
Reviewed-by: Francois Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#497632}
CWE ID: CWE-20
|
bool TaskService::UnbindInstance() {
{
base::AutoLock lock(lock_);
if (bound_instance_id_ == kInvalidInstanceId)
return false;
bound_instance_id_ = kInvalidInstanceId;
DCHECK(default_task_runner_);
default_task_runner_ = nullptr;
}
// But invoked tasks might be still running here. To ensure no task runs on
// quitting this method, wait for all tasks to complete.
base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_);
while (tasks_in_flight_ > 0)
no_tasks_in_flight_cv_.Wait();
return true;
}
| 172,214
|
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: struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode)
{
struct nfs_inode *nfsi = NFS_I(inode);
struct nfs_open_context *pos, *ctx = NULL;
spin_lock(&inode->i_lock);
list_for_each_entry(pos, &nfsi->open_files, list) {
if (cred != NULL && pos->cred != cred)
continue;
if ((pos->mode & mode) == mode) {
ctx = get_nfs_open_context(pos);
break;
}
}
spin_unlock(&inode->i_lock);
return ctx;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode)
struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, fmode_t mode)
{
struct nfs_inode *nfsi = NFS_I(inode);
struct nfs_open_context *pos, *ctx = NULL;
spin_lock(&inode->i_lock);
list_for_each_entry(pos, &nfsi->open_files, list) {
if (cred != NULL && pos->cred != cred)
continue;
if ((pos->mode & mode) == mode) {
ctx = get_nfs_open_context(pos);
break;
}
}
spin_unlock(&inode->i_lock);
return ctx;
}
| 165,682
|
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 EntrySync::remove(ExceptionState& exceptionState) const
{
RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create();
m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
helper->getResult(exceptionState);
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
void EntrySync::remove(ExceptionState& exceptionState) const
{
VoidSyncCallbackHelper* helper = VoidSyncCallbackHelper::create();
m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
helper->getResult(exceptionState);
}
| 171,423
|
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: log2vis_unicode (PyObject * unicode, FriBidiParType base_direction, int clean, int reordernsm)
{
PyObject *logical = NULL; /* input string encoded in utf-8 */
PyObject *visual = NULL; /* output string encoded in utf-8 */
PyObject *result = NULL; /* unicode output string */
int length = PyUnicode_GET_SIZE (unicode);
logical = PyUnicode_AsUTF8String (unicode);
if (logical == NULL)
goto cleanup;
visual = log2vis_utf8 (logical, length, base_direction, clean, reordernsm);
if (visual == NULL)
goto cleanup;
result = PyUnicode_DecodeUTF8 (PyString_AS_STRING (visual),
PyString_GET_SIZE (visual), "strict");
cleanup:
Py_XDECREF (logical);
Py_XDECREF (visual);
return result;
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119
|
log2vis_unicode (PyObject * unicode, FriBidiParType base_direction, int clean, int reordernsm)
_pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw)
{
PyUnicodeObject *logical = NULL; /* input unicode or string object */
FriBidiParType base = FRIBIDI_TYPE_RTL; /* optional direction */
int clean = 0; /* optional flag to clean the string */
int reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/
static char *kwargs[] =
{ "logical", "base_direction", "clean", "reordernsm", NULL };
if (!PyArg_ParseTupleAndKeywords (args, kw, "U|iii", kwargs,
&logical, &base, &clean, &reordernsm)) {
return NULL;
}
/* Validate base */
if (!(base == FRIBIDI_TYPE_RTL
|| base == FRIBIDI_TYPE_LTR
|| base == FRIBIDI_TYPE_ON)) {
return PyErr_Format (PyExc_ValueError,
"invalid value %d: use either RTL, LTR or ON",
base);
}
return unicode_log2vis (logical, base, clean, reordernsm);
}
| 165,641
|
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 base::Callback<void(const gfx::Image&)> Wrap(
const base::Callback<void(const SkBitmap&)>& image_decoded_callback) {
auto* handler = new ImageDecodedHandlerWithTimeout(image_decoded_callback);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded,
handler->weak_ptr_factory_.GetWeakPtr(), gfx::Image()),
base::TimeDelta::FromSeconds(kDecodeLogoTimeoutSeconds));
return base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded,
handler->weak_ptr_factory_.GetWeakPtr());
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <sdefresne@chromium.org>
Reviewed-by: Marc Treib <treib@chromium.org>
Commit-Queue: Chris Pickel <sfiera@chromium.org>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
|
static base::Callback<void(const gfx::Image&)> Wrap(
| 171,961
|
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 vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
|| vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
return;
vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
exit_intr_info = vmx->exit_intr_info;
/* Handle machine checks before interrupts are enabled */
if (is_machine_check(exit_intr_info))
kvm_machine_check();
/* We need to handle NMIs before interrupts are enabled */
if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
(exit_intr_info & INTR_INFO_VALID_MASK)) {
kvm_before_handle_nmi(&vmx->vcpu);
asm("int $2");
kvm_after_handle_nmi(&vmx->vcpu);
}
}
Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)
When L2 exits to L0 due to "exception or NMI", software exceptions
(#BP and #OF) for which L1 has requested an intercept should be
handled by L1 rather than L0. Previously, only hardware exceptions
were forwarded to L1.
Signed-off-by: Jim Mattson <jmattson@google.com>
Cc: stable@vger.kernel.org
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID: CWE-388
|
static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
|| vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
return;
vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
exit_intr_info = vmx->exit_intr_info;
/* Handle machine checks before interrupts are enabled */
if (is_machine_check(exit_intr_info))
kvm_machine_check();
/* We need to handle NMIs before interrupts are enabled */
if (is_nmi(exit_intr_info)) {
kvm_before_handle_nmi(&vmx->vcpu);
asm("int $2");
kvm_after_handle_nmi(&vmx->vcpu);
}
}
| 166,857
|
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 tcp_v4_rcv(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
const struct iphdr *iph;
const struct tcphdr *th;
bool refcounted;
struct sock *sk;
int ret;
if (skb->pkt_type != PACKET_HOST)
goto discard_it;
/* Count it even if it's bad */
__TCP_INC_STATS(net, TCP_MIB_INSEGS);
if (!pskb_may_pull(skb, sizeof(struct tcphdr)))
goto discard_it;
th = (const struct tcphdr *)skb->data;
if (unlikely(th->doff < sizeof(struct tcphdr) / 4))
goto bad_packet;
if (!pskb_may_pull(skb, th->doff * 4))
goto discard_it;
/* An explanation is required here, I think.
* Packet length and doff are validated by header prediction,
* provided case of th->doff==0 is eliminated.
* So, we defer the checks. */
if (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo))
goto csum_error;
th = (const struct tcphdr *)skb->data;
iph = ip_hdr(skb);
/* This is tricky : We move IPCB at its correct location into TCP_SKB_CB()
* barrier() makes sure compiler wont play fool^Waliasing games.
*/
memmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb),
sizeof(struct inet_skb_parm));
barrier();
TCP_SKB_CB(skb)->seq = ntohl(th->seq);
TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +
skb->len - th->doff * 4);
TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);
TCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th);
TCP_SKB_CB(skb)->tcp_tw_isn = 0;
TCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph);
TCP_SKB_CB(skb)->sacked = 0;
lookup:
sk = __inet_lookup_skb(&tcp_hashinfo, skb, __tcp_hdrlen(th), th->source,
th->dest, &refcounted);
if (!sk)
goto no_tcp_socket;
process:
if (sk->sk_state == TCP_TIME_WAIT)
goto do_time_wait;
if (sk->sk_state == TCP_NEW_SYN_RECV) {
struct request_sock *req = inet_reqsk(sk);
struct sock *nsk;
sk = req->rsk_listener;
if (unlikely(tcp_v4_inbound_md5_hash(sk, skb))) {
sk_drops_add(sk, skb);
reqsk_put(req);
goto discard_it;
}
if (unlikely(sk->sk_state != TCP_LISTEN)) {
inet_csk_reqsk_queue_drop_and_put(sk, req);
goto lookup;
}
/* We own a reference on the listener, increase it again
* as we might lose it too soon.
*/
sock_hold(sk);
refcounted = true;
nsk = tcp_check_req(sk, skb, req, false);
if (!nsk) {
reqsk_put(req);
goto discard_and_relse;
}
if (nsk == sk) {
reqsk_put(req);
} else if (tcp_child_process(sk, nsk, skb)) {
tcp_v4_send_reset(nsk, skb);
goto discard_and_relse;
} else {
sock_put(sk);
return 0;
}
}
if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) {
__NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
goto discard_and_relse;
}
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
goto discard_and_relse;
if (tcp_v4_inbound_md5_hash(sk, skb))
goto discard_and_relse;
nf_reset(skb);
if (sk_filter(sk, skb))
goto discard_and_relse;
skb->dev = NULL;
if (sk->sk_state == TCP_LISTEN) {
ret = tcp_v4_do_rcv(sk, skb);
goto put_and_return;
}
sk_incoming_cpu_update(sk);
bh_lock_sock_nested(sk);
tcp_segs_in(tcp_sk(sk), skb);
ret = 0;
if (!sock_owned_by_user(sk)) {
if (!tcp_prequeue(sk, skb))
ret = tcp_v4_do_rcv(sk, skb);
} else if (tcp_add_backlog(sk, skb)) {
goto discard_and_relse;
}
bh_unlock_sock(sk);
put_and_return:
if (refcounted)
sock_put(sk);
return ret;
no_tcp_socket:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
goto discard_it;
if (tcp_checksum_complete(skb)) {
csum_error:
__TCP_INC_STATS(net, TCP_MIB_CSUMERRORS);
bad_packet:
__TCP_INC_STATS(net, TCP_MIB_INERRS);
} else {
tcp_v4_send_reset(NULL, skb);
}
discard_it:
/* Discard frame. */
kfree_skb(skb);
return 0;
discard_and_relse:
sk_drops_add(sk, skb);
if (refcounted)
sock_put(sk);
goto discard_it;
do_time_wait:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
inet_twsk_put(inet_twsk(sk));
goto discard_it;
}
if (tcp_checksum_complete(skb)) {
inet_twsk_put(inet_twsk(sk));
goto csum_error;
}
switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) {
case TCP_TW_SYN: {
struct sock *sk2 = inet_lookup_listener(dev_net(skb->dev),
&tcp_hashinfo, skb,
__tcp_hdrlen(th),
iph->saddr, th->source,
iph->daddr, th->dest,
inet_iif(skb));
if (sk2) {
inet_twsk_deschedule_put(inet_twsk(sk));
sk = sk2;
refcounted = false;
goto process;
}
/* Fall through to ACK */
}
case TCP_TW_ACK:
tcp_v4_timewait_ack(sk, skb);
break;
case TCP_TW_RST:
tcp_v4_send_reset(sk, skb);
inet_twsk_deschedule_put(inet_twsk(sk));
goto discard_it;
case TCP_TW_SUCCESS:;
}
goto discard_it;
}
Commit Message: tcp: take care of truncations done by sk_filter()
With syzkaller help, Marco Grassi found a bug in TCP stack,
crashing in tcp_collapse()
Root cause is that sk_filter() can truncate the incoming skb,
but TCP stack was not really expecting this to happen.
It probably was expecting a simple DROP or ACCEPT behavior.
We first need to make sure no part of TCP header could be removed.
Then we need to adjust TCP_SKB_CB(skb)->end_seq
Many thanks to syzkaller team and Marco for giving us a reproducer.
Signed-off-by: Eric Dumazet <edumazet@google.com>
Reported-by: Marco Grassi <marco.gra@gmail.com>
Reported-by: Vladis Dronov <vdronov@redhat.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-284
|
int tcp_v4_rcv(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
const struct iphdr *iph;
const struct tcphdr *th;
bool refcounted;
struct sock *sk;
int ret;
if (skb->pkt_type != PACKET_HOST)
goto discard_it;
/* Count it even if it's bad */
__TCP_INC_STATS(net, TCP_MIB_INSEGS);
if (!pskb_may_pull(skb, sizeof(struct tcphdr)))
goto discard_it;
th = (const struct tcphdr *)skb->data;
if (unlikely(th->doff < sizeof(struct tcphdr) / 4))
goto bad_packet;
if (!pskb_may_pull(skb, th->doff * 4))
goto discard_it;
/* An explanation is required here, I think.
* Packet length and doff are validated by header prediction,
* provided case of th->doff==0 is eliminated.
* So, we defer the checks. */
if (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo))
goto csum_error;
th = (const struct tcphdr *)skb->data;
iph = ip_hdr(skb);
/* This is tricky : We move IPCB at its correct location into TCP_SKB_CB()
* barrier() makes sure compiler wont play fool^Waliasing games.
*/
memmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb),
sizeof(struct inet_skb_parm));
barrier();
TCP_SKB_CB(skb)->seq = ntohl(th->seq);
TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +
skb->len - th->doff * 4);
TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);
TCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th);
TCP_SKB_CB(skb)->tcp_tw_isn = 0;
TCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph);
TCP_SKB_CB(skb)->sacked = 0;
lookup:
sk = __inet_lookup_skb(&tcp_hashinfo, skb, __tcp_hdrlen(th), th->source,
th->dest, &refcounted);
if (!sk)
goto no_tcp_socket;
process:
if (sk->sk_state == TCP_TIME_WAIT)
goto do_time_wait;
if (sk->sk_state == TCP_NEW_SYN_RECV) {
struct request_sock *req = inet_reqsk(sk);
struct sock *nsk;
sk = req->rsk_listener;
if (unlikely(tcp_v4_inbound_md5_hash(sk, skb))) {
sk_drops_add(sk, skb);
reqsk_put(req);
goto discard_it;
}
if (unlikely(sk->sk_state != TCP_LISTEN)) {
inet_csk_reqsk_queue_drop_and_put(sk, req);
goto lookup;
}
/* We own a reference on the listener, increase it again
* as we might lose it too soon.
*/
sock_hold(sk);
refcounted = true;
nsk = tcp_check_req(sk, skb, req, false);
if (!nsk) {
reqsk_put(req);
goto discard_and_relse;
}
if (nsk == sk) {
reqsk_put(req);
} else if (tcp_child_process(sk, nsk, skb)) {
tcp_v4_send_reset(nsk, skb);
goto discard_and_relse;
} else {
sock_put(sk);
return 0;
}
}
if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) {
__NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
goto discard_and_relse;
}
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
goto discard_and_relse;
if (tcp_v4_inbound_md5_hash(sk, skb))
goto discard_and_relse;
nf_reset(skb);
if (tcp_filter(sk, skb))
goto discard_and_relse;
th = (const struct tcphdr *)skb->data;
iph = ip_hdr(skb);
skb->dev = NULL;
if (sk->sk_state == TCP_LISTEN) {
ret = tcp_v4_do_rcv(sk, skb);
goto put_and_return;
}
sk_incoming_cpu_update(sk);
bh_lock_sock_nested(sk);
tcp_segs_in(tcp_sk(sk), skb);
ret = 0;
if (!sock_owned_by_user(sk)) {
if (!tcp_prequeue(sk, skb))
ret = tcp_v4_do_rcv(sk, skb);
} else if (tcp_add_backlog(sk, skb)) {
goto discard_and_relse;
}
bh_unlock_sock(sk);
put_and_return:
if (refcounted)
sock_put(sk);
return ret;
no_tcp_socket:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
goto discard_it;
if (tcp_checksum_complete(skb)) {
csum_error:
__TCP_INC_STATS(net, TCP_MIB_CSUMERRORS);
bad_packet:
__TCP_INC_STATS(net, TCP_MIB_INERRS);
} else {
tcp_v4_send_reset(NULL, skb);
}
discard_it:
/* Discard frame. */
kfree_skb(skb);
return 0;
discard_and_relse:
sk_drops_add(sk, skb);
if (refcounted)
sock_put(sk);
goto discard_it;
do_time_wait:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
inet_twsk_put(inet_twsk(sk));
goto discard_it;
}
if (tcp_checksum_complete(skb)) {
inet_twsk_put(inet_twsk(sk));
goto csum_error;
}
switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) {
case TCP_TW_SYN: {
struct sock *sk2 = inet_lookup_listener(dev_net(skb->dev),
&tcp_hashinfo, skb,
__tcp_hdrlen(th),
iph->saddr, th->source,
iph->daddr, th->dest,
inet_iif(skb));
if (sk2) {
inet_twsk_deschedule_put(inet_twsk(sk));
sk = sk2;
refcounted = false;
goto process;
}
/* Fall through to ACK */
}
case TCP_TW_ACK:
tcp_v4_timewait_ack(sk, skb);
break;
case TCP_TW_RST:
tcp_v4_send_reset(sk, skb);
inet_twsk_deschedule_put(inet_twsk(sk));
goto discard_it;
case TCP_TW_SUCCESS:;
}
goto discard_it;
}
| 166,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: static int sanitize_ptr_alu(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
struct bpf_reg_state *dst_reg,
bool off_is_neg)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_insn_aux_data *aux = cur_aux(env);
bool ptr_is_dst_reg = ptr_reg == dst_reg;
u8 opcode = BPF_OP(insn->code);
u32 alu_state, alu_limit;
struct bpf_reg_state tmp;
bool ret;
if (env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K)
return 0;
/* We already marked aux for masking from non-speculative
* paths, thus we got here in the first place. We only care
* to explore bad access from here.
*/
if (vstate->speculative)
goto do_sim;
alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
alu_state |= ptr_is_dst_reg ?
BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
return 0;
/* If we arrived here from different branches with different
* limits to sanitize, then this won't work.
*/
if (aux->alu_state &&
(aux->alu_state != alu_state ||
aux->alu_limit != alu_limit))
return -EACCES;
/* Corresponding fixup done in fixup_bpf_calls(). */
aux->alu_state = alu_state;
aux->alu_limit = alu_limit;
do_sim:
/* Simulate and find potential out-of-bounds access under
* speculative execution from truncation as a result of
* masking when off was not within expected range. If off
* sits in dst, then we temporarily need to move ptr there
* to simulate dst (== 0) +/-= ptr. Needed, for example,
* for cases where we use K-based arithmetic in one direction
* and truncated reg-based in the other in order to explore
* bad access.
*/
if (!ptr_is_dst_reg) {
tmp = *dst_reg;
*dst_reg = *ptr_reg;
}
ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
if (!ptr_is_dst_reg)
*dst_reg = tmp;
return !ret ? -EFAULT : 0;
}
Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths
While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer
arithmetic") took care of rejecting alu op on pointer when e.g. pointer
came from two different map values with different map properties such as
value size, Jann reported that a case was not covered yet when a given
alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from
different branches where we would incorrectly try to sanitize based
on the pointer's limit. Catch this corner case and reject the program
instead.
Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
CWE ID: CWE-189
|
static int sanitize_ptr_alu(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
struct bpf_reg_state *dst_reg,
bool off_is_neg)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_insn_aux_data *aux = cur_aux(env);
bool ptr_is_dst_reg = ptr_reg == dst_reg;
u8 opcode = BPF_OP(insn->code);
u32 alu_state, alu_limit;
struct bpf_reg_state tmp;
bool ret;
if (can_skip_alu_sanitation(env, insn))
return 0;
/* We already marked aux for masking from non-speculative
* paths, thus we got here in the first place. We only care
* to explore bad access from here.
*/
if (vstate->speculative)
goto do_sim;
alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
alu_state |= ptr_is_dst_reg ?
BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
return 0;
if (update_alu_sanitation_state(aux, alu_state, alu_limit))
return -EACCES;
do_sim:
/* Simulate and find potential out-of-bounds access under
* speculative execution from truncation as a result of
* masking when off was not within expected range. If off
* sits in dst, then we temporarily need to move ptr there
* to simulate dst (== 0) +/-= ptr. Needed, for example,
* for cases where we use K-based arithmetic in one direction
* and truncated reg-based in the other in order to explore
* bad access.
*/
if (!ptr_is_dst_reg) {
tmp = *dst_reg;
*dst_reg = *ptr_reg;
}
ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
if (!ptr_is_dst_reg)
*dst_reg = tmp;
return !ret ? -EFAULT : 0;
}
| 169,731
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest) {
Guchar *lineBuf;
Guint pix;
Guchar *destPtr0, *destPtr;
int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1;
int i;
yp = scaledHeight / srcHeight;
lineBuf = (Guchar *)gmalloc(srcWidth);
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
}
(*src)(srcData, lineBuf);
xt = 0;
d0 = (255 << 23) / xp;
d1 = (255 << 23) / (xp + 1);
xx = 0;
for (x = 0; x < scaledWidth; ++x) {
if ((xt += xq) >= scaledWidth) {
xt -= scaledWidth;
xStep = xp + 1;
d = d1;
} else {
xStep = xp;
d = d0;
}
pix = 0;
for (i = 0; i < xStep; ++i) {
pix += lineBuf[xx++];
}
pix = (pix * d) >> 23;
for (i = 0; i < yStep; ++i) {
destPtr = destPtr0 + i * scaledWidth + x;
*destPtr = (Guchar)pix;
}
}
destPtr0 += yStep * scaledWidth;
}
gfree(lineBuf);
}
Commit Message:
CWE ID: CWE-119
|
void Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest) {
Guchar *lineBuf;
Guint pix;
Guchar *destPtr0, *destPtr;
int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1;
int i;
destPtr0 = dest->data;
if (destPtr0 == NULL) {
error(errInternal, -1, "dest->data is NULL in Splash::scaleMaskYuXd");
return;
}
yp = scaledHeight / srcHeight;
lineBuf = (Guchar *)gmalloc(srcWidth);
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
yt = 0;
for (y = 0; y < srcHeight; ++y) {
}
(*src)(srcData, lineBuf);
xt = 0;
d0 = (255 << 23) / xp;
d1 = (255 << 23) / (xp + 1);
xx = 0;
for (x = 0; x < scaledWidth; ++x) {
if ((xt += xq) >= scaledWidth) {
xt -= scaledWidth;
xStep = xp + 1;
d = d1;
} else {
xStep = xp;
d = d0;
}
pix = 0;
for (i = 0; i < xStep; ++i) {
pix += lineBuf[xx++];
}
pix = (pix * d) >> 23;
for (i = 0; i < yStep; ++i) {
destPtr = destPtr0 + i * scaledWidth + x;
*destPtr = (Guchar)pix;
}
}
destPtr0 += yStep * scaledWidth;
}
gfree(lineBuf);
}
| 164,735
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual void RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
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
|
virtual void RemoveObserver(Observer* observer) {
virtual void RemoveObserver(InputMethodLibrary::Observer* observer) {
observers_.RemoveObserver(observer);
}
| 170,503
|
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 rngapi_reset(struct crypto_rng *tfm, const u8 *seed,
unsigned int slen)
{
u8 *buf = NULL;
u8 *src = (u8 *)seed;
int err;
if (slen) {
buf = kmalloc(slen, GFP_KERNEL);
if (!buf)
return -ENOMEM;
memcpy(buf, seed, slen);
src = buf;
}
err = crypto_old_rng_alg(tfm)->rng_reset(tfm, src, slen);
kzfree(buf);
return err;
}
Commit Message: crypto: rng - Remove old low-level rng interface
Now that all rng implementations have switched over to the new
interface, we can remove the old low-level interface.
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
CWE ID: CWE-476
|
static int rngapi_reset(struct crypto_rng *tfm, const u8 *seed,
| 167,734
|
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, mount)
{
char *fname, *arch = NULL, *entry = NULL, *path, *actual;
int fname_len, arch_len, entry_len;
size_t path_len, actual_len;
phar_archive_data *pphar;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &path, &path_len, &actual, &actual_len) == FAILURE) {
return;
}
fname = (char*)zend_get_executed_filename();
fname_len = strlen(fname);
#ifdef PHP_WIN32
phar_unixify_path_separators(fname, fname_len);
#endif
if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
efree(entry);
entry = NULL;
if (path_len > 7 && !memcmp(path, "phar://", 7)) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path);
efree(arch);
return;
}
carry_on2:
if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) {
if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) {
if (SUCCESS == phar_copy_on_write(&pphar)) {
goto carry_on;
}
}
zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch);
if (arch) {
efree(arch);
}
return;
}
carry_on:
if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch);
if (path && path == entry) {
efree(entry);
}
if (arch) {
efree(arch);
}
return;
}
if (entry && path && path == entry) {
efree(entry);
}
if (arch) {
efree(arch);
}
return;
} else if (PHAR_G(phar_fname_map.u.flags) && NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) {
goto carry_on;
} else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) {
if (SUCCESS == phar_copy_on_write(&pphar)) {
goto carry_on;
}
goto carry_on;
} else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
path = entry;
path_len = entry_len;
goto carry_on2;
}
zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual);
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, mount)
{
char *fname, *arch = NULL, *entry = NULL, *path, *actual;
int fname_len, arch_len, entry_len;
size_t path_len, actual_len;
phar_archive_data *pphar;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &path, &path_len, &actual, &actual_len) == FAILURE) {
return;
}
fname = (char*)zend_get_executed_filename();
fname_len = strlen(fname);
#ifdef PHP_WIN32
phar_unixify_path_separators(fname, fname_len);
#endif
if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
efree(entry);
entry = NULL;
if (path_len > 7 && !memcmp(path, "phar://", 7)) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path);
efree(arch);
return;
}
carry_on2:
if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) {
if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) {
if (SUCCESS == phar_copy_on_write(&pphar)) {
goto carry_on;
}
}
zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch);
if (arch) {
efree(arch);
}
return;
}
carry_on:
if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch);
if (path && path == entry) {
efree(entry);
}
if (arch) {
efree(arch);
}
return;
}
if (entry && path && path == entry) {
efree(entry);
}
if (arch) {
efree(arch);
}
return;
} else if (PHAR_G(phar_fname_map.u.flags) && NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) {
goto carry_on;
} else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) {
if (SUCCESS == phar_copy_on_write(&pphar)) {
goto carry_on;
}
goto carry_on;
} else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
path = entry;
path_len = entry_len;
goto carry_on2;
}
zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual);
}
| 165,056
|
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 Cluster::Parse(long long& pos, long& len) const {
long status = Load(pos, len);
if (status < 0)
return status;
assert(m_pos >= m_element_start);
assert(m_timecode >= 0);
const long long cluster_stop =
(m_element_size < 0) ? -1 : m_element_start + m_element_size;
if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
return 1; // nothing else to do
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_pos;
for (;;) {
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((total >= 0) && (pos >= total)) {
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return static_cast<long>(id);
if (id == 0) // weird
return E_FILE_FORMAT_INVALID;
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { // Cluster or Cues ID
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
pos += len; // consume ID field
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; // consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) // weird
continue;
const long long block_stop = pos + size;
if (cluster_stop >= 0) {
if (block_stop > cluster_stop) {
if ((id == 0x20) || (id == 0x23))
return E_FILE_FORMAT_INVALID;
pos = cluster_stop;
break;
}
} else if ((total >= 0) && (block_stop > total)) {
m_element_size = total - m_element_start;
pos = total;
break;
} else if (block_stop > avail) {
len = static_cast<long>(size);
return E_BUFFER_NOT_FULL;
}
Cluster* const this_ = const_cast<Cluster*>(this);
if (id == 0x20) // BlockGroup
return this_->ParseBlockGroup(size, pos, len);
if (id == 0x23) // SimpleBlock
return this_->ParseSimpleBlock(size, pos, len);
pos += size; // consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert(m_element_size > 0);
m_pos = pos;
assert((cluster_stop < 0) || (m_pos <= cluster_stop));
if (m_entries_count > 0) {
const long idx = m_entries_count - 1;
const BlockEntry* const pLast = m_entries[idx];
assert(pLast);
const Block* const pBlock = pLast->GetBlock();
assert(pBlock);
const long long start = pBlock->m_start;
if ((total >= 0) && (start > total))
return -1; // defend against trucated stream
const long long size = pBlock->m_size;
const long long stop = start + size;
assert((cluster_stop < 0) || (stop <= cluster_stop));
if ((total >= 0) && (stop > total))
return -1; // defend against trucated stream
}
return 1; // no more entries
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long Cluster::Parse(long long& pos, long& len) const {
long status = Load(pos, len);
if (status < 0)
return status;
assert(m_pos >= m_element_start);
assert(m_timecode >= 0);
const long long cluster_stop =
(m_element_size < 0) ? -1 : m_element_start + m_element_size;
if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
return 1; // nothing else to do
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_pos;
for (;;) {
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((total >= 0) && (pos >= total)) {
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return static_cast<long>(id);
if (id == 0) // weird
return E_FILE_FORMAT_INVALID;
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { // Cluster or Cues ID
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
pos += len; // consume ID field
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; // consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) // weird
continue;
const long long block_stop = pos + size;
if (cluster_stop >= 0) {
if (block_stop > cluster_stop) {
if ((id == 0x20) || (id == 0x23))
return E_FILE_FORMAT_INVALID;
pos = cluster_stop;
break;
}
} else if ((total >= 0) && (block_stop > total)) {
m_element_size = total - m_element_start;
pos = total;
break;
} else if (block_stop > avail) {
len = static_cast<long>(size);
return E_BUFFER_NOT_FULL;
}
Cluster* const this_ = const_cast<Cluster*>(this);
if (id == 0x20) // BlockGroup
return this_->ParseBlockGroup(size, pos, len);
if (id == 0x23) // SimpleBlock
return this_->ParseSimpleBlock(size, pos, len);
pos += size; // consume payload
if (cluster_stop >= 0 && pos > cluster_stop)
return E_FILE_FORMAT_INVALID;
}
assert(m_element_size > 0);
m_pos = pos;
if (cluster_stop >= 0 && m_pos > cluster_stop)
return E_FILE_FORMAT_INVALID;
if (m_entries_count > 0) {
const long idx = m_entries_count - 1;
const BlockEntry* const pLast = m_entries[idx];
assert(pLast);
const Block* const pBlock = pLast->GetBlock();
assert(pBlock);
const long long start = pBlock->m_start;
if ((total >= 0) && (start > total))
return -1; // defend against trucated stream
const long long size = pBlock->m_size;
const long long stop = start + size;
assert((cluster_stop < 0) || (stop <= cluster_stop));
if ((total >= 0) && (stop > total))
return -1; // defend against trucated stream
}
return 1; // no more entries
}
| 173,846
|
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: fr_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
int ret;
uint16_t extracted_ethertype;
u_int dlci;
u_int addr_len;
uint16_t nlpid;
u_int hdr_len;
uint8_t flags[4];
ret = parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length);
if (ret == -1)
goto trunc;
if (ret == 0) {
ND_PRINT((ndo, "Q.922, invalid address"));
return 0;
}
ND_TCHECK(p[addr_len]);
if (length < addr_len + 1)
goto trunc;
if (p[addr_len] != LLC_UI && dlci != 0) {
/*
* Let's figure out if we have Cisco-style encapsulation,
* with an Ethernet type (Cisco HDLC type?) following the
* address.
*/
if (!ND_TTEST2(p[addr_len], 2) || length < addr_len + 2) {
/* no Ethertype */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
} else {
extracted_ethertype = EXTRACT_16BITS(p+addr_len);
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci,
flags, extracted_ethertype);
if (ethertype_print(ndo, extracted_ethertype,
p+addr_len+ETHERTYPE_LEN,
length-addr_len-ETHERTYPE_LEN,
ndo->ndo_snapend-p-addr_len-ETHERTYPE_LEN,
NULL, NULL) == 0)
/* ether_type not known, probably it wasn't one */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
else
return addr_len + 2;
}
}
ND_TCHECK(p[addr_len+1]);
if (length < addr_len + 2)
goto trunc;
if (p[addr_len + 1] == 0) {
/*
* Assume a pad byte after the control (UI) byte.
* A pad byte should only be used with 3-byte Q.922.
*/
if (addr_len != 3)
ND_PRINT((ndo, "Pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* pad */ + 1 /* NLPID */;
} else {
/*
* Not a pad byte.
* A pad byte should be used with 3-byte Q.922.
*/
if (addr_len == 3)
ND_PRINT((ndo, "No pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* NLPID */;
}
ND_TCHECK(p[hdr_len - 1]);
if (length < hdr_len)
goto trunc;
nlpid = p[hdr_len - 1];
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci, flags, nlpid);
p += hdr_len;
length -= hdr_len;
switch (nlpid) {
case NLPID_IP:
ip_print(ndo, p, length);
break;
case NLPID_IP6:
ip6_print(ndo, p, length);
break;
case NLPID_CLNP:
case NLPID_ESIS:
case NLPID_ISIS:
isoclns_print(ndo, p - 1, length + 1, ndo->ndo_snapend - p + 1); /* OSI printers need the NLPID field */
break;
case NLPID_SNAP:
if (snap_print(ndo, p, length, ndo->ndo_snapend - p, NULL, NULL, 0) == 0) {
/* ether_type not known, print raw packet */
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, hdr_len,
dlci, flags, nlpid);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p - hdr_len, length + hdr_len);
}
break;
case NLPID_Q933:
q933_print(ndo, p, length);
break;
case NLPID_MFR:
frf15_print(ndo, p, length);
break;
case NLPID_PPP:
ppp_print(ndo, p, length);
break;
default:
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, addr_len,
dlci, flags, nlpid);
if (!ndo->ndo_xflag)
ND_DEFAULTPRINT(p, length);
}
return hdr_len;
trunc:
ND_PRINT((ndo, "[|fr]"));
return 0;
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
fr_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
int ret;
uint16_t extracted_ethertype;
u_int dlci;
u_int addr_len;
uint16_t nlpid;
u_int hdr_len;
uint8_t flags[4];
ret = parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length);
if (ret == -1)
goto trunc;
if (ret == 0) {
ND_PRINT((ndo, "Q.922, invalid address"));
return 0;
}
ND_TCHECK(p[addr_len]);
if (length < addr_len + 1)
goto trunc;
if (p[addr_len] != LLC_UI && dlci != 0) {
/*
* Let's figure out if we have Cisco-style encapsulation,
* with an Ethernet type (Cisco HDLC type?) following the
* address.
*/
if (!ND_TTEST2(p[addr_len], 2) || length < addr_len + 2) {
/* no Ethertype */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
} else {
extracted_ethertype = EXTRACT_16BITS(p+addr_len);
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci,
flags, extracted_ethertype);
if (ethertype_print(ndo, extracted_ethertype,
p+addr_len+ETHERTYPE_LEN,
length-addr_len-ETHERTYPE_LEN,
ndo->ndo_snapend-p-addr_len-ETHERTYPE_LEN,
NULL, NULL) == 0)
/* ether_type not known, probably it wasn't one */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
else
return addr_len + 2;
}
}
ND_TCHECK(p[addr_len+1]);
if (length < addr_len + 2)
goto trunc;
if (p[addr_len + 1] == 0) {
/*
* Assume a pad byte after the control (UI) byte.
* A pad byte should only be used with 3-byte Q.922.
*/
if (addr_len != 3)
ND_PRINT((ndo, "Pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* pad */ + 1 /* NLPID */;
} else {
/*
* Not a pad byte.
* A pad byte should be used with 3-byte Q.922.
*/
if (addr_len == 3)
ND_PRINT((ndo, "No pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* NLPID */;
}
ND_TCHECK(p[hdr_len - 1]);
if (length < hdr_len)
goto trunc;
nlpid = p[hdr_len - 1];
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci, flags, nlpid);
p += hdr_len;
length -= hdr_len;
switch (nlpid) {
case NLPID_IP:
ip_print(ndo, p, length);
break;
case NLPID_IP6:
ip6_print(ndo, p, length);
break;
case NLPID_CLNP:
case NLPID_ESIS:
case NLPID_ISIS:
isoclns_print(ndo, p - 1, length + 1); /* OSI printers need the NLPID field */
break;
case NLPID_SNAP:
if (snap_print(ndo, p, length, ndo->ndo_snapend - p, NULL, NULL, 0) == 0) {
/* ether_type not known, print raw packet */
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, hdr_len,
dlci, flags, nlpid);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p - hdr_len, length + hdr_len);
}
break;
case NLPID_Q933:
q933_print(ndo, p, length);
break;
case NLPID_MFR:
frf15_print(ndo, p, length);
break;
case NLPID_PPP:
ppp_print(ndo, p, length);
break;
default:
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, addr_len,
dlci, flags, nlpid);
if (!ndo->ndo_xflag)
ND_DEFAULTPRINT(p, length);
}
return hdr_len;
trunc:
ND_PRINT((ndo, "[|fr]"));
return 0;
}
| 167,945
|
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 decode_zbuf(AVBPrint *bp, const uint8_t *data,
const uint8_t *data_end)
{
z_stream zstream;
unsigned char *buf;
unsigned buf_size;
int ret;
zstream.zalloc = ff_png_zalloc;
zstream.zfree = ff_png_zfree;
zstream.opaque = NULL;
if (inflateInit(&zstream) != Z_OK)
return AVERROR_EXTERNAL;
zstream.next_in = (unsigned char *)data;
zstream.avail_in = data_end - data;
av_bprint_init(bp, 0, -1);
while (zstream.avail_in > 0) {
av_bprint_get_buffer(bp, 1, &buf, &buf_size);
if (!buf_size) {
ret = AVERROR(ENOMEM);
goto fail;
}
zstream.next_out = buf;
zstream.avail_out = buf_size;
ret = inflate(&zstream, Z_PARTIAL_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
ret = AVERROR_EXTERNAL;
goto fail;
}
bp->len += zstream.next_out - buf;
if (ret == Z_STREAM_END)
break;
}
inflateEnd(&zstream);
bp->str[bp->len] = 0;
return 0;
fail:
inflateEnd(&zstream);
av_bprint_finalize(bp, NULL);
return ret;
}
Commit Message: avcodec/pngdec: Fix off by 1 size in decode_zbuf()
Fixes out of array access
Fixes: 444/fuzz-2-ffmpeg_VIDEO_AV_CODEC_ID_PNG_fuzzer
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-787
|
static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
const uint8_t *data_end)
{
z_stream zstream;
unsigned char *buf;
unsigned buf_size;
int ret;
zstream.zalloc = ff_png_zalloc;
zstream.zfree = ff_png_zfree;
zstream.opaque = NULL;
if (inflateInit(&zstream) != Z_OK)
return AVERROR_EXTERNAL;
zstream.next_in = (unsigned char *)data;
zstream.avail_in = data_end - data;
av_bprint_init(bp, 0, -1);
while (zstream.avail_in > 0) {
av_bprint_get_buffer(bp, 2, &buf, &buf_size);
if (buf_size < 2) {
ret = AVERROR(ENOMEM);
goto fail;
}
zstream.next_out = buf;
zstream.avail_out = buf_size - 1;
ret = inflate(&zstream, Z_PARTIAL_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
ret = AVERROR_EXTERNAL;
goto fail;
}
bp->len += zstream.next_out - buf;
if (ret == Z_STREAM_END)
break;
}
inflateEnd(&zstream);
bp->str[bp->len] = 0;
return 0;
fail:
inflateEnd(&zstream);
av_bprint_finalize(bp, NULL);
return ret;
}
| 168,245
|
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: PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decoderow != NULL);
assert(sp->decodepfunc != NULL);
if ((*sp->decoderow)(tif, op0, occ0, s)) {
(*sp->decodepfunc)(tif, op0, occ0);
return 1;
} else
return 0;
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
|
PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->decoderow != NULL);
assert(sp->decodepfunc != NULL);
if ((*sp->decoderow)(tif, op0, occ0, s)) {
return (*sp->decodepfunc)(tif, op0, occ0);
} else
return 0;
}
| 166,876
|
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: matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
}
Commit Message: Fix a buffer overflow
Fixes #635
Thanks to HongxuChen for reporting it
CWE ID: CWE-125
|
matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2;
((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length));
k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
}
| 169,022
|
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 *ReadLABELImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent],
*property;
const char
*label;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
TypeMetric
metrics;
size_t
height,
width;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
(void) ResetImagePage(image,"0x0+0+0");
property=InterpretImageProperties(image_info,image,image_info->filename);
(void) SetImageProperty(image,"label",property);
property=DestroyString(property);
label=GetImageProperty(image,"label");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->text=ConstantString(label);
metrics.width=0;
metrics.ascent=0.0;
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if ((image->columns == 0) && (image->rows == 0))
{
image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5);
image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
}
else
if (((image->columns == 0) || (image->rows == 0)) ||
(fabs(image_info->pointsize) < MagickEpsilon))
{
double
high,
low;
/*
Auto fit text into bounding box.
*/
for ( ; ; draw_info->pointsize*=2.0)
{
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width >= image->columns) && (height >= image->rows))
break;
}
else
if (((image->columns != 0) && (width >= image->columns)) ||
((image->rows != 0) && (height >= image->rows)))
break;
}
high=draw_info->pointsize;
for (low=1.0; (high-low) > 0.5; )
{
draw_info->pointsize=(low+high)/2.0;
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width < image->columns) && (height < image->rows))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
else
if (((image->columns != 0) && (width < image->columns)) ||
((image->rows != 0) && (height < image->rows)))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
draw_info->pointsize=(low+high)/2.0-0.5;
}
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image->columns == 0)
image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5);
if (image->columns == 0)
image->columns=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) (metrics.ascent-metrics.descent+
draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Draw label.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
draw_info->direction == RightToLeftDirection ? image->columns-
metrics.bounds.x2 : 0.0,draw_info->gravity == UndefinedGravity ?
metrics.ascent : 0.0);
draw_info->geometry=AcquireString(geometry);
status=AnnotateImage(image,draw_info);
if (image_info->pointsize == 0.0)
{
char
pointsize[MaxTextExtent];
(void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g",
draw_info->pointsize);
(void) SetImageProperty(image,"label:pointsize",pointsize);
}
draw_info=DestroyDrawInfo(draw_info);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
return(GetFirstImageInList(image));
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119
|
static Image *ReadLABELImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent],
*property;
const char
*label;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
TypeMetric
metrics;
size_t
height,
width;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
(void) ResetImagePage(image,"0x0+0+0");
property=InterpretImageProperties(image_info,image,image_info->filename);
(void) SetImageProperty(image,"label",property);
property=DestroyString(property);
label=GetImageProperty(image,"label");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->text=ConstantString(label);
metrics.width=0;
metrics.ascent=0.0;
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if ((image->columns == 0) && (image->rows == 0))
{
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
}
else
if (((image->columns == 0) || (image->rows == 0)) ||
(fabs(image_info->pointsize) < MagickEpsilon))
{
double
high,
low;
/*
Auto fit text into bounding box.
*/
for ( ; ; draw_info->pointsize*=2.0)
{
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width >= image->columns) && (height >= image->rows))
break;
}
else
if (((image->columns != 0) && (width >= image->columns)) ||
((image->rows != 0) && (height >= image->rows)))
break;
}
high=draw_info->pointsize;
for (low=1.0; (high-low) > 0.5; )
{
draw_info->pointsize=(low+high)/2.0;
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width < image->columns) && (height < image->rows))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
else
if (((image->columns != 0) && (width < image->columns)) ||
((image->rows != 0) && (height < image->rows)))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
draw_info->pointsize=(low+high)/2.0-0.5;
}
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image->columns == 0)
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
if (image->columns == 0)
image->columns=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
if (image->rows == 0)
image->rows=(size_t) floor(metrics.ascent-metrics.descent+
draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Draw label.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
draw_info->direction == RightToLeftDirection ? image->columns-
metrics.bounds.x2 : 0.0,draw_info->gravity == UndefinedGravity ?
metrics.ascent : 0.0);
draw_info->geometry=AcquireString(geometry);
status=AnnotateImage(image,draw_info);
if (image_info->pointsize == 0.0)
{
char
pointsize[MaxTextExtent];
(void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g",
draw_info->pointsize);
(void) SetImageProperty(image,"label:pointsize",pointsize);
}
draw_info=DestroyDrawInfo(draw_info);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
return(GetFirstImageInList(image));
}
| 168,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: ossl_cipher_initialize(VALUE self, VALUE str)
{
EVP_CIPHER_CTX *ctx;
const EVP_CIPHER *cipher;
char *name;
unsigned char dummy_key[EVP_MAX_KEY_LENGTH] = { 0 };
name = StringValueCStr(str);
GetCipherInit(self, ctx);
if (ctx) {
ossl_raise(rb_eRuntimeError, "Cipher already inititalized!");
}
AllocCipher(self, ctx);
if (!(cipher = EVP_get_cipherbyname(name))) {
ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%"PRIsVALUE")", str);
}
/*
* EVP_CipherInit_ex() allows to specify NULL to key and IV, however some
* ciphers don't handle well (OpenSSL's bug). [Bug #2768]
*
* The EVP which has EVP_CIPH_RAND_KEY flag (such as DES3) allows
* uninitialized key, but other EVPs (such as AES) does not allow it.
* Calling EVP_CipherUpdate() without initializing key causes SEGV so we
* set the data filled with "\0" as the key by default.
*/
if (EVP_CipherInit_ex(ctx, cipher, NULL, dummy_key, NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
return self;
}
Commit Message: cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49
CWE ID: CWE-310
|
ossl_cipher_initialize(VALUE self, VALUE str)
{
EVP_CIPHER_CTX *ctx;
const EVP_CIPHER *cipher;
char *name;
name = StringValueCStr(str);
GetCipherInit(self, ctx);
if (ctx) {
ossl_raise(rb_eRuntimeError, "Cipher already inititalized!");
}
AllocCipher(self, ctx);
if (!(cipher = EVP_get_cipherbyname(name))) {
ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%"PRIsVALUE")", str);
}
if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
return self;
}
| 168,780
|
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, addEmptyDir)
{
char *dirname;
size_t dirname_len;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &dirname, &dirname_len) == FAILURE) {
return;
}
if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory");
return;
}
phar_mkdir(&phar_obj->archive, dirname, dirname_len);
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, addEmptyDir)
{
char *dirname;
size_t dirname_len;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &dirname, &dirname_len) == FAILURE) {
return;
}
if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory");
return;
}
phar_mkdir(&phar_obj->archive, dirname, dirname_len);
}
| 165,069
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftVideoDecoderOMXComponent::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoPortFormat:
{
OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_VIDEO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > kMaxPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (formatParams->nIndex != 0) {
return OMX_ErrorNoMore;
}
if (formatParams->nPortIndex == kInputPortIndex) {
formatParams->eCompressionFormat = mCodingType;
formatParams->eColorFormat = OMX_COLOR_FormatUnused;
formatParams->xFramerate = 0;
} else {
CHECK_EQ(formatParams->nPortIndex, 1u);
formatParams->eCompressionFormat = OMX_VIDEO_CodingUnused;
formatParams->eColorFormat = OMX_COLOR_FormatYUV420Planar;
formatParams->xFramerate = 0;
}
return OMX_ErrorNone;
}
case OMX_IndexParamVideoProfileLevelQuerySupported:
{
OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevel =
(OMX_VIDEO_PARAM_PROFILELEVELTYPE *) params;
if (profileLevel->nPortIndex != kInputPortIndex) {
ALOGE("Invalid port index: %" PRIu32, profileLevel->nPortIndex);
return OMX_ErrorUnsupportedIndex;
}
if (profileLevel->nProfileIndex >= mNumProfileLevels) {
return OMX_ErrorNoMore;
}
profileLevel->eProfile = mProfileLevels[profileLevel->nProfileIndex].mProfile;
profileLevel->eLevel = mProfileLevels[profileLevel->nProfileIndex].mLevel;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftVideoDecoderOMXComponent::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoPortFormat:
{
OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_VIDEO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > kMaxPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (formatParams->nIndex != 0) {
return OMX_ErrorNoMore;
}
if (formatParams->nPortIndex == kInputPortIndex) {
formatParams->eCompressionFormat = mCodingType;
formatParams->eColorFormat = OMX_COLOR_FormatUnused;
formatParams->xFramerate = 0;
} else {
CHECK_EQ(formatParams->nPortIndex, 1u);
formatParams->eCompressionFormat = OMX_VIDEO_CodingUnused;
formatParams->eColorFormat = OMX_COLOR_FormatYUV420Planar;
formatParams->xFramerate = 0;
}
return OMX_ErrorNone;
}
case OMX_IndexParamVideoProfileLevelQuerySupported:
{
OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevel =
(OMX_VIDEO_PARAM_PROFILELEVELTYPE *) params;
if (!isValidOMXParam(profileLevel)) {
return OMX_ErrorBadParameter;
}
if (profileLevel->nPortIndex != kInputPortIndex) {
ALOGE("Invalid port index: %" PRIu32, profileLevel->nPortIndex);
return OMX_ErrorUnsupportedIndex;
}
if (profileLevel->nProfileIndex >= mNumProfileLevels) {
return OMX_ErrorNoMore;
}
profileLevel->eProfile = mProfileLevels[profileLevel->nProfileIndex].mProfile;
profileLevel->eLevel = mProfileLevels[profileLevel->nProfileIndex].mLevel;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,225
|
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 vol_prc_lib_release(effect_handle_t handle)
{
struct listnode *node, *temp_node_next;
vol_listener_context_t *context = NULL;
vol_listener_context_t *recv_contex = (vol_listener_context_t *)handle;
int status = -1;
bool recompute_flag = false;
int active_stream_count = 0;
ALOGV("%s context %p", __func__, handle);
pthread_mutex_lock(&vol_listner_init_lock);
list_for_each_safe(node, temp_node_next, &vol_effect_list) {
context = node_to_item(node, struct vol_listener_context_s, effect_list_node);
if ((memcmp(&(context->desc->uuid), &(recv_contex->desc->uuid), sizeof(effect_uuid_t)) == 0)
&& (context->session_id == recv_contex->session_id)
&& (context->stream_type == recv_contex->stream_type)) {
ALOGV("--- Found something to remove ---");
list_remove(&context->effect_list_node);
PRINT_STREAM_TYPE(context->stream_type);
if (context->dev_id && AUDIO_DEVICE_OUT_SPEAKER) {
recompute_flag = true;
}
free(context);
status = 0;
} else {
++active_stream_count;
}
}
if (status != 0) {
ALOGE("something wrong ... <<<--- Found NOTHING to remove ... ???? --->>>>>");
}
if (active_stream_count == 0) {
current_gain_dep_cal_level = -1;
current_vol = 0.0;
}
if (recompute_flag) {
check_and_set_gain_dep_cal();
}
if (dumping_enabled) {
dump_list_l();
}
pthread_mutex_unlock(&vol_listner_init_lock);
return status;
}
Commit Message: post proc : volume listener : fix effect release crash
Fix access to deleted effect context in vol_prc_lib_release()
Bug: 25753245.
Change-Id: I64ca99e4d5d09667be4c8c605f66700b9ae67949
(cherry picked from commit 93ab6fdda7b7557ccb34372670c30fa6178f8426)
CWE ID: CWE-119
|
static int vol_prc_lib_release(effect_handle_t handle)
{
struct listnode *node, *temp_node_next;
vol_listener_context_t *context = NULL;
vol_listener_context_t *recv_contex = (vol_listener_context_t *)handle;
int status = -EINVAL;
bool recompute_flag = false;
int active_stream_count = 0;
uint32_t session_id;
uint32_t stream_type;
effect_uuid_t uuid;
ALOGV("%s context %p", __func__, handle);
if (recv_contex == NULL) {
return status;
}
pthread_mutex_lock(&vol_listner_init_lock);
session_id = recv_contex->session_id;
stream_type = recv_contex->stream_type;
uuid = recv_contex->desc->uuid;
list_for_each_safe(node, temp_node_next, &vol_effect_list) {
context = node_to_item(node, struct vol_listener_context_s, effect_list_node);
if ((memcmp(&(context->desc->uuid), &uuid, sizeof(effect_uuid_t)) == 0)
&& (context->session_id == session_id)
&& (context->stream_type == stream_type)) {
ALOGV("--- Found something to remove ---");
list_remove(node);
PRINT_STREAM_TYPE(context->stream_type);
if (context->dev_id && AUDIO_DEVICE_OUT_SPEAKER) {
recompute_flag = true;
}
free(context);
status = 0;
} else {
++active_stream_count;
}
}
if (status != 0) {
ALOGE("something wrong ... <<<--- Found NOTHING to remove ... ???? --->>>>>");
pthread_mutex_unlock(&vol_listner_init_lock);
return status;
}
if (active_stream_count == 0) {
current_gain_dep_cal_level = -1;
current_vol = 0.0;
}
if (recompute_flag) {
check_and_set_gain_dep_cal();
}
if (dumping_enabled) {
dump_list_l();
}
pthread_mutex_unlock(&vol_listner_init_lock);
return status;
}
| 173,916
|
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 getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) {
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
if (end < start) {
return false;
}
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
Commit Message: Add error logging on invalid cmap - DO NOT MERGE
This patch logs instances of fonts with invalid cmap tables.
Bug: 25645298
Bug: 26413177
Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e
CWE ID: CWE-20
|
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) {
android_errorWriteLog(0x534e4554, "25645298");
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
if (end < start) {
android_errorWriteLog(0x534e4554, "26413177");
return false;
}
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
| 173,895
|
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 MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable(
const GURL& site_url) {
JNIEnv* env = AttachCurrentThread();
Java_MostVisitedURLsObserver_onIconMadeAvailable(
env, observer_, ConvertUTF8ToJavaString(env, site_url.spec()));
}
Commit Message: Rename MostVisitedSites.MostVisitedURLsObserver to Observer.
BUG=677672
Review-Url: https://codereview.chromium.org/2697543002
Cr-Commit-Position: refs/heads/master@{#449958}
CWE ID: CWE-17
|
void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable(
const GURL& site_url) {
JNIEnv* env = AttachCurrentThread();
Java_Observer_onIconMadeAvailable(
env, observer_, ConvertUTF8ToJavaString(env, site_url.spec()));
}
| 172,034
|
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 PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder, v8::Local<v8::Value> v8Value)
{
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className);
v8::Local<v8::Value> descriptor;
if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) {
fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
v8::Local<v8::Value> setter;
if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "set")).ToLocal(&setter) || !setter->IsFunction()) {
fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
initializeHolderIfNeeded(scriptState, classObject, holder);
v8::Local<v8::Value> argv[] = { v8Value };
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(setter), scriptState->getExecutionContext(), holder, WTF_ARRAY_LENGTH(argv), argv, isolate).ToLocal(&result)) {
rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::SetterContext, attributeName, className);
block.ReThrow();
return false;
}
return true;
}
Commit Message: Blink-in-JS should not run micro tasks
If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug
(see 645211 for concrete steps).
This CL makes Blink-in-JS use callInternalFunction (instead of callFunction)
to avoid running micro tasks after Blink-in-JS' callbacks.
BUG=645211
Review-Url: https://codereview.chromium.org/2330843002
Cr-Commit-Position: refs/heads/master@{#417874}
CWE ID: CWE-79
|
bool PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder, v8::Local<v8::Value> v8Value)
{
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className);
v8::Local<v8::Value> descriptor;
if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) {
fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
v8::Local<v8::Value> setter;
if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "set")).ToLocal(&setter) || !setter->IsFunction()) {
fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
initializeHolderIfNeeded(scriptState, classObject, holder);
v8::Local<v8::Value> argv[] = { v8Value };
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(setter), holder, WTF_ARRAY_LENGTH(argv), argv, isolate).ToLocal(&result)) {
rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::SetterContext, attributeName, className);
block.ReThrow();
return false;
}
return true;
}
| 172,076
|
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 is_integer(char *string)
{
if (isdigit(string[0]) || string[0] == '-' || string[0] == '+') {
while (*++string && isdigit(*string))
; /* deliberately empty */
if (!*string)
return 1;
}
return 0;
}
Commit Message: Security fixes.
- Don't overflow the small cs_start buffer (reported by Niels
Thykier via the debian tracker (Jakub Wilk), found with a
fuzzer ("American fuzzy lop")).
- Cast arguments to <ctype.h> functions to unsigned char.
CWE ID: CWE-119
|
static int is_integer(char *string)
{
if (isdigit((unsigned char) string[0]) || string[0] == '-' || string[0] == '+') {
while (*++string && isdigit((unsigned char) *string))
; /* deliberately empty */
if (!*string)
return 1;
}
return 0;
}
| 166,621
|
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 MockRenderThread::AddRoute(int32 routing_id,
IPC::Channel::Listener* listener) {
EXPECT_EQ(routing_id_, routing_id);
widget_ = listener;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
void MockRenderThread::AddRoute(int32 routing_id,
IPC::Channel::Listener* listener) {
// We may hear this for views created from OnMsgCreateWindow as well,
// in which case we don't want to track the new widget.
if (routing_id_ == routing_id)
widget_ = listener;
}
| 171,021
|
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_snmp_parse_oid(zval *object, int st, struct objid_query *objid_query, zval **oid, zval **type, zval **value TSRMLS_DC)
{
char *pptr;
HashPosition pos_oid, pos_type, pos_value;
zval **tmp_oid, **tmp_type, **tmp_value;
if (Z_TYPE_PP(oid) != IS_ARRAY) {
if (Z_ISREF_PP(oid)) {
SEPARATE_ZVAL(oid);
}
convert_to_string_ex(oid);
} else if (Z_TYPE_PP(oid) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
}
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) != IS_ARRAY) {
if (Z_ISREF_PP(type)) {
SEPARATE_ZVAL(type);
}
convert_to_string_ex(type);
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(type), &pos_type);
}
if (Z_TYPE_PP(value) != IS_ARRAY) {
if (Z_ISREF_PP(value)) {
SEPARATE_ZVAL(value);
}
convert_to_string_ex(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(value), &pos_value);
}
}
objid_query->count = 0;
objid_query->array_output = ((st & SNMP_CMD_WALK) ? TRUE : FALSE);
if (Z_TYPE_PP(oid) == IS_STRING) {
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING && Z_TYPE_PP(value) == IS_STRING) {
if (Z_STRLEN_PP(type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bogus type '%s', should be single char, got %u", Z_STRVAL_PP(type), Z_STRLEN_PP(type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Single objid and multiple type or values are not supported");
efree(objid_query->vars);
return FALSE;
}
}
objid_query->count++;
} else if (Z_TYPE_PP(oid) == IS_ARRAY) { /* we got objid array */
if (zend_hash_num_elements(Z_ARRVAL_PP(oid)) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Got empty OID array");
return FALSE;
}
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg) * zend_hash_num_elements(Z_ARRVAL_PP(oid)));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid array: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->array_output = ( (st & SNMP_CMD_SET) ? FALSE : TRUE );
for ( zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
zend_hash_get_current_data_ex(Z_ARRVAL_PP(oid), (void **) &tmp_oid, &pos_oid) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_PP(oid), &pos_oid) ) {
convert_to_string_ex(tmp_oid);
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(tmp_oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING) {
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(type), (void **) &tmp_type, &pos_type)) {
convert_to_string_ex(tmp_type);
if (Z_STRLEN_PP(tmp_type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': bogus type '%s', should be single char, got %u", Z_STRVAL_PP(tmp_oid), Z_STRVAL_PP(tmp_type), Z_STRLEN_PP(tmp_type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(tmp_type);
objid_query->vars[objid_query->count].type = *pptr;
zend_hash_move_forward_ex(Z_ARRVAL_PP(type), &pos_type);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no type set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
if (Z_TYPE_PP(value) == IS_STRING) {
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(value), (void **) &tmp_value, &pos_value)) {
convert_to_string_ex(tmp_value);
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(tmp_value);
zend_hash_move_forward_ex(Z_ARRVAL_PP(value), &pos_value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no value set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->count++;
}
}
/* now parse all OIDs */
if (st & SNMP_CMD_WALK) {
if (objid_query->count > 1) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Multi OID walks are not supported!");
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[0].name_length = MAX_NAME_LEN;
if (strlen(objid_query->vars[0].oid)) { /* on a walk, an empty string means top of tree - no error */
if (!snmp_parse_oid(objid_query->vars[0].oid, objid_query->vars[0].name, &(objid_query->vars[0].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[0].oid);
efree(objid_query->vars);
return FALSE;
}
} else {
memmove((char *)objid_query->vars[0].name, (char *)objid_mib, sizeof(objid_mib));
objid_query->vars[0].name_length = sizeof(objid_mib) / sizeof(oid);
}
} else {
for (objid_query->offset = 0; objid_query->offset < objid_query->count; objid_query->offset++) {
objid_query->vars[objid_query->offset].name_length = MAX_OID_LEN;
if (!snmp_parse_oid(objid_query->vars[objid_query->offset].oid, objid_query->vars[objid_query->offset].name, &(objid_query->vars[objid_query->offset].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[objid_query->offset].oid);
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->offset = 0;
objid_query->step = objid_query->count;
return (objid_query->count > 0);
}
Commit Message:
CWE ID: CWE-416
|
static int php_snmp_parse_oid(zval *object, int st, struct objid_query *objid_query, zval **oid, zval **type, zval **value TSRMLS_DC)
{
char *pptr;
HashPosition pos_oid, pos_type, pos_value;
zval **tmp_oid, **tmp_type, **tmp_value;
if (Z_TYPE_PP(oid) != IS_ARRAY) {
if (Z_ISREF_PP(oid)) {
SEPARATE_ZVAL(oid);
}
convert_to_string_ex(oid);
} else if (Z_TYPE_PP(oid) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
}
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) != IS_ARRAY) {
if (Z_ISREF_PP(type)) {
SEPARATE_ZVAL(type);
}
convert_to_string_ex(type);
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(type), &pos_type);
}
if (Z_TYPE_PP(value) != IS_ARRAY) {
if (Z_ISREF_PP(value)) {
SEPARATE_ZVAL(value);
}
convert_to_string_ex(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(value), &pos_value);
}
}
objid_query->count = 0;
objid_query->array_output = ((st & SNMP_CMD_WALK) ? TRUE : FALSE);
if (Z_TYPE_PP(oid) == IS_STRING) {
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING && Z_TYPE_PP(value) == IS_STRING) {
if (Z_STRLEN_PP(type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bogus type '%s', should be single char, got %u", Z_STRVAL_PP(type), Z_STRLEN_PP(type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Single objid and multiple type or values are not supported");
efree(objid_query->vars);
return FALSE;
}
}
objid_query->count++;
} else if (Z_TYPE_PP(oid) == IS_ARRAY) { /* we got objid array */
if (zend_hash_num_elements(Z_ARRVAL_PP(oid)) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Got empty OID array");
return FALSE;
}
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg) * zend_hash_num_elements(Z_ARRVAL_PP(oid)));
if (objid_query->vars == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed while parsing oid array: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->array_output = ( (st & SNMP_CMD_SET) ? FALSE : TRUE );
for ( zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(oid), &pos_oid);
zend_hash_get_current_data_ex(Z_ARRVAL_PP(oid), (void **) &tmp_oid, &pos_oid) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_PP(oid), &pos_oid) ) {
convert_to_string_ex(tmp_oid);
objid_query->vars[objid_query->count].oid = Z_STRVAL_PP(tmp_oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_PP(type) == IS_STRING) {
pptr = Z_STRVAL_PP(type);
objid_query->vars[objid_query->count].type = *pptr;
} else if (Z_TYPE_PP(type) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(type), (void **) &tmp_type, &pos_type)) {
convert_to_string_ex(tmp_type);
if (Z_STRLEN_PP(tmp_type) != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': bogus type '%s', should be single char, got %u", Z_STRVAL_PP(tmp_oid), Z_STRVAL_PP(tmp_type), Z_STRLEN_PP(tmp_type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_PP(tmp_type);
objid_query->vars[objid_query->count].type = *pptr;
zend_hash_move_forward_ex(Z_ARRVAL_PP(type), &pos_type);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no type set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
if (Z_TYPE_PP(value) == IS_STRING) {
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(value);
} else if (Z_TYPE_PP(value) == IS_ARRAY) {
if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(value), (void **) &tmp_value, &pos_value)) {
convert_to_string_ex(tmp_value);
objid_query->vars[objid_query->count].value = Z_STRVAL_PP(tmp_value);
zend_hash_move_forward_ex(Z_ARRVAL_PP(value), &pos_value);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s': no value set", Z_STRVAL_PP(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->count++;
}
}
/* now parse all OIDs */
if (st & SNMP_CMD_WALK) {
if (objid_query->count > 1) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Multi OID walks are not supported!");
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[0].name_length = MAX_NAME_LEN;
if (strlen(objid_query->vars[0].oid)) { /* on a walk, an empty string means top of tree - no error */
if (!snmp_parse_oid(objid_query->vars[0].oid, objid_query->vars[0].name, &(objid_query->vars[0].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[0].oid);
efree(objid_query->vars);
return FALSE;
}
} else {
memmove((char *)objid_query->vars[0].name, (char *)objid_mib, sizeof(objid_mib));
objid_query->vars[0].name_length = sizeof(objid_mib) / sizeof(oid);
}
} else {
for (objid_query->offset = 0; objid_query->offset < objid_query->count; objid_query->offset++) {
objid_query->vars[objid_query->offset].name_length = MAX_OID_LEN;
if (!snmp_parse_oid(objid_query->vars[objid_query->offset].oid, objid_query->vars[objid_query->offset].name, &(objid_query->vars[objid_query->offset].name_length))) {
php_snmp_error(object, NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[objid_query->offset].oid);
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->offset = 0;
objid_query->step = objid_query->count;
return (objid_query->count > 0);
}
| 164,979
|
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 PaymentRequest::SatisfiesSkipUIConstraints() const {
return base::FeatureList::IsEnabled(features::kWebPaymentsSingleAppUiSkip) &&
base::FeatureList::IsEnabled(::features::kServiceWorkerPaymentApps) &&
is_show_user_gesture_ && state()->is_get_all_instruments_finished() &&
state()->available_instruments().size() == 1 &&
spec()->stringified_method_data().size() == 1 &&
!spec()->request_shipping() && !spec()->request_payer_name() &&
!spec()->request_payer_phone() &&
!spec()->request_payer_email()
&& spec()->url_payment_method_identifiers().size() == 1;
}
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 <anthonyvd@chromium.org>
Commit-Queue: Rouslan Solomakhin <rouslan@chromium.org>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189
|
bool PaymentRequest::SatisfiesSkipUIConstraints() const {
| 173,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: static void flush_tmregs_to_thread(struct task_struct *tsk)
{
/*
* If task is not current, it will have been flushed already to
* it's thread_struct during __switch_to().
*
* A reclaim flushes ALL the state or if not in TM save TM SPRs
* in the appropriate thread structures from live.
*/
if (tsk != current)
return;
if (MSR_TM_SUSPENDED(mfmsr())) {
tm_reclaim_current(TM_CAUSE_SIGNAL);
} else {
tm_enable();
tm_save_sprs(&(tsk->thread));
}
}
Commit Message: powerpc/tm: Flush TM only if CPU has TM feature
Commit cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump")
added code to access TM SPRs in flush_tmregs_to_thread(). However
flush_tmregs_to_thread() does not check if TM feature is available on
CPU before trying to access TM SPRs in order to copy live state to
thread structures. flush_tmregs_to_thread() is indeed guarded by
CONFIG_PPC_TRANSACTIONAL_MEM but it might be the case that kernel
was compiled with CONFIG_PPC_TRANSACTIONAL_MEM enabled and ran on
a CPU without TM feature available, thus rendering the execution
of TM instructions that are treated by the CPU as illegal instructions.
The fix is just to add proper checking in flush_tmregs_to_thread()
if CPU has the TM feature before accessing any TM-specific resource,
returning immediately if TM is no available on the CPU. Adding
that checking in flush_tmregs_to_thread() instead of in places
where it is called, like in vsr_get() and vsr_set(), is better because
avoids the same problem cropping up elsewhere.
Cc: stable@vger.kernel.org # v4.13+
Fixes: cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump")
Signed-off-by: Gustavo Romero <gromero@linux.vnet.ibm.com>
Reviewed-by: Cyril Bur <cyrilbur@gmail.com>
Signed-off-by: Michael Ellerman <mpe@ellerman.id.au>
CWE ID: CWE-119
|
static void flush_tmregs_to_thread(struct task_struct *tsk)
{
/*
* If task is not current, it will have been flushed already to
* it's thread_struct during __switch_to().
*
* A reclaim flushes ALL the state or if not in TM save TM SPRs
* in the appropriate thread structures from live.
*/
if ((!cpu_has_feature(CPU_FTR_TM)) || (tsk != current))
return;
if (MSR_TM_SUSPENDED(mfmsr())) {
tm_reclaim_current(TM_CAUSE_SIGNAL);
} else {
tm_enable();
tm_save_sprs(&(tsk->thread));
}
}
| 169,356
|
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 virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov,
unsigned int max_num_sg, bool is_write,
hwaddr pa, size_t sz)
{
unsigned num_sg = *p_num_sg;
assert(num_sg <= max_num_sg);
while (sz) {
hwaddr len = sz;
iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write);
iov[num_sg].iov_len = len;
addr[num_sg] = pa;
sz -= len;
pa += len;
num_sg++;
}
*p_num_sg = num_sg;
}
Commit Message:
CWE ID: CWE-20
|
static void virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov,
unsigned int max_num_sg, bool is_write,
hwaddr pa, size_t sz)
{
unsigned num_sg = *p_num_sg;
assert(num_sg <= max_num_sg);
if (!sz) {
error_report("virtio: zero sized buffers are not allowed");
exit(1);
}
while (sz) {
hwaddr len = sz;
iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write);
iov[num_sg].iov_len = len;
addr[num_sg] = pa;
sz -= len;
pa += len;
num_sg++;
}
*p_num_sg = num_sg;
}
| 164,956
|
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 do_session_handshake (lua_State *L, int status, lua_KContext ctx) {
int rc;
struct ssh_userdata *sshu = NULL;
assert(lua_gettop(L) == 4);
sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2");
while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) {
luaL_getmetafield(L, 3, "filter");
lua_pushvalue(L, 3);
assert(lua_status(L) == LUA_OK);
lua_callk(L, 1, 0, 0, do_session_handshake);
}
if (rc) {
libssh2_session_free(sshu->session);
return luaL_error(L, "Unable to complete libssh2 handshake.");
}
lua_settop(L, 3);
return 1;
}
Commit Message: Avoid a crash (double-free) when SSH connection fails
CWE ID: CWE-415
|
static int do_session_handshake (lua_State *L, int status, lua_KContext ctx) {
int rc;
struct ssh_userdata *sshu = NULL;
assert(lua_gettop(L) == 4);
sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2");
while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) {
luaL_getmetafield(L, 3, "filter");
lua_pushvalue(L, 3);
assert(lua_status(L) == LUA_OK);
lua_callk(L, 1, 0, 0, do_session_handshake);
}
if (rc) {
libssh2_session_free(sshu->session);
sshu->session = NULL;
return luaL_error(L, "Unable to complete libssh2 handshake.");
}
lua_settop(L, 3);
return 1;
}
| 169,856
|
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 SoftOpus::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.opus",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidOpus:
{
const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftOpus::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.opus",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidOpus:
{
const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (!isValidOMXParam(opusParams)) {
return OMX_ErrorBadParameter;
}
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,217
|
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: CuePoint::CuePoint(long idx, long long pos) :
m_element_start(0),
m_element_size(0),
m_index(idx),
m_timecode(-1 * pos),
m_track_positions(NULL),
m_track_positions_count(0)
{
assert(pos > 0);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
CuePoint::CuePoint(long idx, long long pos) :
CuePoint::CuePoint(long idx, long long pos)
: m_element_start(0),
m_element_size(0),
m_index(idx),
m_timecode(-1 * pos),
m_track_positions(NULL),
m_track_positions_count(0) {
assert(pos > 0);
}
| 174,261
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.