instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| 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: lrmd_remote_client_msg(gpointer data)
{
int id = 0;
int rc = 0;
int disconnected = 0;
xmlNode *request = NULL;
crm_client_t *client = data;
if (client->remote->tls_handshake_complete == FALSE) {
int rc = 0;
/* Muliple calls to handshake will be required, this callback
* will be invoked once the client sends more handshake data. */
do {
rc = gnutls_handshake(*client->remote->tls_session);
if (rc < 0 && rc != GNUTLS_E_AGAIN) {
crm_err("Remote lrmd tls handshake failed");
return -1;
}
} while (rc == GNUTLS_E_INTERRUPTED);
if (rc == 0) {
crm_debug("Remote lrmd tls handshake completed");
client->remote->tls_handshake_complete = TRUE;
if (client->remote->auth_timeout) {
g_source_remove(client->remote->auth_timeout);
}
client->remote->auth_timeout = 0;
}
return 0;
}
rc = crm_remote_ready(client->remote, 0);
if (rc == 0) {
/* no msg to read */
return 0;
} else if (rc < 0) {
crm_info("Client disconnected during remote client read");
return -1;
}
crm_remote_recv(client->remote, -1, &disconnected);
request = crm_remote_parse_buffer(client->remote);
while (request) {
crm_element_value_int(request, F_LRMD_REMOTE_MSG_ID, &id);
crm_trace("processing request from remote client with remote msg id %d", id);
if (!client->name) {
const char *value = crm_element_value(request, F_LRMD_CLIENTNAME);
if (value) {
client->name = strdup(value);
}
}
lrmd_call_id++;
if (lrmd_call_id < 1) {
lrmd_call_id = 1;
}
crm_xml_add(request, F_LRMD_CLIENTID, client->id);
crm_xml_add(request, F_LRMD_CLIENTNAME, client->name);
crm_xml_add_int(request, F_LRMD_CALLID, lrmd_call_id);
process_lrmd_message(client, id, request);
free_xml(request);
/* process all the messages in the current buffer */
request = crm_remote_parse_buffer(client->remote);
}
if (disconnected) {
crm_info("Client disconnect detected in tls msg dispatcher.");
return -1;
}
return 0;
}
Commit Message: Fix: remote: cl#5269 - Notify other clients of a new connection only if the handshake has completed (bsc#967388)
CWE ID: CWE-254
|
lrmd_remote_client_msg(gpointer data)
{
int id = 0;
int rc = 0;
int disconnected = 0;
xmlNode *request = NULL;
crm_client_t *client = data;
if (client->remote->tls_handshake_complete == FALSE) {
int rc = 0;
/* Muliple calls to handshake will be required, this callback
* will be invoked once the client sends more handshake data. */
do {
rc = gnutls_handshake(*client->remote->tls_session);
if (rc < 0 && rc != GNUTLS_E_AGAIN) {
crm_err("Remote lrmd tls handshake failed");
return -1;
}
} while (rc == GNUTLS_E_INTERRUPTED);
if (rc == 0) {
crm_debug("Remote lrmd tls handshake completed");
client->remote->tls_handshake_complete = TRUE;
if (client->remote->auth_timeout) {
g_source_remove(client->remote->auth_timeout);
}
client->remote->auth_timeout = 0;
/* Alert other clients of the new connection */
notify_of_new_client(client);
}
return 0;
}
rc = crm_remote_ready(client->remote, 0);
if (rc == 0) {
/* no msg to read */
return 0;
} else if (rc < 0) {
crm_info("Client disconnected during remote client read");
return -1;
}
crm_remote_recv(client->remote, -1, &disconnected);
request = crm_remote_parse_buffer(client->remote);
while (request) {
crm_element_value_int(request, F_LRMD_REMOTE_MSG_ID, &id);
crm_trace("processing request from remote client with remote msg id %d", id);
if (!client->name) {
const char *value = crm_element_value(request, F_LRMD_CLIENTNAME);
if (value) {
client->name = strdup(value);
}
}
lrmd_call_id++;
if (lrmd_call_id < 1) {
lrmd_call_id = 1;
}
crm_xml_add(request, F_LRMD_CLIENTID, client->id);
crm_xml_add(request, F_LRMD_CLIENTNAME, client->name);
crm_xml_add_int(request, F_LRMD_CALLID, lrmd_call_id);
process_lrmd_message(client, id, request);
free_xml(request);
/* process all the messages in the current buffer */
request = crm_remote_parse_buffer(client->remote);
}
if (disconnected) {
crm_info("Client disconnect detected in tls msg dispatcher.");
return -1;
}
return 0;
}
| 168,784
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fdct4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fdct4x4_c(in, out, stride);
}
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 fdct4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
void fdct4x4_ref(const int16_t *in, tran_low_t *out, int stride,
int tx_type) {
vpx_fdct4x4_c(in, out, stride);
}
| 174,557
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE omx_video::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
DEBUG_PRINT_LOW("FTB: buffer->pBuffer[%p]", buffer->pBuffer);
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: FTB in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL ||(buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Invalid buffer or size");
return OMX_ErrorBadParameter;
}
if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->OMX Version Invalid");
return OMX_ErrorVersionMismatch;
}
if (buffer->nOutputPortIndex != (OMX_U32)PORT_INDEX_OUT) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Bad port index");
return OMX_ErrorBadPortIndex;
}
if (!m_sOutPortDef.bEnabled) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->port is disabled");
return OMX_ErrorIncorrectStateOperation;
}
post_event((unsigned long) hComp, (unsigned long)buffer,OMX_COMPONENT_GENERATE_FTB);
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27903498
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVenc problem #3)
CRs-Fixed: 1010088
Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3
CWE ID:
|
OMX_ERRORTYPE omx_video::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
DEBUG_PRINT_LOW("FTB: buffer->pBuffer[%p]", buffer->pBuffer);
if (m_state != OMX_StateExecuting &&
m_state != OMX_StatePause &&
m_state != OMX_StateIdle) {
DEBUG_PRINT_ERROR("ERROR: FTB in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL ||(buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Invalid buffer or size");
return OMX_ErrorBadParameter;
}
if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->OMX Version Invalid");
return OMX_ErrorVersionMismatch;
}
if (buffer->nOutputPortIndex != (OMX_U32)PORT_INDEX_OUT) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Bad port index");
return OMX_ErrorBadPortIndex;
}
if (!m_sOutPortDef.bEnabled) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->port is disabled");
return OMX_ErrorIncorrectStateOperation;
}
post_event((unsigned long) hComp, (unsigned long)buffer,OMX_COMPONENT_GENERATE_FTB);
return OMX_ErrorNone;
}
| 173,747
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void TEMPLATE(process_block_dec)(decoder_info_t *decoder_info,int size,int yposY,int xposY,int sub)
{
int width = decoder_info->width;
int height = decoder_info->height;
stream_t *stream = decoder_info->stream;
frame_type_t frame_type = decoder_info->frame_info.frame_type;
int split_flag = 0;
if (yposY >= height || xposY >= width)
return;
int decode_this_size = (yposY + size <= height) && (xposY + size <= width);
int decode_rectangular_size = !decode_this_size && frame_type != I_FRAME;
int bit_start = stream->bitcnt;
int mode = MODE_SKIP;
block_context_t block_context;
TEMPLATE(find_block_contexts)(yposY, xposY, height, width, size, decoder_info->deblock_data, &block_context, decoder_info->use_block_contexts);
decoder_info->block_context = &block_context;
split_flag = decode_super_mode(decoder_info,size,decode_this_size);
mode = decoder_info->mode;
/* Read delta_qp and set block-level qp */
if (size == (1<<decoder_info->log2_sb_size) && (split_flag || mode != MODE_SKIP) && decoder_info->max_delta_qp > 0) {
/* Read delta_qp */
int delta_qp = read_delta_qp(stream);
int prev_qp;
if (yposY == 0 && xposY == 0)
prev_qp = decoder_info->frame_info.qp;
else
prev_qp = decoder_info->frame_info.qpb;
decoder_info->frame_info.qpb = prev_qp + delta_qp;
}
decoder_info->bit_count.super_mode[decoder_info->bit_count.stat_frame_type] += (stream->bitcnt - bit_start);
if (split_flag){
int new_size = size/2;
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+0*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+0*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+1*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+1*new_size,sub);
}
else if (decode_this_size || decode_rectangular_size){
decode_block(decoder_info,size,yposY,xposY,sub);
}
}
Commit Message: Fix possible stack overflows in decoder for illegal bit streams
Fixes CVE-2018-0429
A vulnerability in the Thor decoder (available at:
https://github.com/cisco/thor) could allow an authenticated, local
attacker to cause segmentation faults and stack overflows when using a
non-conformant Thor bitstream as input.
The vulnerability is due to lack of input validation when parsing the
bitstream. A successful exploit could allow the attacker to cause a
stack overflow and potentially inject and execute arbitrary code.
CWE ID: CWE-119
|
void TEMPLATE(process_block_dec)(decoder_info_t *decoder_info,int size,int yposY,int xposY,int sub)
{
int width = decoder_info->width;
int height = decoder_info->height;
stream_t *stream = decoder_info->stream;
frame_type_t frame_type = decoder_info->frame_info.frame_type;
int split_flag = 0;
if (yposY >= height || xposY >= width)
return;
int decode_this_size = (yposY + size <= height) && (xposY + size <= width);
int decode_rectangular_size = !decode_this_size && frame_type != I_FRAME;
int bit_start = stream->bitcnt;
int mode = MODE_SKIP;
block_context_t block_context;
TEMPLATE(find_block_contexts)(yposY, xposY, height, width, size, decoder_info->deblock_data, &block_context, decoder_info->use_block_contexts);
decoder_info->block_context = &block_context;
split_flag = decode_super_mode(decoder_info,size,decode_this_size);
mode = decoder_info->mode;
/* Read delta_qp and set block-level qp */
if (size == (1<<decoder_info->log2_sb_size) && (split_flag || mode != MODE_SKIP) && decoder_info->max_delta_qp > 0) {
/* Read delta_qp */
int delta_qp = read_delta_qp(stream);
int prev_qp;
if (yposY == 0 && xposY == 0)
prev_qp = decoder_info->frame_info.qp;
else
prev_qp = decoder_info->frame_info.qpb;
decoder_info->frame_info.qpb = prev_qp + delta_qp;
}
decoder_info->bit_count.super_mode[decoder_info->bit_count.stat_frame_type] += (stream->bitcnt - bit_start);
if (split_flag && size >= MIN_BLOCK_SIZE){
int new_size = size/2;
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+0*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+0*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+1*new_size,sub);
TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+1*new_size,sub);
}
else if (decode_this_size || decode_rectangular_size){
decode_block(decoder_info,size,yposY,xposY,sub);
}
}
| 169,366
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src,
int l2w, int l2h, int xoff, int yoff,
unsigned int *sse_ptr) {
int se = 0;
unsigned int sse = 0;
const int w = 1 << l2w, h = 1 << l2h;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
const int a1 = ref[(w + 1) * (y + 0) + x + 0];
const int a2 = ref[(w + 1) * (y + 0) + x + 1];
const int b1 = ref[(w + 1) * (y + 1) + x + 0];
const int b2 = ref[(w + 1) * (y + 1) + x + 1];
const int a = a1 + (((a2 - a1) * xoff + 8) >> 4);
const int b = b1 + (((b2 - b1) * xoff + 8) >> 4);
const int r = a + (((b - a) * yoff + 8) >> 4);
int diff = r - src[w * y + x];
se += diff;
sse += diff * diff;
}
}
*sse_ptr = sse;
return sse - (((int64_t) se * se) >> (l2w + l2h));
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src,
static unsigned int mb_ss_ref(const int16_t *src) {
unsigned int res = 0;
for (int i = 0; i < 256; ++i) {
res += src[i] * src[i];
}
return res;
}
static uint32_t variance_ref(const uint8_t *src, const uint8_t *ref,
int l2w, int l2h, int src_stride_coeff,
int ref_stride_coeff, uint32_t *sse_ptr,
bool use_high_bit_depth_,
vpx_bit_depth_t bit_depth) {
int64_t se = 0;
uint64_t sse = 0;
const int w = 1 << l2w;
const int h = 1 << l2h;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int diff;
if (!use_high_bit_depth_) {
diff = ref[w * y * ref_stride_coeff + x] -
src[w * y * src_stride_coeff + x];
se += diff;
sse += diff * diff;
#if CONFIG_VP9_HIGHBITDEPTH
} else {
diff = CONVERT_TO_SHORTPTR(ref)[w * y * ref_stride_coeff + x] -
CONVERT_TO_SHORTPTR(src)[w * y * src_stride_coeff + x];
se += diff;
sse += diff * diff;
#endif // CONFIG_VP9_HIGHBITDEPTH
}
}
}
RoundHighBitDepth(bit_depth, &se, &sse);
*sse_ptr = static_cast<uint32_t>(sse);
return static_cast<uint32_t>(sse -
((static_cast<int64_t>(se) * se) >>
(l2w + l2h)));
}
/* The subpel reference functions differ from the codec version in one aspect:
* they calculate the bilinear factors directly instead of using a lookup table
* and therefore upshift xoff and yoff by 1. Only every other calculated value
* is used so the codec version shrinks the table to save space and maintain
* compatibility with vp8.
*/
static uint32_t subpel_variance_ref(const uint8_t *ref, const uint8_t *src,
int l2w, int l2h, int xoff, int yoff,
uint32_t *sse_ptr,
bool use_high_bit_depth_,
vpx_bit_depth_t bit_depth) {
int64_t se = 0;
uint64_t sse = 0;
const int w = 1 << l2w;
const int h = 1 << l2h;
xoff <<= 1;
yoff <<= 1;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
// Bilinear interpolation at a 16th pel step.
if (!use_high_bit_depth_) {
const int a1 = ref[(w + 1) * (y + 0) + x + 0];
const int a2 = ref[(w + 1) * (y + 0) + x + 1];
const int b1 = ref[(w + 1) * (y + 1) + x + 0];
const int b2 = ref[(w + 1) * (y + 1) + x + 1];
const int a = a1 + (((a2 - a1) * xoff + 8) >> 4);
const int b = b1 + (((b2 - b1) * xoff + 8) >> 4);
const int r = a + (((b - a) * yoff + 8) >> 4);
const int diff = r - src[w * y + x];
se += diff;
sse += diff * diff;
#if CONFIG_VP9_HIGHBITDEPTH
} else {
uint16_t *ref16 = CONVERT_TO_SHORTPTR(ref);
uint16_t *src16 = CONVERT_TO_SHORTPTR(src);
const int a1 = ref16[(w + 1) * (y + 0) + x + 0];
const int a2 = ref16[(w + 1) * (y + 0) + x + 1];
const int b1 = ref16[(w + 1) * (y + 1) + x + 0];
const int b2 = ref16[(w + 1) * (y + 1) + x + 1];
const int a = a1 + (((a2 - a1) * xoff + 8) >> 4);
const int b = b1 + (((b2 - b1) * xoff + 8) >> 4);
const int r = a + (((b - a) * yoff + 8) >> 4);
const int diff = r - src16[w * y + x];
se += diff;
sse += diff * diff;
#endif // CONFIG_VP9_HIGHBITDEPTH
}
}
}
RoundHighBitDepth(bit_depth, &se, &sse);
*sse_ptr = static_cast<uint32_t>(sse);
return static_cast<uint32_t>(sse -
((static_cast<int64_t>(se) * se) >>
(l2w + l2h)));
}
class SumOfSquaresTest : public ::testing::TestWithParam<SumOfSquaresFunction> {
public:
SumOfSquaresTest() : func_(GetParam()) {}
virtual ~SumOfSquaresTest() {
libvpx_test::ClearSystemState();
}
protected:
void ConstTest();
void RefTest();
SumOfSquaresFunction func_;
ACMRandom rnd_;
};
void SumOfSquaresTest::ConstTest() {
int16_t mem[256];
unsigned int res;
for (int v = 0; v < 256; ++v) {
for (int i = 0; i < 256; ++i) {
mem[i] = v;
}
ASM_REGISTER_STATE_CHECK(res = func_(mem));
EXPECT_EQ(256u * (v * v), res);
}
}
void SumOfSquaresTest::RefTest() {
int16_t mem[256];
for (int i = 0; i < 100; ++i) {
for (int j = 0; j < 256; ++j) {
mem[j] = rnd_.Rand8() - rnd_.Rand8();
}
const unsigned int expected = mb_ss_ref(mem);
unsigned int res;
ASM_REGISTER_STATE_CHECK(res = func_(mem));
EXPECT_EQ(expected, res);
}
}
| 174,595
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CrosLibrary::TestApi::SetTouchpadLibrary(
TouchpadLibrary* library, bool own) {
library_->touchpad_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
void CrosLibrary::TestApi::SetTouchpadLibrary(
| 170,648
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1 ||
bitRate->eControlRate != OMX_Video_ControlRateVariable) {
return OMX_ErrorUndefined;
}
mBitrate = bitRate->nTargetBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline ||
h263type->eLevel != OMX_VIDEO_H263Level45 ||
(h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
h263type->bPLUSPTYPEAllowed != OMX_FALSE ||
h263type->bForceRoundingTypeToZero != OMX_FALSE ||
h263type->nPictureHeaderRepetition != 0 ||
h263type->nGOBHeaderInterval != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore ||
mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 ||
(mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
mpeg4type->nBFrames != 0 ||
mpeg4type->nIDCVLCThreshold != 0 ||
mpeg4type->bACPred != OMX_TRUE ||
mpeg4type->nMaxPacketSize != 256 ||
mpeg4type->nTimeIncRes != 1000 ||
mpeg4type->nHeaderExtension != 0 ||
mpeg4type->bReversibleVLC != OMX_FALSE) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::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 SoftMPEG4Encoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
if (bitRate->nPortIndex != 1 ||
bitRate->eControlRate != OMX_Video_ControlRateVariable) {
return OMX_ErrorUndefined;
}
mBitrate = bitRate->nTargetBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (!isValidOMXParam(h263type)) {
return OMX_ErrorBadParameter;
}
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline ||
h263type->eLevel != OMX_VIDEO_H263Level45 ||
(h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
h263type->bPLUSPTYPEAllowed != OMX_FALSE ||
h263type->bForceRoundingTypeToZero != OMX_FALSE ||
h263type->nPictureHeaderRepetition != 0 ||
h263type->nGOBHeaderInterval != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (!isValidOMXParam(mpeg4type)) {
return OMX_ErrorBadParameter;
}
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore ||
mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 ||
(mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) ||
mpeg4type->nBFrames != 0 ||
mpeg4type->nIDCVLCThreshold != 0 ||
mpeg4type->bACPred != OMX_TRUE ||
mpeg4type->nMaxPacketSize != 256 ||
mpeg4type->nTimeIncRes != 1000 ||
mpeg4type->nHeaderExtension != 0 ||
mpeg4type->bReversibleVLC != OMX_FALSE) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, params);
}
}
| 174,210
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) {
size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0);
icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length);
if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) ==
ustr_host.length())
transliterator_.get()->transliterate(ustr_host);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeString ustr_skeleton;
uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton,
&status);
if (U_FAILURE(status))
return false;
std::string skeleton;
ustr_skeleton.toUTF8String(skeleton);
return LookupMatchInTopDomains(skeleton);
}
Commit Message: Add a few more confusable map entries
1. Map Malaylam U+0D1F to 's'.
2. Map 'small-cap-like' Cyrillic letters to "look-alike" Latin lowercase
letters.
The characters in new confusable map entries are replaced by their Latin
"look-alike" characters before the skeleton is calculated to compare with
top domain names.
Bug: 784761,773930
Test: components_unittests --gtest_filter=*IDNToUni*
Change-Id: Ib26664e21ac5eb290e4a2993b01cbf0edaade0ee
Reviewed-on: https://chromium-review.googlesource.com/805214
Reviewed-by: Peter Kasting <pkasting@chromium.org>
Commit-Queue: Jungshik Shin <jshin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#521648}
CWE ID: CWE-20
|
bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) {
size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0);
icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length);
if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) ==
ustr_host.length())
diacritic_remover_.get()->transliterate(ustr_host);
extra_confusable_mapper_.get()->transliterate(ustr_host);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeString ustr_skeleton;
uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton,
&status);
if (U_FAILURE(status))
return false;
std::string skeleton;
return LookupMatchInTopDomains(ustr_skeleton.toUTF8String(skeleton));
}
| 172,686
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
const uint8_t *src, int src_size)
{
int width, height;
int hdr, zsize, npal, tidx = -1, ret;
int i, j;
const uint8_t *src_end = src + src_size;
uint8_t pal[768], transp[3];
uLongf dlen = (c->tile_width + 1) * c->tile_height;
int sub_type;
int nblocks, cblocks, bstride;
int bits, bitbuf, coded;
uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
tile_y * c->tile_height * c->framebuf_stride;
if (src_size < 2)
return AVERROR_INVALIDDATA;
width = FFMIN(c->width - tile_x * c->tile_width, c->tile_width);
height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
hdr = *src++;
sub_type = hdr >> 5;
if (sub_type == 0) {
int j;
memcpy(transp, src, 3);
src += 3;
for (j = 0; j < height; j++, dst += c->framebuf_stride)
for (i = 0; i < width; i++)
memcpy(dst + i * 3, transp, 3);
return 0;
} else if (sub_type == 1) {
return jpg_decode_data(&c->jc, width, height, src, src_end - src,
dst, c->framebuf_stride, NULL, 0, 0, 0);
}
if (sub_type != 2) {
memcpy(transp, src, 3);
src += 3;
}
npal = *src++ + 1;
memcpy(pal, src, npal * 3); src += npal * 3;
if (sub_type != 2) {
for (i = 0; i < npal; i++) {
if (!memcmp(pal + i * 3, transp, 3)) {
tidx = i;
break;
}
}
}
if (src_end - src < 2)
return 0;
zsize = (src[0] << 8) | src[1]; src += 2;
if (src_end - src < zsize)
return AVERROR_INVALIDDATA;
ret = uncompress(c->kempf_buf, &dlen, src, zsize);
if (ret)
return AVERROR_INVALIDDATA;
src += zsize;
if (sub_type == 2) {
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
NULL, 0, width, height, pal, npal, tidx);
return 0;
}
nblocks = *src++ + 1;
cblocks = 0;
bstride = FFALIGN(width, 16) >> 4;
bits = 0;
for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
if (!bits) {
bitbuf = *src++;
bits = 8;
}
coded = bitbuf & 1;
bits--;
bitbuf >>= 1;
cblocks += coded;
if (cblocks > nblocks)
return AVERROR_INVALIDDATA;
c->kempf_flags[j + i * bstride] = coded;
}
}
memset(c->jpeg_tile, 0, c->tile_stride * height);
jpg_decode_data(&c->jc, width, height, src, src_end - src,
c->jpeg_tile, c->tile_stride,
c->kempf_flags, bstride, nblocks, 0);
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
c->jpeg_tile, c->tile_stride,
width, height, pal, npal, tidx);
return 0;
}
Commit Message: avcodec/g2meet: fix src pointer checks in kempf_decode_tile()
Fixes Ticket2842
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
CWE ID: CWE-119
|
static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
const uint8_t *src, int src_size)
{
int width, height;
int hdr, zsize, npal, tidx = -1, ret;
int i, j;
const uint8_t *src_end = src + src_size;
uint8_t pal[768], transp[3];
uLongf dlen = (c->tile_width + 1) * c->tile_height;
int sub_type;
int nblocks, cblocks, bstride;
int bits, bitbuf, coded;
uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
tile_y * c->tile_height * c->framebuf_stride;
if (src_size < 2)
return AVERROR_INVALIDDATA;
width = FFMIN(c->width - tile_x * c->tile_width, c->tile_width);
height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
hdr = *src++;
sub_type = hdr >> 5;
if (sub_type == 0) {
int j;
memcpy(transp, src, 3);
src += 3;
for (j = 0; j < height; j++, dst += c->framebuf_stride)
for (i = 0; i < width; i++)
memcpy(dst + i * 3, transp, 3);
return 0;
} else if (sub_type == 1) {
return jpg_decode_data(&c->jc, width, height, src, src_end - src,
dst, c->framebuf_stride, NULL, 0, 0, 0);
}
if (sub_type != 2) {
memcpy(transp, src, 3);
src += 3;
}
npal = *src++ + 1;
memcpy(pal, src, npal * 3); src += npal * 3;
if (sub_type != 2) {
for (i = 0; i < npal; i++) {
if (!memcmp(pal + i * 3, transp, 3)) {
tidx = i;
break;
}
}
}
if (src_end - src < 2)
return 0;
zsize = (src[0] << 8) | src[1]; src += 2;
if (src_end - src < zsize + (sub_type != 2))
return AVERROR_INVALIDDATA;
ret = uncompress(c->kempf_buf, &dlen, src, zsize);
if (ret)
return AVERROR_INVALIDDATA;
src += zsize;
if (sub_type == 2) {
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
NULL, 0, width, height, pal, npal, tidx);
return 0;
}
nblocks = *src++ + 1;
cblocks = 0;
bstride = FFALIGN(width, 16) >> 4;
bits = 0;
for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
if (!bits) {
if (src >= src_end)
return AVERROR_INVALIDDATA;
bitbuf = *src++;
bits = 8;
}
coded = bitbuf & 1;
bits--;
bitbuf >>= 1;
cblocks += coded;
if (cblocks > nblocks)
return AVERROR_INVALIDDATA;
c->kempf_flags[j + i * bstride] = coded;
}
}
memset(c->jpeg_tile, 0, c->tile_stride * height);
jpg_decode_data(&c->jc, width, height, src, src_end - src,
c->jpeg_tile, c->tile_stride,
c->kempf_flags, bstride, nblocks, 0);
kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
c->jpeg_tile, c->tile_stride,
width, height, pal, npal, tidx);
return 0;
}
| 165,996
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: v8::Local<v8::Value> V8ValueConverterImpl::ToV8Object(
v8::Isolate* isolate,
v8::Local<v8::Object> creation_context,
const base::DictionaryValue* val) const {
v8::Local<v8::Object> result(v8::Object::New(isolate));
for (base::DictionaryValue::Iterator iter(*val);
!iter.IsAtEnd(); iter.Advance()) {
const std::string& key = iter.key();
v8::Local<v8::Value> child_v8 =
ToV8ValueImpl(isolate, creation_context, &iter.value());
CHECK(!child_v8.IsEmpty());
v8::TryCatch try_catch(isolate);
result->Set(
v8::String::NewFromUtf8(
isolate, key.c_str(), v8::String::kNormalString, key.length()),
child_v8);
if (try_catch.HasCaught()) {
LOG(ERROR) << "Setter for property " << key.c_str() << " threw an "
<< "exception.";
}
}
return result;
}
Commit Message: V8ValueConverter::ToV8Value should not trigger setters
BUG=606390
Review URL: https://codereview.chromium.org/1918793003
Cr-Commit-Position: refs/heads/master@{#390045}
CWE ID:
|
v8::Local<v8::Value> V8ValueConverterImpl::ToV8Object(
v8::Isolate* isolate,
v8::Local<v8::Object> creation_context,
const base::DictionaryValue* val) const {
v8::Local<v8::Object> result(v8::Object::New(isolate));
// TODO(robwu): Callers should pass in the context.
v8::Local<v8::Context> context = isolate->GetCurrentContext();
for (base::DictionaryValue::Iterator iter(*val);
!iter.IsAtEnd(); iter.Advance()) {
const std::string& key = iter.key();
v8::Local<v8::Value> child_v8 =
ToV8ValueImpl(isolate, creation_context, &iter.value());
CHECK(!child_v8.IsEmpty());
v8::Maybe<bool> maybe = result->CreateDataProperty(
context,
v8::String::NewFromUtf8(isolate, key.c_str(), v8::String::kNormalString,
key.length()),
child_v8);
if (!maybe.IsJust() || !maybe.FromJust())
LOG(ERROR) << "Failed to set property with key " << key;
}
return result;
}
| 173,284
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void OnDidAddMessageToConsole(int32_t,
const base::string16& message,
int32_t,
const base::string16&) {
callback_.Run(message);
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <lowell@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Camille Lamy <clamy@chromium.org>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
|
void OnDidAddMessageToConsole(int32_t,
| 172,490
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int nsv_parse_NSVf_header(AVFormatContext *s)
{
NSVContext *nsv = s->priv_data;
AVIOContext *pb = s->pb;
unsigned int av_unused file_size;
unsigned int size;
int64_t duration;
int strings_size;
int table_entries;
int table_entries_used;
nsv->state = NSV_UNSYNC; /* in case we fail */
size = avio_rl32(pb);
if (size < 28)
return -1;
nsv->NSVf_end = size;
file_size = (uint32_t)avio_rl32(pb);
av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size);
av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size);
nsv->duration = duration = avio_rl32(pb); /* in ms */
av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration);
strings_size = avio_rl32(pb);
table_entries = avio_rl32(pb);
table_entries_used = avio_rl32(pb);
av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",
strings_size, table_entries, table_entries_used);
if (avio_feof(pb))
return -1;
av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb));
if (strings_size > 0) {
char *strings; /* last byte will be '\0' to play safe with str*() */
char *p, *endp;
char *token, *value;
char quote;
p = strings = av_mallocz((size_t)strings_size + 1);
if (!p)
return AVERROR(ENOMEM);
endp = strings + strings_size;
avio_read(pb, strings, strings_size);
while (p < endp) {
while (*p == ' ')
p++; /* strip out spaces */
if (p >= endp-2)
break;
token = p;
p = strchr(p, '=');
if (!p || p >= endp-2)
break;
*p++ = '\0';
quote = *p++;
value = p;
p = strchr(p, quote);
if (!p || p >= endp)
break;
*p++ = '\0';
av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value);
av_dict_set(&s->metadata, token, value, 0);
}
av_free(strings);
}
if (avio_feof(pb))
return -1;
av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb));
if (table_entries_used > 0) {
int i;
nsv->index_entries = table_entries_used;
if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t))
return -1;
nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t));
if (!nsv->nsvs_file_offset)
return AVERROR(ENOMEM);
for(i=0;i<table_entries_used;i++)
nsv->nsvs_file_offset[i] = avio_rl32(pb) + size;
if(table_entries > table_entries_used &&
avio_rl32(pb) == MKTAG('T','O','C','2')) {
nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t));
if (!nsv->nsvs_timestamps)
return AVERROR(ENOMEM);
for(i=0;i<table_entries_used;i++) {
nsv->nsvs_timestamps[i] = avio_rl32(pb);
}
}
}
av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb));
avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */
if (avio_feof(pb))
return -1;
nsv->state = NSV_HAS_READ_NSVF;
return 0;
}
Commit Message: avformat/nsvdec: Fix DoS due to lack of eof check in nsvs_file_offset loop.
Fixes: 20170829.nsv
Co-Author: 张洪亮(望初)" <wangchu.zhl@alibaba-inc.com>
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-834
|
static int nsv_parse_NSVf_header(AVFormatContext *s)
{
NSVContext *nsv = s->priv_data;
AVIOContext *pb = s->pb;
unsigned int av_unused file_size;
unsigned int size;
int64_t duration;
int strings_size;
int table_entries;
int table_entries_used;
nsv->state = NSV_UNSYNC; /* in case we fail */
size = avio_rl32(pb);
if (size < 28)
return -1;
nsv->NSVf_end = size;
file_size = (uint32_t)avio_rl32(pb);
av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size);
av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size);
nsv->duration = duration = avio_rl32(pb); /* in ms */
av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration);
strings_size = avio_rl32(pb);
table_entries = avio_rl32(pb);
table_entries_used = avio_rl32(pb);
av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",
strings_size, table_entries, table_entries_used);
if (avio_feof(pb))
return -1;
av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb));
if (strings_size > 0) {
char *strings; /* last byte will be '\0' to play safe with str*() */
char *p, *endp;
char *token, *value;
char quote;
p = strings = av_mallocz((size_t)strings_size + 1);
if (!p)
return AVERROR(ENOMEM);
endp = strings + strings_size;
avio_read(pb, strings, strings_size);
while (p < endp) {
while (*p == ' ')
p++; /* strip out spaces */
if (p >= endp-2)
break;
token = p;
p = strchr(p, '=');
if (!p || p >= endp-2)
break;
*p++ = '\0';
quote = *p++;
value = p;
p = strchr(p, quote);
if (!p || p >= endp)
break;
*p++ = '\0';
av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value);
av_dict_set(&s->metadata, token, value, 0);
}
av_free(strings);
}
if (avio_feof(pb))
return -1;
av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb));
if (table_entries_used > 0) {
int i;
nsv->index_entries = table_entries_used;
if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t))
return -1;
nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t));
if (!nsv->nsvs_file_offset)
return AVERROR(ENOMEM);
for(i=0;i<table_entries_used;i++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
nsv->nsvs_file_offset[i] = avio_rl32(pb) + size;
}
if(table_entries > table_entries_used &&
avio_rl32(pb) == MKTAG('T','O','C','2')) {
nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t));
if (!nsv->nsvs_timestamps)
return AVERROR(ENOMEM);
for(i=0;i<table_entries_used;i++) {
nsv->nsvs_timestamps[i] = avio_rl32(pb);
}
}
}
av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb));
avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */
if (avio_feof(pb))
return -1;
nsv->state = NSV_HAS_READ_NSVF;
return 0;
}
| 167,764
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GpuChannelHost::GpuChannelHost(
GpuChannelHostFactory* factory, int gpu_process_id, int client_id)
: factory_(factory),
gpu_process_id_(gpu_process_id),
client_id_(client_id),
state_(kUnconnected) {
}
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:
|
GpuChannelHost::GpuChannelHost(
GpuChannelHostFactory* factory, int gpu_host_id, int client_id)
: factory_(factory),
client_id_(client_id),
gpu_host_id_(gpu_host_id),
state_(kUnconnected) {
}
| 170,929
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::SetPinCode(const std::string& pincode) {
if (!agent_.get() || pincode_callback_.is_null())
return;
pincode_callback_.Run(SUCCESS, pincode);
pincode_callback_.Reset();
}
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::SetPinCode(const std::string& pincode) {
if (!pairing_context_.get())
return;
pairing_context_->SetPinCode(pincode);
}
| 171,240
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
long len;
id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
return E_FILE_FORMAT_INVALID;
}
const unsigned long long rollover_check =
static_cast<unsigned long long>(pos) + len;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
Commit Message: Fix ParseElementHeader to support 0 payload elements
Cherry-pick'ing Change 5c83bbec9a5f6f00a349674ddad85b753d2ea219
from upstream. This fixes regression in some edge cases for mkv
playback.
BUG=26499283
Change-Id: I88de03219a3d941b6b2f251d384e29c36bdd4d9b
CWE ID: CWE-20
|
long ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
long len;
id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
return E_FILE_FORMAT_INVALID;
}
const unsigned long long rollover_check =
static_cast<unsigned long long>(pos) + len;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if (stop >= 0 && pos > stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 174,229
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: void WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
channel_.reset();
if (launch_elevated_) {
if (job_.IsValid()) {
TerminateJobObject(job_, exit_code);
}
} else {
if (worker_process_.IsValid()) {
TerminateProcess(worker_process_, exit_code);
}
}
}
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 WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
channel_.reset();
pipe_.Close();
if (launch_elevated_) {
if (job_.IsValid()) {
TerminateJobObject(job_, exit_code);
}
} else {
if (worker_process_.IsValid()) {
TerminateProcess(worker_process_, exit_code);
}
}
}
| 171,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: ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
int hdrlen;
uint16_t fc;
uint8_t seq;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4] %x", caplen));
return caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(fc);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[fc & 0x7]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
if (hdrlen == -1) {
ND_PRINT((ndo,"invalid! "));
return caplen;
}
if (!ndo->ndo_vflag) {
p+= hdrlen;
caplen -= hdrlen;
} else {
uint16_t panid = 0;
switch ((fc >> 10) & 0x3) {
case 0x00:
ND_PRINT((ndo,"none "));
break;
case 0x01:
ND_PRINT((ndo,"reserved destination addressing mode"));
return 0;
case 0x02:
panid = EXTRACT_LE_16BITS(p);
p += 2;
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
break;
case 0x03:
panid = EXTRACT_LE_16BITS(p);
p += 2;
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
break;
}
ND_PRINT((ndo,"< "));
switch ((fc >> 14) & 0x3) {
case 0x00:
ND_PRINT((ndo,"none "));
break;
case 0x01:
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case 0x02:
if (!(fc & (1 << 6))) {
panid = EXTRACT_LE_16BITS(p);
p += 2;
}
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
break;
case 0x03:
if (!(fc & (1 << 6))) {
panid = EXTRACT_LE_16BITS(p);
p += 2;
}
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
break;
}
caplen -= hdrlen;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return 0;
}
Commit Message: CVE-2017-13000/IEEE 802.15.4: Add more bounds checks.
While we're at it, add a bunch of macros for the frame control field's
subfields, have the reserved frame types show the frame type value, use
the same code path for processing source and destination addresses
regardless of whether -v was specified (just leave out the addresses in
non-verbose mode), and return the header length in all cases.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125
|
ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| 170,030
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintDialogGtk::UpdateSettings(const DictionaryValue& settings,
const printing::PageRanges& ranges) {
bool collate;
int color;
bool landscape;
bool print_to_pdf;
int copies;
int duplex_mode;
std::string device_name;
if (!settings.GetBoolean(printing::kSettingLandscape, &landscape) ||
!settings.GetBoolean(printing::kSettingCollate, &collate) ||
!settings.GetInteger(printing::kSettingColor, &color) ||
!settings.GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf) ||
!settings.GetInteger(printing::kSettingDuplexMode, &duplex_mode) ||
!settings.GetInteger(printing::kSettingCopies, &copies) ||
!settings.GetString(printing::kSettingDeviceName, &device_name)) {
return false;
}
if (!print_to_pdf) {
scoped_ptr<GtkPrinterList> printer_list(new GtkPrinterList);
printer_ = printer_list->GetPrinterWithName(device_name.c_str());
if (printer_) {
g_object_ref(printer_);
gtk_print_settings_set_printer(gtk_settings_,
gtk_printer_get_name(printer_));
}
gtk_print_settings_set_n_copies(gtk_settings_, copies);
gtk_print_settings_set_collate(gtk_settings_, collate);
const char* color_mode;
switch (color) {
case printing::COLOR:
color_mode = kColor;
break;
case printing::CMYK:
color_mode = kCMYK;
break;
default:
color_mode = kGrayscale;
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSColorModel, color_mode);
if (duplex_mode != printing::UNKNOWN_DUPLEX_MODE) {
const char* cups_duplex_mode = NULL;
switch (duplex_mode) {
case printing::LONG_EDGE:
cups_duplex_mode = kDuplexNoTumble;
break;
case printing::SHORT_EDGE:
cups_duplex_mode = kDuplexTumble;
break;
case printing::SIMPLEX:
cups_duplex_mode = kDuplexNone;
break;
default: // UNKNOWN_DUPLEX_MODE
NOTREACHED();
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSDuplex, cups_duplex_mode);
}
}
gtk_print_settings_set_orientation(
gtk_settings_,
landscape ? GTK_PAGE_ORIENTATION_LANDSCAPE :
GTK_PAGE_ORIENTATION_PORTRAIT);
InitPrintSettings(ranges);
return true;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool PrintDialogGtk::UpdateSettings(const DictionaryValue& settings,
const printing::PageRanges& ranges) {
bool collate;
int color;
bool landscape;
bool print_to_pdf;
int copies;
int duplex_mode;
std::string device_name;
if (!settings.GetBoolean(printing::kSettingLandscape, &landscape) ||
!settings.GetBoolean(printing::kSettingCollate, &collate) ||
!settings.GetInteger(printing::kSettingColor, &color) ||
!settings.GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf) ||
!settings.GetInteger(printing::kSettingDuplexMode, &duplex_mode) ||
!settings.GetInteger(printing::kSettingCopies, &copies) ||
!settings.GetString(printing::kSettingDeviceName, &device_name)) {
return false;
}
if (!gtk_settings_)
gtk_settings_ = gtk_print_settings_new();
if (!print_to_pdf) {
scoped_ptr<GtkPrinterList> printer_list(new GtkPrinterList);
printer_ = printer_list->GetPrinterWithName(device_name.c_str());
if (printer_) {
g_object_ref(printer_);
gtk_print_settings_set_printer(gtk_settings_,
gtk_printer_get_name(printer_));
if (!page_setup_) {
page_setup_ = gtk_printer_get_default_page_size(printer_);
}
}
if (!page_setup_)
page_setup_ = gtk_page_setup_new();
gtk_print_settings_set_n_copies(gtk_settings_, copies);
gtk_print_settings_set_collate(gtk_settings_, collate);
const char* color_mode;
switch (color) {
case printing::COLOR:
color_mode = kColor;
break;
case printing::CMYK:
color_mode = kCMYK;
break;
default:
color_mode = kGrayscale;
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSColorModel, color_mode);
if (duplex_mode != printing::UNKNOWN_DUPLEX_MODE) {
const char* cups_duplex_mode = NULL;
switch (duplex_mode) {
case printing::LONG_EDGE:
cups_duplex_mode = kDuplexNoTumble;
break;
case printing::SHORT_EDGE:
cups_duplex_mode = kDuplexTumble;
break;
case printing::SIMPLEX:
cups_duplex_mode = kDuplexNone;
break;
default: // UNKNOWN_DUPLEX_MODE
NOTREACHED();
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSDuplex, cups_duplex_mode);
}
}
gtk_print_settings_set_orientation(
gtk_settings_,
landscape ? GTK_PAGE_ORIENTATION_LANDSCAPE :
GTK_PAGE_ORIENTATION_PORTRAIT);
InitPrintSettings(ranges);
return true;
}
| 170,254
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vorbis_book_decodev_set(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j;
if (!v) return -1;
for(i=0;i<n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim;j++)
a[i++]=v[j];
}
}else{
int i,j;
for(i=0;i<n;){
for (j=0;j<book->dim;j++)
a[i++]=0;
}
}
return 0;
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200
|
long vorbis_book_decodev_set(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j;
if (!v) return -1;
for(i=0;i<n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim && i < n;j++)
a[i++]=v[j];
}
}else{
int i,j;
for(i=0;i<n;){
for (j=0;j<book->dim && i < n;j++)
a[i++]=0;
}
}
return 0;
}
| 173,987
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PatternMatch(char *pat, int patdashes, char *string, int stringdashes)
{
char c,
t;
if (stringdashes < patdashes)
return 0;
for (;;) {
switch (c = *pat++) {
case '*':
if (!(c = *pat++))
return 1;
if (c == XK_minus) {
patdashes--;
for (;;) {
while ((t = *string++) != XK_minus)
if (!t)
return 0;
stringdashes--;
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
if (stringdashes == patdashes)
return 0;
}
} else {
for (;;) {
while ((t = *string++) != c) {
if (!t)
return 0;
if (t == XK_minus) {
if (stringdashes-- < patdashes)
return 0;
}
}
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
}
}
case '?':
if (*string++ == XK_minus)
stringdashes--;
break;
case '\0':
return (*string == '\0');
patdashes--;
stringdashes--;
break;
}
return 0;
default:
if (c == *string++)
break;
return 0;
}
}
Commit Message:
CWE ID: CWE-125
|
PatternMatch(char *pat, int patdashes, char *string, int stringdashes)
{
char c,
t;
if (stringdashes < patdashes)
return 0;
for (;;) {
switch (c = *pat++) {
case '*':
if (!(c = *pat++))
return 1;
if (c == XK_minus) {
patdashes--;
for (;;) {
while ((t = *string++) != XK_minus)
if (!t)
return 0;
stringdashes--;
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
if (stringdashes == patdashes)
return 0;
}
} else {
for (;;) {
while ((t = *string++) != c) {
if (!t)
return 0;
if (t == XK_minus) {
if (stringdashes-- < patdashes)
return 0;
}
}
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
}
}
case '?':
if ((t = *string++) == XK_minus)
stringdashes--;
if (!t)
return 0;
break;
case '\0':
return (*string == '\0');
patdashes--;
stringdashes--;
break;
}
return 0;
default:
if (c == *string++)
break;
return 0;
}
}
| 164,693
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __init proc_root_init(void)
{
struct vfsmount *mnt;
int err;
proc_init_inodecache();
err = register_filesystem(&proc_fs_type);
if (err)
return;
mnt = kern_mount_data(&proc_fs_type, &init_pid_ns);
if (IS_ERR(mnt)) {
unregister_filesystem(&proc_fs_type);
return;
}
init_pid_ns.proc_mnt = mnt;
proc_symlink("mounts", NULL, "self/mounts");
proc_net_init();
#ifdef CONFIG_SYSVIPC
proc_mkdir("sysvipc", NULL);
#endif
proc_mkdir("fs", NULL);
proc_mkdir("driver", NULL);
proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */
#if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE)
/* just give it a mountpoint */
proc_mkdir("openprom", NULL);
#endif
proc_tty_init();
#ifdef CONFIG_PROC_DEVICETREE
proc_device_tree_init();
#endif
proc_mkdir("bus", NULL);
proc_sys_init();
}
Commit Message: procfs: fix a vfsmount longterm reference leak
kern_mount() doesn't pair with plain mntput()...
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-119
|
void __init proc_root_init(void)
{
int err;
proc_init_inodecache();
err = register_filesystem(&proc_fs_type);
if (err)
return;
err = pid_ns_prepare_proc(&init_pid_ns);
if (err) {
unregister_filesystem(&proc_fs_type);
return;
}
proc_symlink("mounts", NULL, "self/mounts");
proc_net_init();
#ifdef CONFIG_SYSVIPC
proc_mkdir("sysvipc", NULL);
#endif
proc_mkdir("fs", NULL);
proc_mkdir("driver", NULL);
proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */
#if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE)
/* just give it a mountpoint */
proc_mkdir("openprom", NULL);
#endif
proc_tty_init();
#ifdef CONFIG_PROC_DEVICETREE
proc_device_tree_init();
#endif
proc_mkdir("bus", NULL);
proc_sys_init();
}
| 165,615
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 registerStreamURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerStreamURL(blobRegistryContext->url, blobRegistryContext->type);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
static void registerStreamURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
if (WebBlobRegistry* registry = blobRegistry())
registry->registerStreamURL(blobRegistryContext->url, blobRegistryContext->type);
}
| 170,689
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ssize_t socket_bytes_available(const socket_t *socket) {
assert(socket != NULL);
int size = 0;
if (ioctl(socket->fd, FIONREAD, &size) == -1)
return -1;
return size;
}
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
|
ssize_t socket_bytes_available(const socket_t *socket) {
assert(socket != NULL);
int size = 0;
if (TEMP_FAILURE_RETRY(ioctl(socket->fd, FIONREAD, &size)) == -1)
return -1;
return size;
}
| 173,485
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CastCastView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
DCHECK(sender == stop_button_);
StopCast();
}
Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods.
BUG=489445
Review URL: https://codereview.chromium.org/1145833003
Cr-Commit-Position: refs/heads/master@{#330663}
CWE ID: CWE-79
|
void CastCastView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
DCHECK(sender == stop_button_);
cast_config_delegate_->StopCasting();
}
| 171,623
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CreateSession::ExecutePost(Response* const response) {
DictionaryValue *capabilities = NULL;
if (!GetDictionaryParameter("desiredCapabilities", &capabilities)) {
response->SetError(new Error(
kBadRequest, "Missing or invalid 'desiredCapabilities'"));
return;
}
CommandLine command_line_options(CommandLine::NO_PROGRAM);
ListValue* switches = NULL;
const char* kCustomSwitchesKey = "chrome.switches";
if (capabilities->GetListWithoutPathExpansion(kCustomSwitchesKey,
&switches)) {
for (size_t i = 0; i < switches->GetSize(); ++i) {
std::string switch_string;
if (!switches->GetString(i, &switch_string)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
size_t separator_index = switch_string.find("=");
if (separator_index != std::string::npos) {
CommandLine::StringType switch_string_native;
if (!switches->GetString(i, &switch_string_native)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
command_line_options.AppendSwitchNative(
switch_string.substr(0, separator_index),
switch_string_native.substr(separator_index + 1));
} else {
command_line_options.AppendSwitch(switch_string);
}
}
} else if (capabilities->HasKey(kCustomSwitchesKey)) {
response->SetError(new Error(
kBadRequest, "Custom switches must be a list"));
return;
}
FilePath browser_exe;
FilePath::StringType path;
if (capabilities->GetStringWithoutPathExpansion("chrome.binary", &path))
browser_exe = FilePath(path);
Session* session = new Session();
Error* error = session->Init(browser_exe, command_line_options);
if (error) {
response->SetError(error);
return;
}
bool native_events_required = false;
Value* native_events_value = NULL;
if (capabilities->GetWithoutPathExpansion(
"chrome.nativeEvents", &native_events_value)) {
if (native_events_value->GetAsBoolean(&native_events_required)) {
session->set_use_native_events(native_events_required);
}
}
bool screenshot_on_error = false;
if (capabilities->GetBoolean(
"takeScreenshotOnError", &screenshot_on_error)) {
session->set_screenshot_on_error(screenshot_on_error);
}
VLOG(1) << "Created session " << session->id();
std::ostringstream stream;
SessionManager* session_manager = SessionManager::GetInstance();
stream << "http://" << session_manager->GetAddress() << "/session/"
<< session->id();
response->SetStatus(kSeeOther);
response->SetValue(Value::CreateStringValue(stream.str()));
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void CreateSession::ExecutePost(Response* const response) {
DictionaryValue *capabilities = NULL;
if (!GetDictionaryParameter("desiredCapabilities", &capabilities)) {
response->SetError(new Error(
kBadRequest, "Missing or invalid 'desiredCapabilities'"));
return;
}
CommandLine command_line_options(CommandLine::NO_PROGRAM);
ListValue* switches = NULL;
const char* kCustomSwitchesKey = "chrome.switches";
if (capabilities->GetListWithoutPathExpansion(kCustomSwitchesKey,
&switches)) {
for (size_t i = 0; i < switches->GetSize(); ++i) {
std::string switch_string;
if (!switches->GetString(i, &switch_string)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
size_t separator_index = switch_string.find("=");
if (separator_index != std::string::npos) {
CommandLine::StringType switch_string_native;
if (!switches->GetString(i, &switch_string_native)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
command_line_options.AppendSwitchNative(
switch_string.substr(0, separator_index),
switch_string_native.substr(separator_index + 1));
} else {
command_line_options.AppendSwitch(switch_string);
}
}
} else if (capabilities->HasKey(kCustomSwitchesKey)) {
response->SetError(new Error(
kBadRequest, "Custom switches must be a list"));
return;
}
Value* verbose_value;
if (capabilities->GetWithoutPathExpansion("chrome.verbose", &verbose_value)) {
bool verbose;
if (verbose_value->GetAsBoolean(&verbose) && verbose) {
// Since logging is shared among sessions, if any session requests verbose
// logging, verbose logging will be enabled for all sessions. It is not
// possible to turn it off.
logging::SetMinLogLevel(logging::LOG_INFO);
} else {
response->SetError(new Error(
kBadRequest, "verbose must be a boolean true or false"));
return;
}
}
FilePath browser_exe;
FilePath::StringType path;
if (capabilities->GetStringWithoutPathExpansion("chrome.binary", &path))
browser_exe = FilePath(path);
Session* session = new Session();
Error* error = session->Init(browser_exe, command_line_options);
if (error) {
response->SetError(error);
return;
}
bool native_events_required = false;
Value* native_events_value = NULL;
if (capabilities->GetWithoutPathExpansion(
"chrome.nativeEvents", &native_events_value)) {
if (native_events_value->GetAsBoolean(&native_events_required)) {
session->set_use_native_events(native_events_required);
}
}
bool screenshot_on_error = false;
if (capabilities->GetBoolean(
"takeScreenshotOnError", &screenshot_on_error)) {
session->set_screenshot_on_error(screenshot_on_error);
}
LOG(INFO) << "Created session " << session->id();
std::ostringstream stream;
SessionManager* session_manager = SessionManager::GetInstance();
stream << "http://" << session_manager->GetAddress() << "/session/"
<< session->id();
response->SetStatus(kSeeOther);
response->SetValue(Value::CreateStringValue(stream.str()));
}
| 170,453
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long Cluster::GetEntryCount() const
{
return m_entries_count;
}
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 Cluster::GetEntryCount() const
| 174,318
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ShellWindowFrameView::OnPaint(gfx::Canvas* canvas) {
SkPaint paint;
paint.setAntiAlias(false);
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(SK_ColorWHITE);
gfx::Path path;
const int radius = 1;
path.moveTo(0, radius);
path.lineTo(radius, 0);
path.lineTo(width() - radius - 1, 0);
path.lineTo(width(), radius + 1);
path.lineTo(width(), kCaptionHeight);
path.lineTo(0, kCaptionHeight);
path.close();
canvas->DrawPath(path, paint);
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
R=ben@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
|
void ShellWindowFrameView::OnPaint(gfx::Canvas* canvas) {
if (is_frameless_)
return;
SkPaint paint;
paint.setAntiAlias(false);
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(SK_ColorWHITE);
gfx::Path path;
const int radius = 1;
path.moveTo(0, radius);
path.lineTo(radius, 0);
path.lineTo(width() - radius - 1, 0);
path.lineTo(width(), radius + 1);
path.lineTo(width(), kCaptionHeight);
path.lineTo(0, kCaptionHeight);
path.close();
canvas->DrawPath(path, paint);
}
| 170,717
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vpx_codec_err_t vp8_peek_si_internal(const uint8_t *data,
unsigned int data_sz,
vpx_codec_stream_info_t *si,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state)
{
vpx_codec_err_t res = VPX_CODEC_OK;
if(data + data_sz <= data)
{
res = VPX_CODEC_INVALID_PARAM;
}
else
{
/* Parse uncompresssed part of key frame header.
* 3 bytes:- including version, frame type and an offset
* 3 bytes:- sync code (0x9d, 0x01, 0x2a)
* 4 bytes:- including image width and height in the lowest 14 bits
* of each 2-byte value.
*/
uint8_t clear_buffer[10];
const uint8_t *clear = data;
if (decrypt_cb)
{
int n = MIN(sizeof(clear_buffer), data_sz);
decrypt_cb(decrypt_state, data, clear_buffer, n);
clear = clear_buffer;
}
si->is_kf = 0;
if (data_sz >= 10 && !(clear[0] & 0x01)) /* I-Frame */
{
si->is_kf = 1;
/* vet via sync code */
if (clear[3] != 0x9d || clear[4] != 0x01 || clear[5] != 0x2a)
return VPX_CODEC_UNSUP_BITSTREAM;
si->w = (clear[6] | (clear[7] << 8)) & 0x3fff;
si->h = (clear[8] | (clear[9] << 8)) & 0x3fff;
/*printf("w=%d, h=%d\n", si->w, si->h);*/
if (!(si->h | si->w))
res = VPX_CODEC_UNSUP_BITSTREAM;
}
else
{
res = VPX_CODEC_UNSUP_BITSTREAM;
}
}
return res;
}
Commit Message: DO NOT MERGE | libvpx: Cherry-pick 0f42d1f from upstream
Description from upstream:
vp8: fix decoder crash with invalid leading keyframes
decoding the same invalid keyframe twice would result in a crash as the
second time through the decoder would be assumed to have been
initialized as there was no resolution change. in this case the
resolution was itself invalid (0x6), but vp8_peek_si() was only failing
in the case of 0x0.
invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf tests this case by
duplicating the first keyframe and additionally adds a valid one to
ensure decoding can resume without error.
Bug: 30593765
Change-Id: I0de85f5a5eb5c0a5605230faf20c042b69aea507
(cherry picked from commit fc0466b695dce03e10390101844caa374848d903)
(cherry picked from commit 1114575245cb9d2f108749f916c76549524f5136)
CWE ID: CWE-20
|
static vpx_codec_err_t vp8_peek_si_internal(const uint8_t *data,
unsigned int data_sz,
vpx_codec_stream_info_t *si,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state)
{
vpx_codec_err_t res = VPX_CODEC_OK;
if(data + data_sz <= data)
{
res = VPX_CODEC_INVALID_PARAM;
}
else
{
/* Parse uncompresssed part of key frame header.
* 3 bytes:- including version, frame type and an offset
* 3 bytes:- sync code (0x9d, 0x01, 0x2a)
* 4 bytes:- including image width and height in the lowest 14 bits
* of each 2-byte value.
*/
uint8_t clear_buffer[10];
const uint8_t *clear = data;
if (decrypt_cb)
{
int n = MIN(sizeof(clear_buffer), data_sz);
decrypt_cb(decrypt_state, data, clear_buffer, n);
clear = clear_buffer;
}
si->is_kf = 0;
if (data_sz >= 10 && !(clear[0] & 0x01)) /* I-Frame */
{
si->is_kf = 1;
/* vet via sync code */
if (clear[3] != 0x9d || clear[4] != 0x01 || clear[5] != 0x2a)
return VPX_CODEC_UNSUP_BITSTREAM;
si->w = (clear[6] | (clear[7] << 8)) & 0x3fff;
si->h = (clear[8] | (clear[9] << 8)) & 0x3fff;
/*printf("w=%d, h=%d\n", si->w, si->h);*/
if (!(si->h && si->w))
res = VPX_CODEC_CORRUPT_FRAME;
}
else
{
res = VPX_CODEC_UNSUP_BITSTREAM;
}
}
return res;
}
| 173,383
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 color_cmyk_to_rgb(opj_image_t *image)
{
float C, M, Y, K;
float sC, sM, sY, sK;
unsigned int w, h, max, i;
w = image->comps[0].w;
h = image->comps[0].h;
if(image->numcomps < 4) return;
max = w * h;
sC = 1.0F / (float)((1 << image->comps[0].prec) - 1);
sM = 1.0F / (float)((1 << image->comps[1].prec) - 1);
sY = 1.0F / (float)((1 << image->comps[2].prec) - 1);
sK = 1.0F / (float)((1 << image->comps[3].prec) - 1);
for(i = 0; i < max; ++i)
{
/* CMYK values from 0 to 1 */
C = (float)(image->comps[0].data[i]) * sC;
M = (float)(image->comps[1].data[i]) * sM;
Y = (float)(image->comps[2].data[i]) * sY;
K = (float)(image->comps[3].data[i]) * sK;
/* Invert all CMYK values */
C = 1.0F - C;
M = 1.0F - M;
Y = 1.0F - Y;
K = 1.0F - K;
/* CMYK -> RGB : RGB results from 0 to 255 */
image->comps[0].data[i] = (int)(255.0F * C * K); /* R */
image->comps[1].data[i] = (int)(255.0F * M * K); /* G */
image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */
}
free(image->comps[3].data); image->comps[3].data = NULL;
image->comps[0].prec = 8;
image->comps[1].prec = 8;
image->comps[2].prec = 8;
image->numcomps -= 1;
image->color_space = OPJ_CLRSPC_SRGB;
for (i = 3; i < image->numcomps; ++i) {
memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i]));
}
}/* color_cmyk_to_rgb() */
Commit Message: Fix Heap Buffer Overflow in function color_cmyk_to_rgb
Fix uclouvain/openjpeg#774
CWE ID: CWE-119
|
void color_cmyk_to_rgb(opj_image_t *image)
{
float C, M, Y, K;
float sC, sM, sY, sK;
unsigned int w, h, max, i;
w = image->comps[0].w;
h = image->comps[0].h;
if (
(image->numcomps < 4)
|| (image->comps[0].dx != image->comps[1].dx) || (image->comps[0].dx != image->comps[2].dx) || (image->comps[0].dx != image->comps[3].dx)
|| (image->comps[0].dy != image->comps[1].dy) || (image->comps[0].dy != image->comps[2].dy) || (image->comps[0].dy != image->comps[3].dy)
) {
fprintf(stderr,"%s:%d:color_cmyk_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__);
return;
}
max = w * h;
sC = 1.0F / (float)((1 << image->comps[0].prec) - 1);
sM = 1.0F / (float)((1 << image->comps[1].prec) - 1);
sY = 1.0F / (float)((1 << image->comps[2].prec) - 1);
sK = 1.0F / (float)((1 << image->comps[3].prec) - 1);
for(i = 0; i < max; ++i)
{
/* CMYK values from 0 to 1 */
C = (float)(image->comps[0].data[i]) * sC;
M = (float)(image->comps[1].data[i]) * sM;
Y = (float)(image->comps[2].data[i]) * sY;
K = (float)(image->comps[3].data[i]) * sK;
/* Invert all CMYK values */
C = 1.0F - C;
M = 1.0F - M;
Y = 1.0F - Y;
K = 1.0F - K;
/* CMYK -> RGB : RGB results from 0 to 255 */
image->comps[0].data[i] = (int)(255.0F * C * K); /* R */
image->comps[1].data[i] = (int)(255.0F * M * K); /* G */
image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */
}
free(image->comps[3].data); image->comps[3].data = NULL;
image->comps[0].prec = 8;
image->comps[1].prec = 8;
image->comps[2].prec = 8;
image->numcomps -= 1;
image->color_space = OPJ_CLRSPC_SRGB;
for (i = 3; i < image->numcomps; ++i) {
memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i]));
}
}/* color_cmyk_to_rgb() */
| 168,836
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
unsigned long quirks = (unsigned long)hid_get_drvdata(hdev);
unsigned int i;
if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX))
return rdesc;
for (i = 0; i < *rsize - 4; i++)
if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) {
rdesc[i] = 0x19;
rdesc[i + 2] = 0x29;
swap(rdesc[i + 3], rdesc[i + 1]);
}
return rdesc;
}
Commit Message: HID: hid-cypress: validate length of report
Make sure we have enough of a report structure to validate before
looking at it.
Reported-by: Benoit Camredon <benoit.camredon@airbus.com>
Tested-by: Benoit Camredon <benoit.camredon@airbus.com>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID:
|
static __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
unsigned long quirks = (unsigned long)hid_get_drvdata(hdev);
unsigned int i;
if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX))
return rdesc;
if (*rsize < 4)
return rdesc;
for (i = 0; i < *rsize - 4; i++)
if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) {
rdesc[i] = 0x19;
rdesc[i + 2] = 0x29;
swap(rdesc[i + 3], rdesc[i + 1]);
}
return rdesc;
}
| 168,288
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dtls1_clear_queues(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
pqueue_free(s->d1->buffered_messages);
}
}
Commit Message:
CWE ID: CWE-399
|
static void dtls1_clear_queues(SSL *s)
{
dtls1_clear_received_buffer(s);
dtls1_clear_sent_buffer(s);
}
void dtls1_clear_received_buffer(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
}
void dtls1_clear_sent_buffer(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
pqueue_free(s->d1->buffered_messages);
}
}
| 165,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: bool asn1_write_GeneralString(struct asn1_data *data, const char *s)
{
asn1_push_tag(data, ASN1_GENERAL_STRING);
asn1_write_LDAPString(data, s);
asn1_pop_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
|
bool asn1_write_GeneralString(struct asn1_data *data, const char *s)
{
if (!asn1_push_tag(data, ASN1_GENERAL_STRING)) return false;
if (!asn1_write_LDAPString(data, s)) return false;
return asn1_pop_tag(data);
}
| 164,589
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain <= 0) {
/* 2.0.34: EOF is incorrect. We use 0 for
* errors and EOF, just like fileGetbuf,
* which is a simple fread() wrapper.
* TBB. Original bug report: Daniel Cowgill. */
return 0; /* NOT EOF */
}
rlen = remain;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
Commit Message: Fix invalid read in gdImageCreateFromTiffPtr()
tiff_invalid_read.tiff is corrupt, and causes an invalid read in
gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit
is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case,
dynamicGetbuf() is called with a negative dp->pos, but also positive buffer
overflows have to be handled, in which case 0 has to be returned (cf. commit
75e29a9).
Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create
the image, because the return value of TIFFReadRGBAImage() is not checked.
We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails.
This issue had been reported by Ibrahim El-Sayed to security@libgd.org.
CVE-2016-6911
CWE ID: CWE-125
|
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
if (dp->pos < 0 || dp->pos >= dp->realSize) {
return 0;
}
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain <= 0) {
return 0;
}
rlen = remain;
}
if (dp->pos + rlen > dp->realSize) {
rlen = dp->realSize - dp->pos;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
| 168,821
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 scsi_read_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
int n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) {
return;
}
}
DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->iov.iov_len);
n = r->iov.iov_len / 512;
r->sector += n;
r->sector_count -= n;
scsi_req_data(&r->req, r->iov.iov_len);
}
Commit Message: scsi-disk: commonize iovec creation between reads and writes
Also, consistently use qiov.size instead of iov.iov_len.
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
CWE ID: CWE-119
|
static void scsi_read_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
int n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) {
return;
}
}
DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->qiov.size);
n = r->qiov.size / 512;
r->sector += n;
r->sector_count -= n;
scsi_req_data(&r->req, r->qiov.size);
}
| 169,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: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), nullptr, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(DangerousPatternTLS().Get());
if (!dangerous_pattern) {
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"(\u0131[\u0300-\u0339]|)"
R"([ijl]\u0307)",
-1, US_INV),
0, status);
DangerousPatternTLS().Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Add a few more confusability mapping entries
U+0153(œ) => ce
U+00E6(æ), U+04D5 (ӕ) => ae
U+0499(ҙ) => 3
U+0525(ԥ) => n
Bug: 835554, 826019, 836885
Test: components_unittests --gtest_filter=*IDN*
Change-Id: Ic89211f70359d3d67cc25c1805b426b72cdb16ae
Reviewed-on: https://chromium-review.googlesource.com/1055894
Commit-Queue: Jungshik Shin <jshin@chromium.org>
Reviewed-by: Peter Kasting <pkasting@chromium.org>
Cr-Commit-Position: refs/heads/master@{#558928}
CWE ID:
|
bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), nullptr, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(DangerousPatternTLS().Get());
if (!dangerous_pattern) {
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"(\u0131[\u0300-\u0339]|)"
R"([ijl]\u0307)",
-1, US_INV),
0, status);
DangerousPatternTLS().Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 173,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: ExtensionTtsPlatformImpl* ExtensionTtsController::GetPlatformImpl() {
if (!platform_impl_)
platform_impl_ = ExtensionTtsPlatformImpl::GetInstance();
return platform_impl_;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
ExtensionTtsPlatformImpl* ExtensionTtsController::GetPlatformImpl() {
| 170,381
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void check_pointer_type_change(Notifier *notifier, void *data)
{
VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
int absolute = qemu_input_is_absolute();
if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, absolute, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_POINTER_TYPE_CHANGE);
vnc_unlock_output(vs);
vnc_flush(vs);
vnc_unlock_output(vs);
vnc_flush(vs);
}
vs->absolute = absolute;
}
Commit Message:
CWE ID: CWE-125
|
static void check_pointer_type_change(Notifier *notifier, void *data)
{
VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
int absolute = qemu_input_is_absolute();
if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, absolute, 0,
pixman_image_get_width(vs->vd->server),
pixman_image_get_height(vs->vd->server),
VNC_ENCODING_POINTER_TYPE_CHANGE);
vnc_unlock_output(vs);
vnc_flush(vs);
vnc_unlock_output(vs);
vnc_flush(vs);
}
vs->absolute = absolute;
}
| 165,458
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, char **buf, int *buf_type)
{
struct smb_rqst rqst;
int resp_buftype, rc = -EACCES;
struct smb2_read_plain_req *req = NULL;
struct smb2_read_rsp *rsp = NULL;
struct kvec iov[1];
struct kvec rsp_iov;
unsigned int total_len;
int flags = CIFS_LOG_ERROR;
struct cifs_ses *ses = io_parms->tcon->ses;
*nbytes = 0;
rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
if (rc)
return rc;
if (smb3_encryption_required(io_parms->tcon))
flags |= CIFS_TRANSFORM_REQ;
iov[0].iov_base = (char *)req;
iov[0].iov_len = total_len;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = 1;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
if (rc) {
if (rc != -ENODATA) {
cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
cifs_dbg(VFS, "Send error in read = %d\n", rc);
trace_smb3_read_err(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length,
rc);
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, 0);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return rc == -ENODATA ? 0 : rc;
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length);
*nbytes = le32_to_cpu(rsp->DataLength);
if ((*nbytes > CIFS_MAX_MSGSIZE) ||
(*nbytes > io_parms->length)) {
cifs_dbg(FYI, "bad length %d for count %d\n",
*nbytes, io_parms->length);
rc = -EIO;
*nbytes = 0;
}
if (*buf) {
memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
} else if (resp_buftype != CIFS_NO_BUFFER) {
*buf = rsp_iov.iov_base;
if (resp_buftype == CIFS_SMALL_BUFFER)
*buf_type = CIFS_SMALL_BUFFER;
else if (resp_buftype == CIFS_LARGE_BUFFER)
*buf_type = CIFS_LARGE_BUFFER;
}
return rc;
}
Commit Message: cifs: Fix use-after-free in SMB2_read
There is a KASAN use-after-free:
BUG: KASAN: use-after-free in SMB2_read+0x1136/0x1190
Read of size 8 at addr ffff8880b4e45e50 by task ln/1009
Should not release the 'req' because it will use in the trace.
Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging")
Signed-off-by: ZhangXiaoxu <zhangxiaoxu5@huawei.com>
Signed-off-by: Steve French <stfrench@microsoft.com>
CC: Stable <stable@vger.kernel.org> 4.18+
Reviewed-by: Pavel Shilovsky <pshilov@microsoft.com>
CWE ID: CWE-416
|
SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, char **buf, int *buf_type)
{
struct smb_rqst rqst;
int resp_buftype, rc = -EACCES;
struct smb2_read_plain_req *req = NULL;
struct smb2_read_rsp *rsp = NULL;
struct kvec iov[1];
struct kvec rsp_iov;
unsigned int total_len;
int flags = CIFS_LOG_ERROR;
struct cifs_ses *ses = io_parms->tcon->ses;
*nbytes = 0;
rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
if (rc)
return rc;
if (smb3_encryption_required(io_parms->tcon))
flags |= CIFS_TRANSFORM_REQ;
iov[0].iov_base = (char *)req;
iov[0].iov_len = total_len;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = 1;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
if (rc) {
if (rc != -ENODATA) {
cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
cifs_dbg(VFS, "Send error in read = %d\n", rc);
trace_smb3_read_err(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length,
rc);
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, 0);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return rc == -ENODATA ? 0 : rc;
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length);
cifs_small_buf_release(req);
*nbytes = le32_to_cpu(rsp->DataLength);
if ((*nbytes > CIFS_MAX_MSGSIZE) ||
(*nbytes > io_parms->length)) {
cifs_dbg(FYI, "bad length %d for count %d\n",
*nbytes, io_parms->length);
rc = -EIO;
*nbytes = 0;
}
if (*buf) {
memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
} else if (resp_buftype != CIFS_NO_BUFFER) {
*buf = rsp_iov.iov_base;
if (resp_buftype == CIFS_SMALL_BUFFER)
*buf_type = CIFS_SMALL_BUFFER;
else if (resp_buftype == CIFS_LARGE_BUFFER)
*buf_type = CIFS_LARGE_BUFFER;
}
return rc;
}
| 169,525
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool Block::IsInvisible() const
{
return bool(int(m_flags & 0x08) != 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
|
bool Block::IsInvisible() const
const Block::Frame& Block::GetFrame(int idx) const {
assert(idx >= 0);
assert(idx < m_frame_count);
const Frame& f = m_frames[idx];
assert(f.pos > 0);
assert(f.len > 0);
return f;
}
| 174,391
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: krb5_gss_export_sec_context(minor_status, context_handle, interprocess_token)
OM_uint32 *minor_status;
gss_ctx_id_t *context_handle;
gss_buffer_t interprocess_token;
{
krb5_context context = NULL;
krb5_error_code kret;
OM_uint32 retval;
size_t bufsize, blen;
krb5_gss_ctx_id_t ctx;
krb5_octet *obuffer, *obp;
/* Assume a tragic failure */
obuffer = (krb5_octet *) NULL;
retval = GSS_S_FAILURE;
*minor_status = 0;
ctx = (krb5_gss_ctx_id_t) *context_handle;
context = ctx->k5_context;
kret = krb5_gss_ser_init(context);
if (kret)
goto error_out;
/* Determine size needed for externalization of context */
bufsize = 0;
if ((kret = kg_ctx_size(context, (krb5_pointer) ctx,
&bufsize)))
goto error_out;
/* Allocate the buffer */
if ((obuffer = gssalloc_malloc(bufsize)) == NULL) {
kret = ENOMEM;
goto error_out;
}
obp = obuffer;
blen = bufsize;
/* Externalize the context */
if ((kret = kg_ctx_externalize(context,
(krb5_pointer) ctx, &obp, &blen)))
goto error_out;
/* Success! Return the buffer */
interprocess_token->length = bufsize - blen;
interprocess_token->value = obuffer;
*minor_status = 0;
retval = GSS_S_COMPLETE;
/* Now, clean up the context state */
(void)krb5_gss_delete_sec_context(minor_status, context_handle, NULL);
*context_handle = GSS_C_NO_CONTEXT;
return (GSS_S_COMPLETE);
error_out:
if (retval != GSS_S_COMPLETE)
if (kret != 0 && context != 0)
save_error_info((OM_uint32)kret, context);
if (obuffer && bufsize) {
memset(obuffer, 0, bufsize);
xfree(obuffer);
}
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID:
|
krb5_gss_export_sec_context(minor_status, context_handle, interprocess_token)
OM_uint32 *minor_status;
gss_ctx_id_t *context_handle;
gss_buffer_t interprocess_token;
{
krb5_context context = NULL;
krb5_error_code kret;
OM_uint32 retval;
size_t bufsize, blen;
krb5_gss_ctx_id_t ctx;
krb5_octet *obuffer, *obp;
/* Assume a tragic failure */
obuffer = (krb5_octet *) NULL;
retval = GSS_S_FAILURE;
*minor_status = 0;
ctx = (krb5_gss_ctx_id_t) *context_handle;
if (ctx->terminated) {
*minor_status = KG_CTX_INCOMPLETE;
return (GSS_S_NO_CONTEXT);
}
context = ctx->k5_context;
kret = krb5_gss_ser_init(context);
if (kret)
goto error_out;
/* Determine size needed for externalization of context */
bufsize = 0;
if ((kret = kg_ctx_size(context, (krb5_pointer) ctx,
&bufsize)))
goto error_out;
/* Allocate the buffer */
if ((obuffer = gssalloc_malloc(bufsize)) == NULL) {
kret = ENOMEM;
goto error_out;
}
obp = obuffer;
blen = bufsize;
/* Externalize the context */
if ((kret = kg_ctx_externalize(context,
(krb5_pointer) ctx, &obp, &blen)))
goto error_out;
/* Success! Return the buffer */
interprocess_token->length = bufsize - blen;
interprocess_token->value = obuffer;
*minor_status = 0;
retval = GSS_S_COMPLETE;
/* Now, clean up the context state */
(void)krb5_gss_delete_sec_context(minor_status, context_handle, NULL);
*context_handle = GSS_C_NO_CONTEXT;
return (GSS_S_COMPLETE);
error_out:
if (retval != GSS_S_COMPLETE)
if (kret != 0 && context != 0)
save_error_info((OM_uint32)kret, context);
if (obuffer && bufsize) {
memset(obuffer, 0, bufsize);
xfree(obuffer);
}
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
| 166,814
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SProcXFixesChangeSaveSet(ClientPtr client)
{
REQUEST(xXFixesChangeSaveSetReq);
swaps(&stuff->length);
swapl(&stuff->window);
}
Commit Message:
CWE ID: CWE-20
|
SProcXFixesChangeSaveSet(ClientPtr client)
{
REQUEST(xXFixesChangeSaveSetReq);
REQUEST_SIZE_MATCH(xXFixesChangeSaveSetReq);
swaps(&stuff->length);
swapl(&stuff->window);
}
| 165,443
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: AutoFillQueryXmlParser::AutoFillQueryXmlParser(
std::vector<AutoFillFieldType>* field_types,
UploadRequired* upload_required)
: field_types_(field_types),
upload_required_(upload_required) {
DCHECK(upload_required_);
}
Commit Message: Add support for autofill server experiments
BUG=none
TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId
Review URL: http://codereview.chromium.org/6260027
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
AutoFillQueryXmlParser::AutoFillQueryXmlParser(
std::vector<AutoFillFieldType>* field_types,
UploadRequired* upload_required,
std::string* experiment_id)
: field_types_(field_types),
upload_required_(upload_required),
experiment_id_(experiment_id) {
DCHECK(upload_required_);
DCHECK(experiment_id_);
}
| 170,653
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int wdm_post_reset(struct usb_interface *intf)
{
struct wdm_device *desc = wdm_find_device(intf);
int rv;
clear_bit(WDM_RESETTING, &desc->flags);
rv = recover_from_urb_loss(desc);
mutex_unlock(&desc->wlock);
mutex_unlock(&desc->rlock);
return 0;
}
Commit Message: USB: cdc-wdm: fix buffer overflow
The buffer for responses must not overflow.
If this would happen, set a flag, drop the data and return
an error after user space has read all remaining data.
Signed-off-by: Oliver Neukum <oliver@neukum.org>
CC: stable@kernel.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID: CWE-119
|
static int wdm_post_reset(struct usb_interface *intf)
{
struct wdm_device *desc = wdm_find_device(intf);
int rv;
clear_bit(WDM_OVERFLOW, &desc->flags);
clear_bit(WDM_RESETTING, &desc->flags);
rv = recover_from_urb_loss(desc);
mutex_unlock(&desc->wlock);
mutex_unlock(&desc->rlock);
return 0;
}
| 166,104
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
Commit Message:
CWE ID: CWE-399
|
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
if (SeekBlob(image,offset,SEEK_CUR) < 0)
break;
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 168,853
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: AppModalDialog::~AppModalDialog() {
}
Commit Message: Fix a Windows crash bug with javascript alerts from extension popups.
BUG=137707
Review URL: https://chromiumcodereview.appspot.com/10828423
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
AppModalDialog::~AppModalDialog() {
CompleteDialog();
}
| 170,755
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: stringprep_strerror (Stringprep_rc rc)
{
const char *p;
bindtextdomain (PACKAGE, LOCALEDIR);
switch (rc)
{
case STRINGPREP_OK:
p = _("Success");
break;
case STRINGPREP_CONTAINS_UNASSIGNED:
p = _("Forbidden unassigned code points in input");
break;
case STRINGPREP_CONTAINS_PROHIBITED:
p = _("Prohibited code points in input");
break;
case STRINGPREP_BIDI_BOTH_L_AND_RAL:
p = _("Conflicting bidirectional properties in input");
break;
case STRINGPREP_BIDI_LEADTRAIL_NOT_RAL:
p = _("Malformed bidirectional string");
break;
case STRINGPREP_BIDI_CONTAINS_PROHIBITED:
p = _("Prohibited bidirectional code points in input");
break;
case STRINGPREP_TOO_SMALL_BUFFER:
p = _("Output would exceed the buffer space provided");
break;
case STRINGPREP_PROFILE_ERROR:
p = _("Error in stringprep profile definition");
break;
case STRINGPREP_FLAG_ERROR:
p = _("Flag conflict with profile");
break;
case STRINGPREP_UNKNOWN_PROFILE:
case STRINGPREP_UNKNOWN_PROFILE:
p = _("Unknown profile");
break;
case STRINGPREP_NFKC_FAILED:
p = _("Unicode normalization failed (internal error)");
break;
default:
p = _("Unknown error");
break;
}
return p;
}
Commit Message:
CWE ID: CWE-119
|
stringprep_strerror (Stringprep_rc rc)
{
const char *p;
bindtextdomain (PACKAGE, LOCALEDIR);
switch (rc)
{
case STRINGPREP_OK:
p = _("Success");
break;
case STRINGPREP_CONTAINS_UNASSIGNED:
p = _("Forbidden unassigned code points in input");
break;
case STRINGPREP_CONTAINS_PROHIBITED:
p = _("Prohibited code points in input");
break;
case STRINGPREP_BIDI_BOTH_L_AND_RAL:
p = _("Conflicting bidirectional properties in input");
break;
case STRINGPREP_BIDI_LEADTRAIL_NOT_RAL:
p = _("Malformed bidirectional string");
break;
case STRINGPREP_BIDI_CONTAINS_PROHIBITED:
p = _("Prohibited bidirectional code points in input");
break;
case STRINGPREP_TOO_SMALL_BUFFER:
p = _("Output would exceed the buffer space provided");
break;
case STRINGPREP_PROFILE_ERROR:
p = _("Error in stringprep profile definition");
break;
case STRINGPREP_FLAG_ERROR:
p = _("Flag conflict with profile");
break;
case STRINGPREP_UNKNOWN_PROFILE:
case STRINGPREP_UNKNOWN_PROFILE:
p = _("Unknown profile");
break;
case STRINGPREP_ICONV_ERROR:
p = _("Could not convert string in locale encoding.");
break;
case STRINGPREP_NFKC_FAILED:
p = _("Unicode normalization failed (internal error)");
break;
default:
p = _("Unknown error");
break;
}
return p;
}
| 164,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: psf_fwrite (const void *ptr, sf_count_t bytes, sf_count_t items, SF_PRIVATE *psf)
{ sf_count_t total = 0 ;
ssize_t count ;
if (psf->virtual_io)
return psf->vio.write (ptr, bytes*items, psf->vio_user_data) / bytes ;
items *= bytes ;
/* Do this check after the multiplication above. */
if (items <= 0)
return 0 ;
while (items > 0)
{ /* Break the writes down to a sensible size. */
count = (items > SENSIBLE_SIZE) ? SENSIBLE_SIZE : items ;
count = write (psf->file.filedes, ((const char*) ptr) + total, count) ;
if (count == -1)
{ if (errno == EINTR)
continue ;
psf_log_syserr (psf, errno) ;
break ;
} ;
if (count == 0)
break ;
total += count ;
items -= count ;
} ;
if (psf->is_pipe)
psf->pipeoffset += total ;
return total / bytes ;
} /* psf_fwrite */
Commit Message: src/file_io.c : Prevent potential divide-by-zero.
Closes: https://github.com/erikd/libsndfile/issues/92
CWE ID: CWE-189
|
psf_fwrite (const void *ptr, sf_count_t bytes, sf_count_t items, SF_PRIVATE *psf)
{ sf_count_t total = 0 ;
ssize_t count ;
if (bytes == 0 || items == 0)
return 0 ;
if (psf->virtual_io)
return psf->vio.write (ptr, bytes*items, psf->vio_user_data) / bytes ;
items *= bytes ;
/* Do this check after the multiplication above. */
if (items <= 0)
return 0 ;
while (items > 0)
{ /* Break the writes down to a sensible size. */
count = (items > SENSIBLE_SIZE) ? SENSIBLE_SIZE : items ;
count = write (psf->file.filedes, ((const char*) ptr) + total, count) ;
if (count == -1)
{ if (errno == EINTR)
continue ;
psf_log_syserr (psf, errno) ;
break ;
} ;
if (count == 0)
break ;
total += count ;
items -= count ;
} ;
if (psf->is_pipe)
psf->pipeoffset += total ;
return total / bytes ;
} /* psf_fwrite */
| 166,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: ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
int error;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(inode, bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
ext4_xattr_cache_insert(ext4_mb_cache, bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
int error;
struct mb2_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(inode, bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
ext4_xattr_cache_insert(ext4_mb_cache, bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
| 169,989
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool AppCacheBackendImpl::SelectCacheForSharedWorker(
int host_id, int64 appcache_id) {
AppCacheHost* host = GetHost(host_id);
if (!host || host->was_select_cache_called())
return false;
host->SelectCacheForSharedWorker(appcache_id);
return true;
}
Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer.
BUG=551044
Review URL: https://codereview.chromium.org/1418783005
Cr-Commit-Position: refs/heads/master@{#358815}
CWE ID:
|
bool AppCacheBackendImpl::SelectCacheForSharedWorker(
int host_id, int64 appcache_id) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
return host->SelectCacheForSharedWorker(appcache_id);
}
| 171,737
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
CWE ID: CWE-20
|
tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)
return res;
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
| 168,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: static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */
{
int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC);
while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) {
spl_filesystem_file_free_line(intern TSRMLS_CC);
ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC);
}
return ret;
}
/* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */
{
int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC);
while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) {
spl_filesystem_file_free_line(intern TSRMLS_CC);
ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC);
}
return ret;
}
/* }}} */
| 167,078
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ProcRenderSetPictureFilter(ClientPtr client)
{
REQUEST(xRenderSetPictureFilterReq);
PicturePtr pPicture;
int result;
xFixed *params;
int nparams;
char *name;
REQUEST_AT_LEAST_SIZE(xRenderSetPictureFilterReq);
VERIFY_PICTURE(pPicture, stuff->picture, client, DixSetAttrAccess);
name = (char *) (stuff + 1);
params = (xFixed *) (name + pad_to_int32(stuff->nbytes));
nparams = ((xFixed *) stuff + client->req_len) - params;
result = SetPictureFilter(pPicture, name, stuff->nbytes, params, nparams);
return result;
}
Commit Message:
CWE ID: CWE-20
|
ProcRenderSetPictureFilter(ClientPtr client)
{
REQUEST(xRenderSetPictureFilterReq);
PicturePtr pPicture;
int result;
xFixed *params;
int nparams;
char *name;
REQUEST_AT_LEAST_SIZE(xRenderSetPictureFilterReq);
VERIFY_PICTURE(pPicture, stuff->picture, client, DixSetAttrAccess);
name = (char *) (stuff + 1);
params = (xFixed *) (name + pad_to_int32(stuff->nbytes));
nparams = ((xFixed *) stuff + client->req_len) - params;
if (nparams < 0)
return BadLength;
result = SetPictureFilter(pPicture, name, stuff->nbytes, params, nparams);
return result;
}
| 165,438
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
ssize_t size, void *private)
{
ext4_io_end_t *io_end = iocb->private;
struct workqueue_struct *wq;
/* if not async direct IO or dio with 0 bytes write, just return */
if (!io_end || !size)
return;
ext_debug("ext4_end_io_dio(): io_end 0x%p"
"for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
iocb->private, io_end->inode->i_ino, iocb, offset,
size);
/* if not aio dio with unwritten extents, just free io and return */
if (io_end->flag != EXT4_IO_UNWRITTEN){
ext4_free_io_end(io_end);
iocb->private = NULL;
return;
}
io_end->offset = offset;
io_end->size = size;
wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
/* queue the work to convert unwritten extents to written */
queue_work(wq, &io_end->work);
/* Add the io_end to per-inode completed aio dio list*/
list_add_tail(&io_end->list,
&EXT4_I(io_end->inode)->i_completed_io_list);
iocb->private = NULL;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
ssize_t size, void *private)
{
ext4_io_end_t *io_end = iocb->private;
struct workqueue_struct *wq;
unsigned long flags;
struct ext4_inode_info *ei;
/* if not async direct IO or dio with 0 bytes write, just return */
if (!io_end || !size)
return;
ext_debug("ext4_end_io_dio(): io_end 0x%p"
"for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
iocb->private, io_end->inode->i_ino, iocb, offset,
size);
/* if not aio dio with unwritten extents, just free io and return */
if (io_end->flag != EXT4_IO_UNWRITTEN){
ext4_free_io_end(io_end);
iocb->private = NULL;
return;
}
io_end->offset = offset;
io_end->size = size;
io_end->flag = EXT4_IO_UNWRITTEN;
wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
/* queue the work to convert unwritten extents to written */
queue_work(wq, &io_end->work);
/* Add the io_end to per-inode completed aio dio list*/
ei = EXT4_I(io_end->inode);
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
list_add_tail(&io_end->list, &ei->i_completed_io_list);
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
iocb->private = NULL;
}
| 167,540
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
assert((cc%(4*stride))==0);
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 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
|
horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc32",
"%s", "cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
return 1;
}
| 166,883
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 check_request_for_cacheability(struct stream *s, struct channel *chn)
{
struct http_txn *txn = s->txn;
char *p1, *p2;
char *cur_ptr, *cur_end, *cur_next;
int pragma_found;
int cc_found;
int cur_idx;
if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
return; /* nothing more to do here */
cur_idx = 0;
pragma_found = cc_found = 0;
cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) {
struct hdr_idx_elem *cur_hdr;
int val;
cur_hdr = &txn->hdr_idx.v[cur_idx];
cur_ptr = cur_next;
cur_end = cur_ptr + cur_hdr->len;
cur_next = cur_end + cur_hdr->cr + 1;
/* We have one full header between cur_ptr and cur_end, and the
* next header starts at cur_next.
*/
val = http_header_match2(cur_ptr, cur_end, "Pragma", 6);
if (val) {
if ((cur_end - (cur_ptr + val) >= 8) &&
strncasecmp(cur_ptr + val, "no-cache", 8) == 0) {
pragma_found = 1;
continue;
}
}
val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13);
if (!val)
continue;
p2 = p1;
while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2))
p2++;
/* we have a complete value between p1 and p2. We don't check the
* values after max-age, max-stale nor min-fresh, we simply don't
* use the cache when they're specified.
*/
if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) ||
((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) {
txn->flags |= TX_CACHE_IGNORE;
continue;
}
if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) {
txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
continue;
}
}
/* RFC7234#5.4:
* When the Cache-Control header field is also present and
* understood in a request, Pragma is ignored.
* When the Cache-Control header field is not present in a
* request, caches MUST consider the no-cache request
* pragma-directive as having the same effect as if
* "Cache-Control: no-cache" were present.
*/
if (!cc_found && pragma_found)
txn->flags |= TX_CACHE_IGNORE;
}
Commit Message:
CWE ID: CWE-200
|
void check_request_for_cacheability(struct stream *s, struct channel *chn)
{
struct http_txn *txn = s->txn;
char *p1, *p2;
char *cur_ptr, *cur_end, *cur_next;
int pragma_found;
int cc_found;
int cur_idx;
if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
return; /* nothing more to do here */
cur_idx = 0;
pragma_found = cc_found = 0;
cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) {
struct hdr_idx_elem *cur_hdr;
int val;
cur_hdr = &txn->hdr_idx.v[cur_idx];
cur_ptr = cur_next;
cur_end = cur_ptr + cur_hdr->len;
cur_next = cur_end + cur_hdr->cr + 1;
/* We have one full header between cur_ptr and cur_end, and the
* next header starts at cur_next.
*/
val = http_header_match2(cur_ptr, cur_end, "Pragma", 6);
if (val) {
if ((cur_end - (cur_ptr + val) >= 8) &&
strncasecmp(cur_ptr + val, "no-cache", 8) == 0) {
pragma_found = 1;
continue;
}
}
/* Don't use the cache and don't try to store if we found the
* Authorization header */
val = http_header_match2(cur_ptr, cur_end, "Authorization", 13);
if (val) {
txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
txn->flags |= TX_CACHE_IGNORE;
continue;
}
val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13);
if (!val)
continue;
p2 = p1;
while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2))
p2++;
/* we have a complete value between p1 and p2. We don't check the
* values after max-age, max-stale nor min-fresh, we simply don't
* use the cache when they're specified.
*/
if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) ||
((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) {
txn->flags |= TX_CACHE_IGNORE;
continue;
}
if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) {
txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
continue;
}
}
/* RFC7234#5.4:
* When the Cache-Control header field is also present and
* understood in a request, Pragma is ignored.
* When the Cache-Control header field is not present in a
* request, caches MUST consider the no-cache request
* pragma-directive as having the same effect as if
* "Cache-Control: no-cache" were present.
*/
if (!cc_found && pragma_found)
txn->flags |= TX_CACHE_IGNORE;
}
| 164,841
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext)
{
if (!executionContext)
return;
v8::HandleScope handleScope(toIsolate(executionContext));
v8::Local<v8::Context> v8Context = toV8Context(executionContext, world());
if (v8Context.IsEmpty())
return;
ScriptState* scriptState = ScriptState::from(v8Context);
if (!scriptState->contextIsValid())
return;
if (executionContext->isDocument() && !toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) {
clearListenerObject();
return;
}
if (hasExistingListenerObject())
return;
ASSERT(executionContext->isDocument());
ScriptState::Scope scope(scriptState);
String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName);
String code = "(function() {"
"with (this[2]) {"
"with (this[1]) {"
"with (this[0]) {"
"return function(" + m_eventParameterName + ") {" +
listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler.
"};"
"}}}})";
v8::Handle<v8::String> codeExternalString = v8String(isolate(), code);
v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position);
if (result.IsEmpty())
return;
ASSERT(result->IsFunction());
v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>();
HTMLFormElement* formElement = 0;
if (m_node && m_node->isHTMLElement())
formElement = toHTMLElement(m_node)->formOwner();
v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState);
v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState);
v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState);
v8::Local<v8::Object> thisObject = v8::Object::New(isolate());
if (thisObject.IsEmpty())
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper))
return;
v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate());
if (innerValue.IsEmpty() || !innerValue->IsFunction())
return;
v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>();
v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString);
ASSERT(!toStringFunction.IsEmpty());
String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}";
V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString));
wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction);
wrappedFunction->SetName(v8String(isolate(), m_functionName));
setListenerObject(wrappedFunction);
}
Commit Message: Turn a bunch of ASSERTs into graceful failures when compiling listeners
BUG=456192
R=yangguo@chromium.org
Review URL: https://codereview.chromium.org/906193002
git-svn-id: svn://svn.chromium.org/blink/trunk@189796 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-17
|
void V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext)
{
if (!executionContext)
return;
v8::HandleScope handleScope(toIsolate(executionContext));
v8::Local<v8::Context> v8Context = toV8Context(executionContext, world());
if (v8Context.IsEmpty())
return;
ScriptState* scriptState = ScriptState::from(v8Context);
if (!scriptState->contextIsValid())
return;
if (!executionContext->isDocument())
return;
if (!toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) {
clearListenerObject();
return;
}
if (hasExistingListenerObject())
return;
ScriptState::Scope scope(scriptState);
String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName);
String code = "(function() {"
"with (this[2]) {"
"with (this[1]) {"
"with (this[0]) {"
"return function(" + m_eventParameterName + ") {" +
listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler.
"};"
"}}}})";
v8::Handle<v8::String> codeExternalString = v8String(isolate(), code);
v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position);
if (result.IsEmpty())
return;
if (!result->IsFunction())
return;
v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>();
HTMLFormElement* formElement = 0;
if (m_node && m_node->isHTMLElement())
formElement = toHTMLElement(m_node)->formOwner();
v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState);
v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState);
v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState);
v8::Local<v8::Object> thisObject = v8::Object::New(isolate());
if (thisObject.IsEmpty())
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper))
return;
v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate());
if (innerValue.IsEmpty() || !innerValue->IsFunction())
return;
v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>();
v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString);
ASSERT(!toStringFunction.IsEmpty());
String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}";
V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString));
wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction);
wrappedFunction->SetName(v8String(isolate(), m_functionName));
setListenerObject(wrappedFunction);
}
| 172,025
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: DOMWindow* CreateWindow(const String& url_string,
const AtomicString& frame_name,
const String& window_features_string,
LocalDOMWindow& calling_window,
LocalFrame& first_frame,
LocalFrame& opener_frame,
ExceptionState& exception_state) {
LocalFrame* active_frame = calling_window.GetFrame();
DCHECK(active_frame);
KURL completed_url = url_string.IsEmpty()
? KURL(kParsedURLString, g_empty_string)
: first_frame.GetDocument()->CompleteURL(url_string);
if (!completed_url.IsEmpty() && !completed_url.IsValid()) {
UseCounter::Count(active_frame, WebFeature::kWindowOpenWithInvalidURL);
exception_state.ThrowDOMException(
kSyntaxError, "Unable to open a window with invalid URL '" +
completed_url.GetString() + "'.\n");
return nullptr;
}
WebWindowFeatures window_features =
GetWindowFeaturesFromString(window_features_string);
FrameLoadRequest frame_request(calling_window.document(),
ResourceRequest(completed_url), frame_name);
frame_request.SetShouldSetOpener(window_features.noopener ? kNeverSetOpener
: kMaybeSetOpener);
frame_request.GetResourceRequest().SetFrameType(
WebURLRequest::kFrameTypeAuxiliary);
frame_request.GetResourceRequest().SetRequestorOrigin(
SecurityOrigin::Create(active_frame->GetDocument()->Url()));
frame_request.GetResourceRequest().SetHTTPReferrer(
SecurityPolicy::GenerateReferrer(
active_frame->GetDocument()->GetReferrerPolicy(), completed_url,
active_frame->GetDocument()->OutgoingReferrer()));
bool has_user_gesture = UserGestureIndicator::ProcessingUserGesture();
bool created;
Frame* new_frame = CreateWindowHelper(
opener_frame, *active_frame, opener_frame, frame_request, window_features,
kNavigationPolicyIgnore, created);
if (!new_frame)
return nullptr;
if (new_frame->DomWindow()->IsInsecureScriptAccess(calling_window,
completed_url))
return window_features.noopener ? nullptr : new_frame->DomWindow();
if (created) {
FrameLoadRequest request(calling_window.document(),
ResourceRequest(completed_url));
request.GetResourceRequest().SetHasUserGesture(has_user_gesture);
new_frame->Navigate(request);
} else if (!url_string.IsEmpty()) {
new_frame->Navigate(*calling_window.document(), completed_url, false,
has_user_gesture ? UserGestureStatus::kActive
: UserGestureStatus::kNone);
}
return window_features.noopener ? nullptr : new_frame->DomWindow();
}
Commit Message: CSP now prevents opening javascript url windows when they're not allowed
spec: https://html.spec.whatwg.org/#navigate
which leads to: https://w3c.github.io/webappsec-csp/#should-block-navigation-request
Bug: 756040
Change-Id: I5fd62ebfb6fe1d767694b0ed6cf427c8ea95994a
Reviewed-on: https://chromium-review.googlesource.com/632580
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#497338}
CWE ID:
|
DOMWindow* CreateWindow(const String& url_string,
const AtomicString& frame_name,
const String& window_features_string,
LocalDOMWindow& calling_window,
LocalFrame& first_frame,
LocalFrame& opener_frame,
ExceptionState& exception_state) {
LocalFrame* active_frame = calling_window.GetFrame();
DCHECK(active_frame);
KURL completed_url = url_string.IsEmpty()
? KURL(kParsedURLString, g_empty_string)
: first_frame.GetDocument()->CompleteURL(url_string);
if (!completed_url.IsEmpty() && !completed_url.IsValid()) {
UseCounter::Count(active_frame, WebFeature::kWindowOpenWithInvalidURL);
exception_state.ThrowDOMException(
kSyntaxError, "Unable to open a window with invalid URL '" +
completed_url.GetString() + "'.\n");
return nullptr;
}
if (completed_url.ProtocolIsJavaScript() &&
opener_frame.GetDocument()->GetContentSecurityPolicy() &&
!ContentSecurityPolicy::ShouldBypassMainWorld(
opener_frame.GetDocument())) {
const int kJavascriptSchemeLength = sizeof("javascript:") - 1;
String script_source = DecodeURLEscapeSequences(completed_url.GetString())
.Substring(kJavascriptSchemeLength);
if (!opener_frame.GetDocument()
->GetContentSecurityPolicy()
->AllowJavaScriptURLs(nullptr, script_source,
opener_frame.GetDocument()->Url(),
OrdinalNumber())) {
return nullptr;
}
}
WebWindowFeatures window_features =
GetWindowFeaturesFromString(window_features_string);
FrameLoadRequest frame_request(calling_window.document(),
ResourceRequest(completed_url), frame_name);
frame_request.SetShouldSetOpener(window_features.noopener ? kNeverSetOpener
: kMaybeSetOpener);
frame_request.GetResourceRequest().SetFrameType(
WebURLRequest::kFrameTypeAuxiliary);
frame_request.GetResourceRequest().SetRequestorOrigin(
SecurityOrigin::Create(active_frame->GetDocument()->Url()));
frame_request.GetResourceRequest().SetHTTPReferrer(
SecurityPolicy::GenerateReferrer(
active_frame->GetDocument()->GetReferrerPolicy(), completed_url,
active_frame->GetDocument()->OutgoingReferrer()));
bool has_user_gesture = UserGestureIndicator::ProcessingUserGesture();
bool created;
Frame* new_frame = CreateWindowHelper(
opener_frame, *active_frame, opener_frame, frame_request, window_features,
kNavigationPolicyIgnore, created);
if (!new_frame)
return nullptr;
if (new_frame->DomWindow()->IsInsecureScriptAccess(calling_window,
completed_url))
return window_features.noopener ? nullptr : new_frame->DomWindow();
if (created) {
FrameLoadRequest request(calling_window.document(),
ResourceRequest(completed_url));
request.GetResourceRequest().SetHasUserGesture(has_user_gesture);
new_frame->Navigate(request);
} else if (!url_string.IsEmpty()) {
new_frame->Navigate(*calling_window.document(), completed_url, false,
has_user_gesture ? UserGestureStatus::kActive
: UserGestureStatus::kNone);
}
return window_features.noopener ? nullptr : new_frame->DomWindow();
}
| 172,953
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: WebContext* WebContext::FromBrowserContext(oxide::BrowserContext* context) {
BrowserContextDelegate* delegate =
static_cast<BrowserContextDelegate*>(context->GetDelegate());
if (!delegate) {
return nullptr;
}
return delegate->context();
}
Commit Message:
CWE ID: CWE-20
|
WebContext* WebContext::FromBrowserContext(oxide::BrowserContext* context) {
WebContext* WebContext::FromBrowserContext(BrowserContext* context) {
BrowserContextDelegate* delegate =
static_cast<BrowserContextDelegate*>(context->GetDelegate());
if (!delegate) {
return nullptr;
}
return delegate->context();
}
| 165,411
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE omx_vdec::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
unsigned nPortIndex = 0;
if (dynamic_buf_mode) {
private_handle_t *handle = NULL;
struct VideoDecoderOutputMetaData *meta;
unsigned int nPortIndex = 0;
if (!buffer || !buffer->pBuffer) {
DEBUG_PRINT_ERROR("%s: invalid params: %p", __FUNCTION__, buffer);
return OMX_ErrorBadParameter;
}
meta = (struct VideoDecoderOutputMetaData *)buffer->pBuffer;
handle = (private_handle_t *)meta->pHandle;
DEBUG_PRINT_LOW("FTB: metabuf: %p buftype: %d bufhndl: %p ", meta, meta->eType, meta->pHandle);
if (!handle) {
DEBUG_PRINT_ERROR("FTB: Error: IL client passed an invalid buf handle - %p", handle);
return OMX_ErrorBadParameter;
}
nPortIndex = buffer-((OMX_BUFFERHEADERTYPE *)client_buffers.get_il_buf_hdr());
drv_ctx.ptr_outputbuffer[nPortIndex].pmem_fd = handle->fd;
drv_ctx.ptr_outputbuffer[nPortIndex].bufferaddr = (OMX_U8*) buffer;
native_buffer[nPortIndex].privatehandle = handle;
native_buffer[nPortIndex].nativehandle = handle;
buffer->nFilledLen = 0;
buffer->nAllocLen = handle->size;
}
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("FTB in Invalid State");
return OMX_ErrorInvalidState;
}
if (!m_out_bEnabled) {
DEBUG_PRINT_ERROR("ERROR:FTB incorrect state operation, output port is disabled.");
return OMX_ErrorIncorrectStateOperation;
}
nPortIndex = buffer - client_buffers.get_il_buf_hdr();
if (buffer == NULL ||
(nPortIndex >= drv_ctx.op_buf.actualcount)) {
DEBUG_PRINT_ERROR("FTB: ERROR: invalid buffer index, nPortIndex %u bufCount %u",
nPortIndex, drv_ctx.op_buf.actualcount);
return OMX_ErrorBadParameter;
}
if (buffer->nOutputPortIndex != OMX_CORE_OUTPUT_PORT_INDEX) {
DEBUG_PRINT_ERROR("ERROR:FTB invalid port in header %u", (unsigned int)buffer->nOutputPortIndex);
return OMX_ErrorBadPortIndex;
}
DEBUG_PRINT_LOW("[FTB] bufhdr = %p, bufhdr->pBuffer = %p", buffer, buffer->pBuffer);
post_event((unsigned long) hComp, (unsigned long)buffer, m_fill_output_msg);
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID:
|
OMX_ERRORTYPE omx_vdec::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
if (m_state != OMX_StateExecuting &&
m_state != OMX_StatePause &&
m_state != OMX_StateIdle) {
DEBUG_PRINT_ERROR("FTB in Invalid State");
return OMX_ErrorInvalidState;
}
if (!m_out_bEnabled) {
DEBUG_PRINT_ERROR("ERROR:FTB incorrect state operation, output port is disabled.");
return OMX_ErrorIncorrectStateOperation;
}
unsigned nPortIndex = 0;
if (dynamic_buf_mode) {
private_handle_t *handle = NULL;
struct VideoDecoderOutputMetaData *meta;
unsigned int nPortIndex = 0;
if (!buffer || !buffer->pBuffer) {
DEBUG_PRINT_ERROR("%s: invalid params: %p", __FUNCTION__, buffer);
return OMX_ErrorBadParameter;
}
meta = (struct VideoDecoderOutputMetaData *)buffer->pBuffer;
handle = (private_handle_t *)meta->pHandle;
DEBUG_PRINT_LOW("FTB: metabuf: %p buftype: %d bufhndl: %p ", meta, meta->eType, meta->pHandle);
if (!handle) {
DEBUG_PRINT_ERROR("FTB: Error: IL client passed an invalid buf handle - %p", handle);
return OMX_ErrorBadParameter;
}
nPortIndex = buffer-((OMX_BUFFERHEADERTYPE *)client_buffers.get_il_buf_hdr());
drv_ctx.ptr_outputbuffer[nPortIndex].pmem_fd = handle->fd;
drv_ctx.ptr_outputbuffer[nPortIndex].bufferaddr = (OMX_U8*) buffer;
native_buffer[nPortIndex].privatehandle = handle;
native_buffer[nPortIndex].nativehandle = handle;
buffer->nFilledLen = 0;
buffer->nAllocLen = handle->size;
}
nPortIndex = buffer - client_buffers.get_il_buf_hdr();
if (buffer == NULL ||
(nPortIndex >= drv_ctx.op_buf.actualcount)) {
DEBUG_PRINT_ERROR("FTB: ERROR: invalid buffer index, nPortIndex %u bufCount %u",
nPortIndex, drv_ctx.op_buf.actualcount);
return OMX_ErrorBadParameter;
}
if (buffer->nOutputPortIndex != OMX_CORE_OUTPUT_PORT_INDEX) {
DEBUG_PRINT_ERROR("ERROR:FTB invalid port in header %u", (unsigned int)buffer->nOutputPortIndex);
return OMX_ErrorBadPortIndex;
}
DEBUG_PRINT_LOW("[FTB] bufhdr = %p, bufhdr->pBuffer = %p", buffer, buffer->pBuffer);
post_event((unsigned long) hComp, (unsigned long)buffer, m_fill_output_msg);
return OMX_ErrorNone;
}
| 173,751
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SetExtendedFileAttribute(const char* path,
const char* name,
const char* value,
size_t value_size,
int flags) {
//// On Chrome OS, there is no component that can validate these extended
//// attributes so there is no need to set them.
base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
int result = setxattr(path, name, value, value_size, flags);
if (result) {
DPLOG(ERROR) << "Could not set extended attribute " << name << " on file "
<< path;
return false;
}
return true;
}
Commit Message: Disable setxattr calls from quarantine subsystem on Chrome OS.
BUG=733943
Change-Id: I6e743469a8dc91536e180ecf4ff0df0cf427037c
Reviewed-on: https://chromium-review.googlesource.com/c/1380571
Commit-Queue: Will Harris <wfh@chromium.org>
Reviewed-by: Raymes Khoury <raymes@chromium.org>
Reviewed-by: David Trainor <dtrainor@chromium.org>
Reviewed-by: Thiemo Nagel <tnagel@chromium.org>
Cr-Commit-Position: refs/heads/master@{#617961}
CWE ID: CWE-200
|
bool SetExtendedFileAttribute(const char* path,
const char* name,
const char* value,
size_t value_size,
int flags) {
//// On Chrome OS, there is no component that can validate these extended
//// attributes so there is no need to set them.
#if !defined(OS_CHROMEOS)
base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
int result = setxattr(path, name, value, value_size, flags);
if (result) {
DPLOG(ERROR) << "Could not set extended attribute " << name << " on file "
<< path;
return false;
}
#endif // !defined(OS_CHROMEOS)
return true;
}
| 173,117
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __f2fs_set_acl(struct inode *inode, int type,
struct posix_acl *acl, struct page *ipage)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
set_acl_inode(inode, inode->i_mode);
if (error == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = f2fs_acl_to_disk(acl, &size);
if (IS_ERR(value)) {
clear_inode_flag(inode, FI_ACL_MODE);
return (int)PTR_ERR(value);
}
}
error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
clear_inode_flag(inode, FI_ACL_MODE);
return error;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com>
CWE ID: CWE-285
|
static int __f2fs_set_acl(struct inode *inode, int type,
struct posix_acl *acl, struct page *ipage)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (error)
return error;
set_acl_inode(inode, inode->i_mode);
}
break;
case ACL_TYPE_DEFAULT:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = f2fs_acl_to_disk(acl, &size);
if (IS_ERR(value)) {
clear_inode_flag(inode, FI_ACL_MODE);
return (int)PTR_ERR(value);
}
}
error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
clear_inode_flag(inode, FI_ACL_MODE);
return error;
}
| 166,971
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(render_frame_host);
if (delegate_)
delegate_->WillRunBeforeUnloadConfirm();
bool suppress_this_message =
!rfhi->is_active() ||
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (suppress_this_message) {
rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
return;
}
is_showing_before_unload_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunBeforeUnloadDialog(
this, is_reload,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
false));
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20
|
void WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (IsFullscreenForCurrentTab())
ExitFullscreen(true);
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(render_frame_host);
if (delegate_)
delegate_->WillRunBeforeUnloadConfirm();
bool suppress_this_message =
!rfhi->is_active() ||
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (suppress_this_message) {
rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
return;
}
is_showing_before_unload_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunBeforeUnloadDialog(
this, is_reload,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
false));
}
| 172,315
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExpectCanDiscardFalseTrivial(const LifecycleUnit* lifecycle_unit,
DiscardReason discard_reason) {
DecisionDetails decision_details;
EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
EXPECT_FALSE(decision_details.IsPositive());
EXPECT_TRUE(decision_details.reasons().empty());
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
|
void ExpectCanDiscardFalseTrivial(const LifecycleUnit* lifecycle_unit,
DiscardReason discard_reason) {
DecisionDetails decision_details;
EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
EXPECT_FALSE(decision_details.IsPositive());
// |reasons()| will either contain the status for the 4 local site features
// heuristics or be empty if the database doesn't track this lifecycle unit.
EXPECT_TRUE(decision_details.reasons().empty() ||
(decision_details.reasons().size() == 4));
}
| 172,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: void TestFlashMessageLoop::RunTests(const std::string& filter) {
RUN_TEST(Basics, filter);
RUN_TEST(RunWithoutQuit, filter);
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264
|
void TestFlashMessageLoop::RunTests(const std::string& filter) {
RUN_TEST(Basics, filter);
RUN_TEST(RunWithoutQuit, filter);
RUN_TEST(SuspendScriptCallbackWhileRunning, filter);
}
void TestFlashMessageLoop::DidRunScriptCallback() {
// Script callbacks are not supposed to run while the Flash message loop is
// running.
if (message_loop_)
suspend_script_callback_result_ = false;
}
pp::deprecated::ScriptableObject* TestFlashMessageLoop::CreateTestObject() {
if (!instance_so_)
instance_so_ = new InstanceSO(this);
return instance_so_;
}
| 172,125
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Track::Info::Info():
uid(0),
defaultDuration(0),
codecDelay(0),
seekPreRoll(0),
nameAsUTF8(NULL),
language(NULL),
codecId(NULL),
codecNameAsUTF8(NULL),
codecPrivate(NULL),
codecPrivateSize(0),
lacing(false)
{
}
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
|
Track::Info::Info():
| 174,385
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: AppCacheUpdateJob::~AppCacheUpdateJob() {
if (service_)
service_->RemoveObserver(this);
if (internal_state_ != COMPLETED)
Cancel();
DCHECK(!manifest_fetcher_);
DCHECK(pending_url_fetches_.empty());
DCHECK(!inprogress_cache_.get());
DCHECK(pending_master_entries_.empty());
DCHECK(master_entry_fetches_.empty());
if (group_)
group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE);
}
Commit Message: AppCache: fix a browser crashing bug that can happen during updates.
BUG=558589
Review URL: https://codereview.chromium.org/1463463003
Cr-Commit-Position: refs/heads/master@{#360967}
CWE ID:
|
AppCacheUpdateJob::~AppCacheUpdateJob() {
if (service_)
service_->RemoveObserver(this);
if (internal_state_ != COMPLETED)
Cancel();
DCHECK(!inprogress_cache_.get());
DCHECK(pending_master_entries_.empty());
// The job must not outlive any of its fetchers.
CHECK(!manifest_fetcher_);
CHECK(pending_url_fetches_.empty());
CHECK(master_entry_fetches_.empty());
if (group_)
group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE);
}
| 171,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: void BeginInstallWithManifestFunction::OnParseSuccess(
const SkBitmap& icon, DictionaryValue* parsed_manifest) {
CHECK(parsed_manifest);
icon_ = icon;
parsed_manifest_.reset(parsed_manifest);
std::string init_errors;
dummy_extension_ = Extension::Create(
FilePath(),
Extension::INTERNAL,
*static_cast<DictionaryValue*>(parsed_manifest_.get()),
Extension::NO_FLAGS,
&init_errors);
if (!dummy_extension_.get()) {
OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError));
return;
}
if (icon_.empty())
icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app());
ShowExtensionInstallDialog(profile(),
this,
dummy_extension_.get(),
&icon_,
dummy_extension_->GetPermissionMessageStrings(),
ExtensionInstallUI::INSTALL_PROMPT);
}
Commit Message: Adding tests for new webstore beginInstallWithManifest method.
BUG=75821
TEST=none
Review URL: http://codereview.chromium.org/6900059
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83080 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void BeginInstallWithManifestFunction::OnParseSuccess(
const SkBitmap& icon, DictionaryValue* parsed_manifest) {
CHECK(parsed_manifest);
icon_ = icon;
parsed_manifest_.reset(parsed_manifest);
std::string init_errors;
dummy_extension_ = Extension::Create(
FilePath(),
Extension::INTERNAL,
*static_cast<DictionaryValue*>(parsed_manifest_.get()),
Extension::NO_FLAGS,
&init_errors);
if (!dummy_extension_.get()) {
OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError));
return;
}
if (icon_.empty())
icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app());
// In tests, we may have setup to proceed or abort without putting up the real
// confirmation dialog.
if (auto_confirm_for_tests != DO_NOT_SKIP) {
if (auto_confirm_for_tests == PROCEED)
this->InstallUIProceed();
else
this->InstallUIAbort();
return;
}
ShowExtensionInstallDialog(profile(),
this,
dummy_extension_.get(),
&icon_,
dummy_extension_->GetPermissionMessageStrings(),
ExtensionInstallUI::INSTALL_PROMPT);
}
| 170,405
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ext4_writepage(struct page *page,
struct writeback_control *wbc)
{
int ret = 0;
loff_t size;
unsigned int len;
struct buffer_head *page_bufs;
struct inode *inode = page->mapping->host;
trace_ext4_writepage(inode, page);
size = i_size_read(inode);
if (page->index == size >> PAGE_CACHE_SHIFT)
len = size & ~PAGE_CACHE_MASK;
else
len = PAGE_CACHE_SIZE;
if (page_has_buffers(page)) {
page_bufs = page_buffers(page);
if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
ext4_bh_delay_or_unwritten)) {
/*
* We don't want to do block allocation
* So redirty the page and return
* We may reach here when we do a journal commit
* via journal_submit_inode_data_buffers.
* If we don't have mapping block we just ignore
* them. We can also reach here via shrink_page_list
*/
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
} else {
/*
* The test for page_has_buffers() is subtle:
* We know the page is dirty but it lost buffers. That means
* that at some moment in time after write_begin()/write_end()
* has been called all buffers have been clean and thus they
* must have been written at least once. So they are all
* mapped and we can happily proceed with mapping them
* and writing the page.
*
* Try to initialize the buffer_heads and check whether
* all are mapped and non delay. We don't want to
* do block allocation here.
*/
ret = block_prepare_write(page, 0, len,
noalloc_get_block_write);
if (!ret) {
page_bufs = page_buffers(page);
/* check whether all are mapped and non delay */
if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
ext4_bh_delay_or_unwritten)) {
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
} else {
/*
* We can't do block allocation here
* so just redity the page and unlock
* and return
*/
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
/* now mark the buffer_heads as dirty and uptodate */
block_commit_write(page, 0, len);
}
if (PageChecked(page) && ext4_should_journal_data(inode)) {
/*
* It's mmapped pagecache. Add buffers and journal it. There
* doesn't seem much point in redirtying the page here.
*/
ClearPageChecked(page);
return __ext4_journalled_writepage(page, len);
}
if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
ret = nobh_writepage(page, noalloc_get_block_write, wbc);
else
ret = block_write_full_page(page, noalloc_get_block_write,
wbc);
return ret;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
static int ext4_writepage(struct page *page,
struct writeback_control *wbc)
{
int ret = 0;
loff_t size;
unsigned int len;
struct buffer_head *page_bufs = NULL;
struct inode *inode = page->mapping->host;
trace_ext4_writepage(inode, page);
size = i_size_read(inode);
if (page->index == size >> PAGE_CACHE_SHIFT)
len = size & ~PAGE_CACHE_MASK;
else
len = PAGE_CACHE_SIZE;
if (page_has_buffers(page)) {
page_bufs = page_buffers(page);
if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
ext4_bh_delay_or_unwritten)) {
/*
* We don't want to do block allocation
* So redirty the page and return
* We may reach here when we do a journal commit
* via journal_submit_inode_data_buffers.
* If we don't have mapping block we just ignore
* them. We can also reach here via shrink_page_list
*/
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
} else {
/*
* The test for page_has_buffers() is subtle:
* We know the page is dirty but it lost buffers. That means
* that at some moment in time after write_begin()/write_end()
* has been called all buffers have been clean and thus they
* must have been written at least once. So they are all
* mapped and we can happily proceed with mapping them
* and writing the page.
*
* Try to initialize the buffer_heads and check whether
* all are mapped and non delay. We don't want to
* do block allocation here.
*/
ret = block_prepare_write(page, 0, len,
noalloc_get_block_write);
if (!ret) {
page_bufs = page_buffers(page);
/* check whether all are mapped and non delay */
if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
ext4_bh_delay_or_unwritten)) {
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
} else {
/*
* We can't do block allocation here
* so just redity the page and unlock
* and return
*/
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
/* now mark the buffer_heads as dirty and uptodate */
block_commit_write(page, 0, len);
}
if (PageChecked(page) && ext4_should_journal_data(inode)) {
/*
* It's mmapped pagecache. Add buffers and journal it. There
* doesn't seem much point in redirtying the page here.
*/
ClearPageChecked(page);
return __ext4_journalled_writepage(page, len);
}
if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
ret = nobh_writepage(page, noalloc_get_block_write, wbc);
else if (page_bufs && buffer_uninit(page_bufs)) {
ext4_set_bh_endio(page_bufs, inode);
ret = block_write_full_page_endio(page, noalloc_get_block_write,
wbc, ext4_end_io_buffer_write);
} else
ret = block_write_full_page(page, noalloc_get_block_write,
wbc);
return ret;
}
| 167,549
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeOSSetImePropertyActivated(
InputMethodStatusConnection* connection, const char* key, bool activated) {
DLOG(INFO) << "SetImePropertyeActivated: " << key << ": " << activated;
DCHECK(key);
g_return_if_fail(connection);
connection->SetImePropertyActivated(key, activated);
}
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
|
void ChromeOSSetImePropertyActivated(
| 170,527
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) {
ipfix_template_record_t *ipfix_template_record;
while ( size_left ) {
uint32_t id;
ipfix_template_record = (ipfix_template_record_t *)DataPtr;
size_left -= 4;
id = ntohs(ipfix_template_record->TemplateID);
if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) {
remove_all_translation_tables(exporter);
ReInitExtensionMapList(fs);
} else {
remove_translation_table(fs, exporter, id);
}
DataPtr = DataPtr + 4;
if ( size_left < 4 ) {
dbg_printf("Skip %u bytes padding\n", size_left);
size_left = 0;
}
}
} // End of Process_ipfix_template_withdraw
Commit Message: Fix potential unsigned integer underflow
CWE ID: CWE-190
|
static void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) {
ipfix_template_record_t *ipfix_template_record;
while ( size_left ) {
uint32_t id;
if ( size_left < 4 ) {
LogError("Process_ipfix [%u] Template withdraw size error at %s line %u" ,
exporter->info.id, __FILE__, __LINE__, strerror (errno));
size_left = 0;
continue;
}
ipfix_template_record = (ipfix_template_record_t *)DataPtr;
size_left -= 4;
id = ntohs(ipfix_template_record->TemplateID);
if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) {
remove_all_translation_tables(exporter);
ReInitExtensionMapList(fs);
} else {
remove_translation_table(fs, exporter, id);
}
DataPtr = DataPtr + 4;
if ( size_left < 4 ) {
dbg_printf("Skip %u bytes padding\n", size_left);
size_left = 0;
}
}
} // End of Process_ipfix_template_withdraw
| 169,583
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
return r;
}
Commit Message: Fix seven bugs discovered and fixed by ForAllSecure:
CVE-2019-13217: heap buffer overflow in start_decoder()
CVE-2019-13218: stack buffer overflow in compute_codewords()
CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()
CVE-2019-13220: out-of-range read in draw_line()
CVE-2019-13221: issue with large 1D codebooks in lookup1_values()
CVE-2019-13222: unchecked NULL returned by get_window()
CVE-2019-13223: division by zero in predict_point()
CWE ID: CWE-20
|
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
if (pow((float) r+1, dim) <= entries)
return -1;
if ((int) floor(pow((float) r, dim)) > entries)
return -1;
return r;
}
| 169,616
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nsc_encode_subsampling(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
BYTE* co_dst;
BYTE* cg_dst;
INT8* co_src0;
INT8* co_src1;
INT8* cg_src0;
INT8* cg_src1;
UINT32 tempWidth;
UINT32 tempHeight;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
for (y = 0; y < tempHeight >> 1; y++)
{
co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);
cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);
co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;
co_src1 = co_src0 + tempWidth;
cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;
cg_src1 = cg_src0 + tempWidth;
for (x = 0; x < tempWidth >> 1; x++)
{
*co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) +
(INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2);
*cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) +
(INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2);
co_src0 += 2;
co_src1 += 2;
cg_src0 += 2;
cg_src1 += 2;
}
}
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787
|
static void nsc_encode_subsampling(NSC_CONTEXT* context)
static BOOL nsc_encode_subsampling(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
UINT32 tempWidth;
UINT32 tempHeight;
if (!context)
return FALSE;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
if (tempHeight == 0)
return FALSE;
if (tempWidth > context->priv->PlaneBuffersLength / tempHeight)
return FALSE;
for (y = 0; y < tempHeight >> 1; y++)
{
BYTE* co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);
BYTE* cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);
const INT8* co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;
const INT8* co_src1 = co_src0 + tempWidth;
const INT8* cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;
const INT8* cg_src1 = cg_src0 + tempWidth;
for (x = 0; x < tempWidth >> 1; x++)
{
*co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) +
(INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2);
*cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) +
(INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2);
co_src0 += 2;
co_src1 += 2;
cg_src0 += 2;
cg_src1 += 2;
}
}
return TRUE;
}
| 169,289
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Erase(const std::string& addr) {
base::AutoLock lock(lock_);
map_.erase(addr);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void Erase(const std::string& addr) {
// Erases the entry for |preview_id|.
void Erase(int32 preview_id) {
base::AutoLock lock(lock_);
map_.erase(preview_id);
}
| 170,830
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BaseShadow::log_except(const char *msg)
{
ShadowExceptionEvent event;
bool exception_already_logged = false;
if(!msg) msg = "";
sprintf(event.message, msg);
if ( BaseShadow::myshadow_ptr ) {
BaseShadow *shadow = BaseShadow::myshadow_ptr;
event.recvd_bytes = shadow->bytesSent();
event.sent_bytes = shadow->bytesReceived();
exception_already_logged = shadow->exception_already_logged;
if (shadow->began_execution) {
event.began_execution = TRUE;
}
} else {
event.recvd_bytes = 0.0;
event.sent_bytes = 0.0;
}
if (!exception_already_logged && !uLog.writeEventNoFsync (&event,NULL))
{
::dprintf (D_ALWAYS, "Unable to log ULOG_SHADOW_EXCEPTION event\n");
}
}
Commit Message:
CWE ID: CWE-134
|
BaseShadow::log_except(const char *msg)
{
ShadowExceptionEvent event;
bool exception_already_logged = false;
if(!msg) msg = "";
sprintf(event.message, "%s", msg);
if ( BaseShadow::myshadow_ptr ) {
BaseShadow *shadow = BaseShadow::myshadow_ptr;
event.recvd_bytes = shadow->bytesSent();
event.sent_bytes = shadow->bytesReceived();
exception_already_logged = shadow->exception_already_logged;
if (shadow->began_execution) {
event.began_execution = TRUE;
}
} else {
event.recvd_bytes = 0.0;
event.sent_bytes = 0.0;
}
if (!exception_already_logged && !uLog.writeEventNoFsync (&event,NULL))
{
::dprintf (D_ALWAYS, "Unable to log ULOG_SHADOW_EXCEPTION event\n");
}
}
| 165,377
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cues::DoneParsing() const
{
const long long stop = m_start + m_size;
return (m_pos >= stop);
}
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
|
bool Cues::DoneParsing() const
| 174,267
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftVPX::onQueueFilled(OMX_U32 /* portIndex */) {
if (mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
bool EOSseen = false;
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
EOSseen = true;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
}
if (mImg == NULL) {
if (vpx_codec_decode(
(vpx_codec_ctx_t *)mCtx,
inHeader->pBuffer + inHeader->nOffset,
inHeader->nFilledLen,
NULL,
0)) {
ALOGE("on2 decoder failed to decode frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
vpx_codec_iter_t iter = NULL;
mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter);
}
if (mImg != NULL) {
CHECK_EQ(mImg->fmt, IMG_FMT_I420);
uint32_t width = mImg->d_w;
uint32_t height = mImg->d_h;
bool portWillReset = false;
handlePortSettingsChange(&portWillReset, width, height);
if (portWillReset) {
return;
}
outHeader->nOffset = 0;
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nFlags = EOSseen ? OMX_BUFFERFLAG_EOS : 0;
outHeader->nTimeStamp = inHeader->nTimeStamp;
uint8_t *dst = outHeader->pBuffer;
const uint8_t *srcY = (const uint8_t *)mImg->planes[PLANE_Y];
const uint8_t *srcU = (const uint8_t *)mImg->planes[PLANE_U];
const uint8_t *srcV = (const uint8_t *)mImg->planes[PLANE_V];
size_t srcYStride = mImg->stride[PLANE_Y];
size_t srcUStride = mImg->stride[PLANE_U];
size_t srcVStride = mImg->stride[PLANE_V];
copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride);
mImg = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
Commit Message: DO NOT MERGE - Remove deprecated image defines
libvpx has always supported the VPX_ prefixed versions of these defines.
The unprefixed versions have been removed in the most recent release.
https://chromium.googlesource.com/webm/libvpx/+/9cdaa3d72eade9ad162ef8f78a93bd8f85c6de10
BUG=23452792
Change-Id: I8a656f2262f117d7a95271f45100b8c6fd0a470f
CWE ID: CWE-119
|
void SoftVPX::onQueueFilled(OMX_U32 /* portIndex */) {
if (mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
bool EOSseen = false;
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
EOSseen = true;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
}
if (mImg == NULL) {
if (vpx_codec_decode(
(vpx_codec_ctx_t *)mCtx,
inHeader->pBuffer + inHeader->nOffset,
inHeader->nFilledLen,
NULL,
0)) {
ALOGE("on2 decoder failed to decode frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
vpx_codec_iter_t iter = NULL;
mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter);
}
if (mImg != NULL) {
CHECK_EQ(mImg->fmt, VPX_IMG_FMT_I420);
uint32_t width = mImg->d_w;
uint32_t height = mImg->d_h;
bool portWillReset = false;
handlePortSettingsChange(&portWillReset, width, height);
if (portWillReset) {
return;
}
outHeader->nOffset = 0;
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nFlags = EOSseen ? OMX_BUFFERFLAG_EOS : 0;
outHeader->nTimeStamp = inHeader->nTimeStamp;
uint8_t *dst = outHeader->pBuffer;
const uint8_t *srcY = (const uint8_t *)mImg->planes[VPX_PLANE_Y];
const uint8_t *srcU = (const uint8_t *)mImg->planes[VPX_PLANE_U];
const uint8_t *srcV = (const uint8_t *)mImg->planes[VPX_PLANE_V];
size_t srcYStride = mImg->stride[VPX_PLANE_Y];
size_t srcUStride = mImg->stride[VPX_PLANE_U];
size_t srcVStride = mImg->stride[VPX_PLANE_V];
copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride);
mImg = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
| 173,899
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
if (!h) {
return 0;
}
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) err = BAD_VALUE;
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
Commit Message: Correctly handle dup() failure in Parcel::readNativeHandle
bail out if dup() fails, instead of creating an invalid native_handle_t
Bug: 28395952
Change-Id: Ia1a6198c0f45165b9c6a55a803e5f64d8afa0572
CWE ID: CWE-20
|
native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
if (!h) {
return 0;
}
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) {
for (int j = 0; j < i; j++) {
close(h->data[j]);
}
native_handle_delete(h);
return 0;
}
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
| 173,744
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: email_close(FILE *mailer)
{
char *temp;
mode_t prev_umask;
priv_state priv;
char *customSig;
if ( mailer == NULL ) {
return;
}
/* Want the letter to come from "condor" if possible */
priv = set_condor_priv();
customSig = NULL;
if ((customSig = param("EMAIL_SIGNATURE")) != NULL) {
fprintf( mailer, "\n\n");
fprintf( mailer, customSig);
fprintf( mailer, "\n");
free(customSig);
} else {
/* Put a signature on the bottom of the email */
fprintf( mailer, "\n\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n" );
fprintf( mailer, "Questions about this message or Condor in general?\n" );
/* See if there's an address users should use for help */
temp = param( "CONDOR_SUPPORT_EMAIL" );
if( ! temp ) {
temp = param( "CONDOR_ADMIN" );
}
if( temp ) {
fprintf( mailer, "Email address of the local Condor administrator: "
"%s\n", temp );
free( temp );
}
fprintf( mailer, "The Official Condor Homepage is "
"http://www.cs.wisc.edu/condor\n" );
}
fflush(mailer);
/* there are some oddities with how pclose can close a file. In some
arches, pclose will create temp files for locking and they need to
be of the correct perms in order to be deleted. So the umask is
set to something useable for the close operation. -pete 9/11/99
*/
prev_umask = umask(022);
/*
** we fclose() on UNIX, pclose on win32
*/
#if defined(WIN32)
if (EMAIL_FINAL_COMMAND == NULL) {
my_pclose( mailer );
} else {
char *email_filename = NULL;
/* Should this be a pclose??? -Erik 9/21/00 */
fclose( mailer );
dprintf(D_FULLDEBUG,"Sending email via system(%s)\n",
EMAIL_FINAL_COMMAND);
system(EMAIL_FINAL_COMMAND);
if ( (email_filename=strrchr(EMAIL_FINAL_COMMAND,'<')) ) {
email_filename++; /* go past the "<" */
email_filename++; /* go past the space after the < */
if ( unlink(email_filename) == -1 ) {
dprintf(D_ALWAYS,"email_close: cannot unlink temp file %s\n",
email_filename);
}
}
free(EMAIL_FINAL_COMMAND);
EMAIL_FINAL_COMMAND = NULL;
}
#else
(void)fclose( mailer );
#endif
umask(prev_umask);
/* Set priv state back */
set_priv(priv);
}
Commit Message:
CWE ID: CWE-134
|
email_close(FILE *mailer)
{
char *temp;
mode_t prev_umask;
priv_state priv;
char *customSig;
if ( mailer == NULL ) {
return;
}
/* Want the letter to come from "condor" if possible */
priv = set_condor_priv();
customSig = NULL;
if ((customSig = param("EMAIL_SIGNATURE")) != NULL) {
fprintf( mailer, "\n\n");
fprintf( mailer, "%s", customSig);
fprintf( mailer, "\n");
free(customSig);
} else {
/* Put a signature on the bottom of the email */
fprintf( mailer, "\n\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n" );
fprintf( mailer, "Questions about this message or Condor in general?\n" );
/* See if there's an address users should use for help */
temp = param( "CONDOR_SUPPORT_EMAIL" );
if( ! temp ) {
temp = param( "CONDOR_ADMIN" );
}
if( temp ) {
fprintf( mailer, "Email address of the local Condor administrator: "
"%s\n", temp );
free( temp );
}
fprintf( mailer, "The Official Condor Homepage is "
"http://www.cs.wisc.edu/condor\n" );
}
fflush(mailer);
/* there are some oddities with how pclose can close a file. In some
arches, pclose will create temp files for locking and they need to
be of the correct perms in order to be deleted. So the umask is
set to something useable for the close operation. -pete 9/11/99
*/
prev_umask = umask(022);
/*
** we fclose() on UNIX, pclose on win32
*/
#if defined(WIN32)
if (EMAIL_FINAL_COMMAND == NULL) {
my_pclose( mailer );
} else {
char *email_filename = NULL;
/* Should this be a pclose??? -Erik 9/21/00 */
fclose( mailer );
dprintf(D_FULLDEBUG,"Sending email via system(%s)\n",
EMAIL_FINAL_COMMAND);
system(EMAIL_FINAL_COMMAND);
if ( (email_filename=strrchr(EMAIL_FINAL_COMMAND,'<')) ) {
email_filename++; /* go past the "<" */
email_filename++; /* go past the space after the < */
if ( unlink(email_filename) == -1 ) {
dprintf(D_ALWAYS,"email_close: cannot unlink temp file %s\n",
email_filename);
}
}
free(EMAIL_FINAL_COMMAND);
EMAIL_FINAL_COMMAND = NULL;
}
#else
(void)fclose( mailer );
#endif
umask(prev_umask);
/* Set priv state back */
set_priv(priv);
}
| 165,384
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __detach_mounts(struct dentry *dentry)
{
struct mountpoint *mp;
struct mount *mnt;
namespace_lock();
mp = lookup_mountpoint(dentry);
if (IS_ERR_OR_NULL(mp))
goto out_unlock;
lock_mount_hash();
while (!hlist_empty(&mp->m_list)) {
mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
hlist_add_head(&p->mnt_umount.s_list, &unmounted);
umount_mnt(p);
}
}
else umount_tree(mnt, 0);
}
unlock_mount_hash();
put_mountpoint(mp);
out_unlock:
namespace_unlock();
}
Commit Message: mnt: Update detach_mounts to leave mounts connected
Now that it is possible to lazily unmount an entire mount tree and
leave the individual mounts connected to each other add a new flag
UMOUNT_CONNECTED to umount_tree to force this behavior and use
this flag in detach_mounts.
This closes a bug where the deletion of a file or directory could
trigger an unmount and reveal data under a mount point.
Cc: stable@vger.kernel.org
Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
CWE ID: CWE-200
|
void __detach_mounts(struct dentry *dentry)
{
struct mountpoint *mp;
struct mount *mnt;
namespace_lock();
mp = lookup_mountpoint(dentry);
if (IS_ERR_OR_NULL(mp))
goto out_unlock;
lock_mount_hash();
while (!hlist_empty(&mp->m_list)) {
mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
hlist_add_head(&p->mnt_umount.s_list, &unmounted);
umount_mnt(p);
}
}
else umount_tree(mnt, UMOUNT_CONNECTED);
}
unlock_mount_hash();
put_mountpoint(mp);
out_unlock:
namespace_unlock();
}
| 167,564
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData)
{
Mutex::Autolock _l(mLock);
ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
if (mState == DESTROYED || mEffectInterface == NULL) {
return NO_INIT;
}
if (mStatus != NO_ERROR) {
return mStatus;
}
if (cmdCode == EFFECT_CMD_GET_PARAM &&
(*replySize < sizeof(effect_param_t) ||
((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) {
android_errorWriteLog(0x534e4554, "29251553");
return -EINVAL;
}
status_t status = (*mEffectInterface)->command(mEffectInterface,
cmdCode,
cmdSize,
pCmdData,
replySize,
pReplyData);
if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
uint32_t size = (replySize == NULL) ? 0 : *replySize;
for (size_t i = 1; i < mHandles.size(); i++) {
EffectHandle *h = mHandles[i];
if (h != NULL && !h->destroyed_l()) {
h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
}
}
}
return status;
}
Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking
Bug: 30204301
Change-Id: Ib9c3ee1c2f23c96f8f7092dd9e146bc453d7a290
(cherry picked from commit e4a1d91501d47931dbae19c47815952378787ab6)
CWE ID: CWE-200
|
status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData)
{
Mutex::Autolock _l(mLock);
ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
if (mState == DESTROYED || mEffectInterface == NULL) {
return NO_INIT;
}
if (mStatus != NO_ERROR) {
return mStatus;
}
if (cmdCode == EFFECT_CMD_GET_PARAM &&
(*replySize < sizeof(effect_param_t) ||
((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) {
android_errorWriteLog(0x534e4554, "29251553");
return -EINVAL;
}
if ((cmdCode == EFFECT_CMD_SET_PARAM
|| cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) && // DEFERRED not generally used
(sizeof(effect_param_t) > cmdSize
|| ((effect_param_t *)pCmdData)->psize > cmdSize
- sizeof(effect_param_t)
|| ((effect_param_t *)pCmdData)->vsize > cmdSize
- sizeof(effect_param_t)
- ((effect_param_t *)pCmdData)->psize
|| roundUpDelta(((effect_param_t *)pCmdData)->psize, (uint32_t)sizeof(int)) >
cmdSize
- sizeof(effect_param_t)
- ((effect_param_t *)pCmdData)->psize
- ((effect_param_t *)pCmdData)->vsize)) {
android_errorWriteLog(0x534e4554, "30204301");
return -EINVAL;
}
status_t status = (*mEffectInterface)->command(mEffectInterface,
cmdCode,
cmdSize,
pCmdData,
replySize,
pReplyData);
if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
uint32_t size = (replySize == NULL) ? 0 : *replySize;
for (size_t i = 1; i < mHandles.size(); i++) {
EffectHandle *h = mHandles[i];
if (h != NULL && !h->destroyed_l()) {
h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
}
}
}
return status;
}
| 173,387
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SetUpCommandLine(CommandLine* command_line) {
GpuFeatureTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableThreadedCompositing);
}
Commit Message: Revert 124346 - Add basic threaded compositor test to gpu_feature_browsertest.cc
BUG=113159
Review URL: http://codereview.chromium.org/9509001
TBR=jbates@chromium.org
Review URL: https://chromiumcodereview.appspot.com/9561011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@124356 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual void SetUpCommandLine(CommandLine* command_line) {
| 170,959
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MockRenderThread::OnMessageReceived(const IPC::Message& msg) {
sink_.OnMessageReceived(msg);
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(MockRenderThread, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnMsgCreateWidget)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
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
|
bool MockRenderThread::OnMessageReceived(const IPC::Message& msg) {
sink_.OnMessageReceived(msg);
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(MockRenderThread, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnMsgCreateWidget)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWindow, OnMsgCreateWindow)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
| 171,023
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 asn1_read_BOOLEAN_context(struct asn1_data *data, bool *v, int context)
{
uint8_t tmp = 0;
asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(context));
asn1_read_uint8(data, &tmp);
if (tmp == 0xFF) {
*v = true;
} else {
*v = false;
}
asn1_end_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
|
bool asn1_read_BOOLEAN_context(struct asn1_data *data, bool *v, int context)
{
uint8_t tmp = 0;
if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(context))) return false;
*v = false;
if (!asn1_read_uint8(data, &tmp)) return false;
if (tmp == 0xFF) {
*v = true;
}
return asn1_end_tag(data);
}
| 164,584
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions)
{
const KURL& requestURL = request.url();
ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
if (m_forceDoNotAllowStoredCredentials)
resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials;
resourceLoaderOptions.securityOrigin = m_securityOrigin;
if (m_async) {
if (!m_actualRequest.isNull())
resourceLoaderOptions.dataBufferingPolicy = BufferData;
if (m_options.timeoutMilliseconds > 0)
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE);
FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
ASSERT(!resource());
if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio)
setResource(RawResource::fetchMedia(newRequest, document().fetcher()));
else if (request.requestContext() == WebURLRequest::RequestContextManifest)
setResource(RawResource::fetchManifest(newRequest, document().fetcher()));
else
setResource(RawResource::fetch(newRequest, document().fetcher()));
if (!resource()) {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
ThreadableLoaderClient* client = m_client;
clear();
client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading."));
return;
}
if (resource()->loader()) {
unsigned long identifier = resource()->identifier();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
} else {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
}
return;
}
FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher());
ResourceResponse response = resource ? resource->response() : ResourceResponse();
unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
ResourceError error = resource ? resource->resourceError() : ResourceError();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
if (!resource) {
m_client->didFail(error);
return;
}
if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
m_client->didFail(error);
return;
}
if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
m_client->didFailRedirectCheck();
return;
}
handleResponse(identifier, response, nullptr);
if (!m_client)
return;
SharedBuffer* data = resource->resourceBuffer();
if (data)
handleReceivedData(data->data(), data->size());
if (!m_client)
return;
handleSuccessfulFinish(identifier, 0.0);
}
Commit Message: DocumentThreadableLoader: Add guards for sync notifyFinished() in setResource()
In loadRequest(), setResource() can call clear() synchronously:
DocumentThreadableLoader::clear()
DocumentThreadableLoader::handleError()
Resource::didAddClient()
RawResource::didAddClient()
and thus |m_client| can be null while resource() isn't null after setResource(),
causing crashes (Issue 595964).
This CL checks whether |*this| is destructed and
whether |m_client| is null after setResource().
BUG=595964
Review-Url: https://codereview.chromium.org/1902683002
Cr-Commit-Position: refs/heads/master@{#391001}
CWE ID: CWE-189
|
void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions)
{
const KURL& requestURL = request.url();
ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
if (m_forceDoNotAllowStoredCredentials)
resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials;
resourceLoaderOptions.securityOrigin = m_securityOrigin;
if (m_async) {
if (!m_actualRequest.isNull())
resourceLoaderOptions.dataBufferingPolicy = BufferData;
if (m_options.timeoutMilliseconds > 0)
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE);
FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
ASSERT(!resource());
WeakPtr<DocumentThreadableLoader> self(m_weakFactory.createWeakPtr());
if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio)
setResource(RawResource::fetchMedia(newRequest, document().fetcher()));
else if (request.requestContext() == WebURLRequest::RequestContextManifest)
setResource(RawResource::fetchManifest(newRequest, document().fetcher()));
else
setResource(RawResource::fetch(newRequest, document().fetcher()));
// setResource() might call notifyFinished() synchronously, and thus
// clear() might be called and |this| may be dead here.
if (!self)
return;
if (!resource()) {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
ThreadableLoaderClient* client = m_client;
clear();
// setResource() might call notifyFinished() and thus clear()
// synchronously, and in such cases ThreadableLoaderClient is
// already notified and |client| is null.
if (!client)
return;
client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading."));
return;
}
if (resource()->loader()) {
unsigned long identifier = resource()->identifier();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
} else {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
}
return;
}
FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher());
ResourceResponse response = resource ? resource->response() : ResourceResponse();
unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
ResourceError error = resource ? resource->resourceError() : ResourceError();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
if (!resource) {
m_client->didFail(error);
return;
}
if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
m_client->didFail(error);
return;
}
if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
m_client->didFailRedirectCheck();
return;
}
handleResponse(identifier, response, nullptr);
if (!m_client)
return;
SharedBuffer* data = resource->resourceBuffer();
if (data)
handleReceivedData(data->data(), data->size());
if (!m_client)
return;
handleSuccessfulFinish(identifier, 0.0);
}
| 171,612
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BaseRenderingContext2D::setStrokeStyle(
const StringOrCanvasGradientOrCanvasPattern& style) {
DCHECK(!style.IsNull());
String color_string;
CanvasStyle* canvas_style = nullptr;
if (style.IsString()) {
color_string = style.GetAsString();
if (color_string == GetState().UnparsedStrokeColor())
return;
Color parsed_color = 0;
if (!ParseColorOrCurrentColor(parsed_color, color_string))
return;
if (GetState().StrokeStyle()->IsEquivalentRGBA(parsed_color.Rgb())) {
ModifiableState().SetUnparsedStrokeColor(color_string);
return;
}
canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb());
} else if (style.IsCanvasGradient()) {
canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient());
} else if (style.IsCanvasPattern()) {
CanvasPattern* canvas_pattern = style.GetAsCanvasPattern();
if (OriginClean() && !canvas_pattern->OriginClean()) {
SetOriginTainted();
ClearResolvedFilters();
}
canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern);
}
DCHECK(canvas_style);
ModifiableState().SetStrokeStyle(canvas_style);
ModifiableState().SetUnparsedStrokeColor(color_string);
ModifiableState().ClearResolvedFilter();
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <fs@opera.com>
Commit-Queue: Chris Harrelson <chrishtr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200
|
void BaseRenderingContext2D::setStrokeStyle(
const StringOrCanvasGradientOrCanvasPattern& style) {
DCHECK(!style.IsNull());
String color_string;
CanvasStyle* canvas_style = nullptr;
if (style.IsString()) {
color_string = style.GetAsString();
if (color_string == GetState().UnparsedStrokeColor())
return;
Color parsed_color = 0;
if (!ParseColorOrCurrentColor(parsed_color, color_string))
return;
if (GetState().StrokeStyle()->IsEquivalentRGBA(parsed_color.Rgb())) {
ModifiableState().SetUnparsedStrokeColor(color_string);
return;
}
canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb());
} else if (style.IsCanvasGradient()) {
canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient());
} else if (style.IsCanvasPattern()) {
CanvasPattern* canvas_pattern = style.GetAsCanvasPattern();
if (!origin_tainted_by_content_ && !canvas_pattern->OriginClean())
SetOriginTaintedByContent();
canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern);
}
DCHECK(canvas_style);
ModifiableState().SetStrokeStyle(canvas_style);
ModifiableState().SetUnparsedStrokeColor(color_string);
ModifiableState().ClearResolvedFilter();
}
| 172,909
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 parse_video_info(AVIOContext *pb, AVStream *st)
{
uint16_t size_asf; // ASF-specific Format Data size
uint32_t size_bmp; // BMP_HEADER-specific Format Data size
unsigned int tag;
st->codecpar->width = avio_rl32(pb);
st->codecpar->height = avio_rl32(pb);
avio_skip(pb, 1); // skip reserved flags
size_asf = avio_rl16(pb);
tag = ff_get_bmp_header(pb, st, &size_bmp);
st->codecpar->codec_tag = tag;
st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag);
size_bmp = FFMAX(size_asf, size_bmp);
if (size_bmp > BMP_HEADER_SIZE) {
int ret;
st->codecpar->extradata_size = size_bmp - BMP_HEADER_SIZE;
if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size +
AV_INPUT_BUFFER_PADDING_SIZE))) {
st->codecpar->extradata_size = 0;
return AVERROR(ENOMEM);
}
memset(st->codecpar->extradata + st->codecpar->extradata_size , 0,
AV_INPUT_BUFFER_PADDING_SIZE);
if ((ret = avio_read(pb, st->codecpar->extradata,
st->codecpar->extradata_size)) < 0)
return ret;
}
return 0;
}
Commit Message: avformat/asfdec_o: Check size_bmp more fully
Fixes: integer overflow and out of array access
Fixes: asfo-crash-46080c4341572a7137a162331af77f6ded45cbd7
Found-by: Paul Ch <paulcher@icloud.com>
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-119
|
static int parse_video_info(AVIOContext *pb, AVStream *st)
{
uint16_t size_asf; // ASF-specific Format Data size
uint32_t size_bmp; // BMP_HEADER-specific Format Data size
unsigned int tag;
st->codecpar->width = avio_rl32(pb);
st->codecpar->height = avio_rl32(pb);
avio_skip(pb, 1); // skip reserved flags
size_asf = avio_rl16(pb);
tag = ff_get_bmp_header(pb, st, &size_bmp);
st->codecpar->codec_tag = tag;
st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag);
size_bmp = FFMAX(size_asf, size_bmp);
if (size_bmp > BMP_HEADER_SIZE &&
size_bmp < INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
int ret;
st->codecpar->extradata_size = size_bmp - BMP_HEADER_SIZE;
if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size +
AV_INPUT_BUFFER_PADDING_SIZE))) {
st->codecpar->extradata_size = 0;
return AVERROR(ENOMEM);
}
memset(st->codecpar->extradata + st->codecpar->extradata_size , 0,
AV_INPUT_BUFFER_PADDING_SIZE);
if ((ret = avio_read(pb, st->codecpar->extradata,
st->codecpar->extradata_size)) < 0)
return ret;
}
return 0;
}
| 168,926
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CrosLibrary::TestApi::SetUpdateLibrary(
UpdateLibrary* library, bool own) {
library_->update_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
void CrosLibrary::TestApi::SetUpdateLibrary(
| 170,649
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 getnum (lua_State *L, const char **fmt, int df) {
if (!isdigit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))
luaL_error(L, "integral size overflow");
a = a*10 + *((*fmt)++) - '0';
} while (isdigit(**fmt));
return a;
}
}
Commit Message: Security: update Lua struct package for security.
During an auditing Apple found that the "struct" Lua package
we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains
a security problem. A bound-checking statement fails because of integer
overflow. The bug exists since we initially integrated this package with
Lua, when scripting was introduced, so every version of Redis with
EVAL/EVALSHA capabilities exposed is affected.
Instead of just fixing the bug, the library was updated to the latest
version shipped by the author.
CWE ID: CWE-190
|
static int getnum (lua_State *L, const char **fmt, int df) {
static int getnum (const char **fmt, int df) {
if (!isdigit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
a = a*10 + *((*fmt)++) - '0';
} while (isdigit(**fmt));
return a;
}
}
| 170,165
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeMetricsServiceClient::RegisterUKMProviders() {
ukm_service_->RegisterMetricsProvider(
std::make_unique<metrics::NetworkMetricsProvider>(
content::CreateNetworkConnectionTrackerAsyncGetter(),
std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>()));
#if defined(OS_CHROMEOS)
ukm_service_->RegisterMetricsProvider(
std::make_unique<ChromeOSMetricsProvider>());
#endif // !defined(OS_CHROMEOS)
ukm_service_->RegisterMetricsProvider(
std::make_unique<variations::FieldTrialsProvider>(nullptr,
kUKMFieldTrialSuffix));
}
Commit Message: Add CPU metrics provider and Add CPU/GPU provider for UKM.
Bug: 907674
Change-Id: I61b88aeac8d2a7ff81d812fa5a267f48203ec7e2
Reviewed-on: https://chromium-review.googlesource.com/c/1381376
Commit-Queue: Nik Bhagat <nikunjb@chromium.org>
Reviewed-by: Robert Kaplow <rkaplow@chromium.org>
Cr-Commit-Position: refs/heads/master@{#618037}
CWE ID: CWE-79
|
void ChromeMetricsServiceClient::RegisterUKMProviders() {
ukm_service_->RegisterMetricsProvider(
std::make_unique<metrics::NetworkMetricsProvider>(
content::CreateNetworkConnectionTrackerAsyncGetter(),
std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>()));
#if defined(OS_CHROMEOS)
ukm_service_->RegisterMetricsProvider(
std::make_unique<ChromeOSMetricsProvider>());
#endif // !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::GPUMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::CPUMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::ScreenInfoMetricsProvider>());
ukm_service_->RegisterMetricsProvider(
std::make_unique<variations::FieldTrialsProvider>(nullptr,
kUKMFieldTrialSuffix));
}
| 172,071
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: dhcpv4_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint8_t type, optlen;
i = 0;
while (i < length) {
tlv = cp + i;
type = (uint8_t)tlv[0];
optlen = (uint8_t)tlv[1];
value = tlv + 2;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 2 ));
switch (type) {
case DH4OPT_DNS_SERVERS:
case DH4OPT_NTP_SERVERS: {
if (optlen < 4 || optlen % 4 != 0) {
return -1;
}
for (t = 0; t < optlen; t += 4)
ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t)));
}
break;
case DH4OPT_DOMAIN_SEARCH: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 2 + optlen;
}
return 0;
}
Commit Message: CVE-2017-13044/HNCP: add DHCPv4-Data bounds checks
dhcpv4_print() in print-hncp.c had the same bug as dhcpv6_print(), apply
a fix along the same lines.
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
|
dhcpv4_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint8_t type, optlen;
i = 0;
while (i < length) {
if (i + 2 > length)
return -1;
tlv = cp + i;
type = (uint8_t)tlv[0];
optlen = (uint8_t)tlv[1];
value = tlv + 2;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 2 ));
if (i + 2 + optlen > length)
return -1;
switch (type) {
case DH4OPT_DNS_SERVERS:
case DH4OPT_NTP_SERVERS: {
if (optlen < 4 || optlen % 4 != 0) {
return -1;
}
for (t = 0; t < optlen; t += 4)
ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t)));
}
break;
case DH4OPT_DOMAIN_SEARCH: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 2 + optlen;
}
return 0;
}
| 167,831
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FaviconWebUIHandler::OnFaviconDataAvailable(
FaviconService::Handle request_handle,
history::FaviconData favicon) {
FaviconService* favicon_service =
web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
int id = consumer_.GetClientData(favicon_service, request_handle);
if (favicon.is_valid()) {
FundamentalValue id_value(id);
color_utils::GridSampler sampler;
SkColor color =
color_utils::CalculateKMeanColorOfPNG(favicon.image_data, 100, 665,
sampler);
std::string css_color = base::StringPrintf("rgb(%d, %d, %d)",
SkColorGetR(color),
SkColorGetG(color),
SkColorGetB(color));
StringValue color_value(css_color);
web_ui_->CallJavascriptFunction("ntp4.setFaviconDominantColor",
id_value, color_value);
}
}
Commit Message: ntp4: show larger favicons in most visited page
extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe).
BUG=none
TEST=manual
Review URL: http://codereview.chromium.org/7300017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void FaviconWebUIHandler::OnFaviconDataAvailable(
FaviconService::Handle request_handle,
history::FaviconData favicon) {
FaviconService* favicon_service =
web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
int id = consumer_.GetClientData(favicon_service, request_handle);
FundamentalValue id_value(id);
scoped_ptr<StringValue> color_value;
if (favicon.is_valid()) {
color_utils::GridSampler sampler;
SkColor color =
color_utils::CalculateKMeanColorOfPNG(favicon.image_data, 100, 665,
sampler);
std::string css_color = base::StringPrintf("rgb(%d, %d, %d)",
SkColorGetR(color),
SkColorGetG(color),
SkColorGetB(color));
color_value.reset(new StringValue(css_color));
} else {
color_value.reset(new StringValue("#919191"));
}
web_ui_->CallJavascriptFunction("ntp4.setFaviconDominantColor",
id_value, *color_value);
}
| 170,370
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DesktopSessionWin::OnChannelConnected() {
DCHECK(main_task_runner_->BelongsToCurrentThread());
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void DesktopSessionWin::OnChannelConnected() {
void DesktopSessionWin::OnChannelConnected(int32 peer_pid) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
}
| 171,542
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) {
if (parcel == NULL) {
SkDebugf("-------- unparcel parcel is NULL\n");
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
const bool isMutable = p->readInt32() != 0;
const SkColorType colorType = (SkColorType)p->readInt32();
const SkAlphaType alphaType = (SkAlphaType)p->readInt32();
const int width = p->readInt32();
const int height = p->readInt32();
const int rowBytes = p->readInt32();
const int density = p->readInt32();
if (kN32_SkColorType != colorType &&
kRGB_565_SkColorType != colorType &&
kARGB_4444_SkColorType != colorType &&
kIndex_8_SkColorType != colorType &&
kAlpha_8_SkColorType != colorType) {
SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType);
return NULL;
}
SkBitmap* bitmap = new SkBitmap;
bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes);
SkColorTable* ctable = NULL;
if (colorType == kIndex_8_SkColorType) {
int count = p->readInt32();
if (count > 0) {
size_t size = count * sizeof(SkPMColor);
const SkPMColor* src = (const SkPMColor*)p->readInplace(size);
ctable = new SkColorTable(src, count);
}
}
jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable);
if (NULL == buffer) {
SkSafeUnref(ctable);
delete bitmap;
return NULL;
}
SkSafeUnref(ctable);
size_t size = bitmap->getSize();
android::Parcel::ReadableBlob blob;
android::status_t status = p->readBlob(size, &blob);
if (status) {
doThrowRE(env, "Could not read bitmap from parcel blob.");
delete bitmap;
return NULL;
}
bitmap->lockPixels();
memcpy(bitmap->getPixels(), blob.data(), size);
bitmap->unlockPixels();
blob.release();
return GraphicsJNI::createBitmap(env, bitmap, buffer, getPremulBitmapCreateFlags(isMutable),
NULL, NULL, density);
}
Commit Message: Make Bitmap_createFromParcel check the color count. DO NOT MERGE
When reading from the parcel, if the number of colors is invalid, early
exit.
Add two more checks: setInfo must return true, and Parcel::readInplace
must return non-NULL. The former ensures that the previously read values
(width, height, etc) were valid, and the latter checks that the Parcel
had enough data even if the number of colors was reasonable.
Also use an auto-deleter to handle deletion of the SkBitmap.
Cherry pick from change-Id: Icbd562d6d1f131a723724883fd31822d337cf5a6
BUG=19666945
Change-Id: Iab0d218c41ae0c39606e333e44cda078eef32291
CWE ID: CWE-189
|
static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) {
if (parcel == NULL) {
SkDebugf("-------- unparcel parcel is NULL\n");
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
const bool isMutable = p->readInt32() != 0;
const SkColorType colorType = (SkColorType)p->readInt32();
const SkAlphaType alphaType = (SkAlphaType)p->readInt32();
const int width = p->readInt32();
const int height = p->readInt32();
const int rowBytes = p->readInt32();
const int density = p->readInt32();
if (kN32_SkColorType != colorType &&
kRGB_565_SkColorType != colorType &&
kARGB_4444_SkColorType != colorType &&
kIndex_8_SkColorType != colorType &&
kAlpha_8_SkColorType != colorType) {
SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType);
return NULL;
}
SkAutoTDelete<SkBitmap> bitmap(new SkBitmap);
if (!bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes)) {
return NULL;
}
SkColorTable* ctable = NULL;
if (colorType == kIndex_8_SkColorType) {
int count = p->readInt32();
if (count < 0 || count > 256) {
// The data is corrupt, since SkColorTable enforces a value between 0 and 256,
// inclusive.
return NULL;
}
if (count > 0) {
size_t size = count * sizeof(SkPMColor);
const SkPMColor* src = (const SkPMColor*)p->readInplace(size);
if (src == NULL) {
return NULL;
}
ctable = new SkColorTable(src, count);
}
}
jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap.get(), ctable);
if (NULL == buffer) {
SkSafeUnref(ctable);
return NULL;
}
SkSafeUnref(ctable);
size_t size = bitmap->getSize();
android::Parcel::ReadableBlob blob;
android::status_t status = p->readBlob(size, &blob);
if (status) {
doThrowRE(env, "Could not read bitmap from parcel blob.");
return NULL;
}
bitmap->lockPixels();
memcpy(bitmap->getPixels(), blob.data(), size);
bitmap->unlockPixels();
blob.release();
return GraphicsJNI::createBitmap(env, bitmap.detach(), buffer,
getPremulBitmapCreateFlags(isMutable), NULL, NULL, density);
}
| 173,372
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (!mTimeToSample.empty() || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
if ((uint64_t)mTimeToSampleCount >
(uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) {
ALOGE(" Error: Time-to-sample table size too large.");
return ERROR_OUT_OF_RANGE;
}
if (!mDataSource->getVector(data_offset + 8, &mTimeToSample,
mTimeToSampleCount * 2)) {
ALOGE(" Error: Incomplete data read for time-to-sample table.");
return ERROR_IO;
}
for (size_t i = 0; i < mTimeToSample.size(); ++i) {
mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]);
}
return OK;
}
Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug
28076789.
Detail: Before the original fix
(Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the
code allowed a time-to-sample table size to be 0. The change
made in that fix disallowed such situation, which in fact should
be allowed. This current patch allows it again while maintaining
the security of the previous fix.
Bug: 28288202
Bug: 28076789
Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295
CWE ID: CWE-20
|
status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mHasTimeToSample || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
if ((uint64_t)mTimeToSampleCount >
(uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) {
ALOGE(" Error: Time-to-sample table size too large.");
return ERROR_OUT_OF_RANGE;
}
if (!mDataSource->getVector(data_offset + 8, &mTimeToSample,
mTimeToSampleCount * 2)) {
ALOGE(" Error: Incomplete data read for time-to-sample table.");
return ERROR_IO;
}
for (size_t i = 0; i < mTimeToSample.size(); ++i) {
mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]);
}
mHasTimeToSample = true;
return OK;
}
| 173,773
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
int i, j;
int w, h;
int leftbyte, rightbyte;
int shift;
uint8_t *s, *ss;
uint8_t *d, *dd;
uint8_t mask, rightmask;
if (op != JBIG2_COMPOSE_OR) {
/* hand off the the general routine */
return jbig2_image_compose_unopt(ctx, dst, src, x, y, op);
}
/* clip */
w = src->width;
h = src->height;
ss = src->data;
if (x < 0) {
w += x;
x = 0;
}
if (y < 0) {
h += y;
y = 0;
}
w = (x + w < dst->width) ? w : dst->width - x;
h = (y + h < dst->height) ? h : dst->height - y;
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping\n", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
#if 0
/* special case complete/strip replacement */
/* disabled because it's only safe to do when the destination
buffer is all-blank. */
if ((x == 0) && (w == src->width)) {
memcpy(dst->data + y * dst->stride, src->data, h * src->stride);
return 0;
}
#endif
leftbyte = x >> 3;
rightbyte = (x + w - 1) >> 3;
shift = x & 7;
/* general OR case */
s = ss;
d = dd = dst->data + y * dst->stride + leftbyte;
if (d < dst->data || leftbyte > dst->stride || h * dst->stride < 0 || d - leftbyte + h * dst->stride > dst->data + dst->height * dst->stride) {
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "preventing heap overflow in jbig2_image_compose");
}
if (leftbyte == rightbyte) {
mask = 0x100 - (0x100 >> w);
for (j = 0; j < h; j++) {
*d |= (*s & mask) >> shift;
d += dst->stride;
s += src->stride;
}
} else if (shift == 0) {
rightmask = (w & 7) ? 0x100 - (1 << (8 - (w & 7))) : 0xFF;
for (j = 0; j < h; j++) {
for (i = leftbyte; i < rightbyte; i++)
*d++ |= *s++;
*d |= *s & rightmask;
d = (dd += dst->stride);
s = (ss += src->stride);
}
} else {
bool overlap = (((w + 7) >> 3) < ((x + w + 7) >> 3) - (x >> 3));
mask = 0x100 - (1 << shift);
if (overlap)
rightmask = (0x100 - (0x100 >> ((x + w) & 7))) >> (8 - shift);
else
rightmask = 0x100 - (0x100 >> (w & 7));
for (j = 0; j < h; j++) {
*d++ |= (*s & mask) >> shift;
for (i = leftbyte; i < rightbyte - 1; i++) {
*d |= ((*s++ & ~mask) << (8 - shift));
*d++ |= ((*s & mask) >> shift);
}
if (overlap)
*d |= (*s & rightmask) << (8 - shift);
else
*d |= ((s[0] & ~mask) << (8 - shift)) | ((s[1] & rightmask) >> shift);
d = (dd += dst->stride);
s = (ss += src->stride);
}
}
return 0;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
uint32_t i, j;
uint32_t w, h;
uint32_t leftbyte, rightbyte;
uint32_t shift;
uint8_t *s, *ss;
uint8_t *d, *dd;
uint8_t mask, rightmask;
if (op != JBIG2_COMPOSE_OR) {
/* hand off the the general routine */
return jbig2_image_compose_unopt(ctx, dst, src, x, y, op);
}
/* clip */
w = src->width;
h = src->height;
ss = src->data;
if (x < 0) {
w += x;
x = 0;
}
if (y < 0) {
h += y;
y = 0;
}
w = ((uint32_t)x + w < dst->width) ? w : ((dst->width >= (uint32_t)x) ? dst->width - (uint32_t)x : 0);
h = ((uint32_t)y + h < dst->height) ? h : ((dst->height >= (uint32_t)y) ? dst->height - (uint32_t)y : 0);
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping\n", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
#if 0
/* special case complete/strip replacement */
/* disabled because it's only safe to do when the destination
buffer is all-blank. */
if ((x == 0) && (w == src->width)) {
memcpy(dst->data + y * dst->stride, src->data, h * src->stride);
return 0;
}
#endif
leftbyte = (uint32_t)x >> 3;
rightbyte = ((uint32_t)x + w - 1) >> 3;
shift = x & 7;
/* general OR case */
s = ss;
d = dd = dst->data + y * dst->stride + leftbyte;
if (d < dst->data || leftbyte > dst->stride || h * dst->stride < 0 || d - leftbyte + h * dst->stride > dst->data + dst->height * dst->stride) {
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "preventing heap overflow in jbig2_image_compose");
}
if (leftbyte == rightbyte) {
mask = 0x100 - (0x100 >> w);
for (j = 0; j < h; j++) {
*d |= (*s & mask) >> shift;
d += dst->stride;
s += src->stride;
}
} else if (shift == 0) {
rightmask = (w & 7) ? 0x100 - (1 << (8 - (w & 7))) : 0xFF;
for (j = 0; j < h; j++) {
for (i = leftbyte; i < rightbyte; i++)
*d++ |= *s++;
*d |= *s & rightmask;
d = (dd += dst->stride);
s = (ss += src->stride);
}
} else {
bool overlap = (((w + 7) >> 3) < ((x + w + 7) >> 3) - (x >> 3));
mask = 0x100 - (1 << shift);
if (overlap)
rightmask = (0x100 - (0x100 >> ((x + w) & 7))) >> (8 - shift);
else
rightmask = 0x100 - (0x100 >> (w & 7));
for (j = 0; j < h; j++) {
*d++ |= (*s & mask) >> shift;
for (i = leftbyte; i < rightbyte - 1; i++) {
*d |= ((*s++ & ~mask) << (8 - shift));
*d++ |= ((*s & mask) >> shift);
}
if (overlap)
*d |= (*s & rightmask) << (8 - shift);
else
*d |= ((s[0] & ~mask) << (8 - shift)) | ((s[1] & rightmask) >> shift);
d = (dd += dst->stride);
s = (ss += src->stride);
}
}
return 0;
}
| 165,489
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */
{
char *cipher_dir_string;
char *module_dir_string;
int block_size, max_key_length, use_key_length, i, count, iv_size;
unsigned long int data_size;
int *key_length_sizes;
char *key_s = NULL, *iv_s;
char *data_s;
MCRYPT td;
MCRYPT_GET_INI
td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
/* Checking for key-length */
max_key_length = mcrypt_enc_get_key_size(td);
if (key_len > max_key_length) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm");
}
key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count);
if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */
use_key_length = key_len;
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, use_key_length);
} else if (count == 1) { /* only m_k_l = OK */
key_s = emalloc(key_length_sizes[0]);
memset(key_s, 0, key_length_sizes[0]);
memcpy(key_s, key, MIN(key_len, key_length_sizes[0]));
use_key_length = key_length_sizes[0];
} else { /* dertermine smallest supported key > length of requested key */
use_key_length = max_key_length; /* start with max key length */
for (i = 0; i < count; i++) {
if (key_length_sizes[i] >= key_len &&
key_length_sizes[i] < use_key_length)
{
use_key_length = key_length_sizes[i];
}
}
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, MIN(key_len, use_key_length));
}
mcrypt_free (key_length_sizes);
/* Check IV */
iv_s = NULL;
iv_size = mcrypt_enc_get_iv_size (td);
/* IV is required */
if (mcrypt_enc_mode_has_iv(td) == 1) {
if (argc == 5) {
if (iv_size != iv_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE);
} else {
iv_s = emalloc(iv_size + 1);
memcpy(iv_s, iv, iv_size);
}
} else if (argc == 4) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend");
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
}
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed");
RETURN_FALSE;
}
if (dencrypt == MCRYPT_ENCRYPT) {
mcrypt_generic(td, data_s, data_size);
} else {
mdecrypt_generic(td, data_s, data_size);
}
RETVAL_STRINGL(data_s, data_size, 1);
/* freeing vars */
mcrypt_generic_end(td);
if (key_s != NULL) {
efree (key_s);
}
if (iv_s != NULL) {
efree (iv_s);
}
efree (data_s);
}
/* }}} */
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */
{
char *cipher_dir_string;
char *module_dir_string;
int block_size, max_key_length, use_key_length, i, count, iv_size;
unsigned long int data_size;
int *key_length_sizes;
char *key_s = NULL, *iv_s;
char *data_s;
MCRYPT td;
MCRYPT_GET_INI
td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
/* Checking for key-length */
max_key_length = mcrypt_enc_get_key_size(td);
if (key_len > max_key_length) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm");
}
key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count);
if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */
use_key_length = key_len;
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, use_key_length);
} else if (count == 1) { /* only m_k_l = OK */
key_s = emalloc(key_length_sizes[0]);
memset(key_s, 0, key_length_sizes[0]);
memcpy(key_s, key, MIN(key_len, key_length_sizes[0]));
use_key_length = key_length_sizes[0];
} else { /* dertermine smallest supported key > length of requested key */
use_key_length = max_key_length; /* start with max key length */
for (i = 0; i < count; i++) {
if (key_length_sizes[i] >= key_len &&
key_length_sizes[i] < use_key_length)
{
use_key_length = key_length_sizes[i];
}
}
key_s = emalloc(use_key_length);
memset(key_s, 0, use_key_length);
memcpy(key_s, key, MIN(key_len, use_key_length));
}
mcrypt_free (key_length_sizes);
/* Check IV */
iv_s = NULL;
iv_size = mcrypt_enc_get_iv_size (td);
/* IV is required */
if (mcrypt_enc_mode_has_iv(td) == 1) {
if (argc == 5) {
if (iv_size != iv_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE);
} else {
iv_s = emalloc(iv_size + 1);
memcpy(iv_s, iv, iv_size);
}
} else if (argc == 4) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend");
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
}
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed");
RETURN_FALSE;
}
if (dencrypt == MCRYPT_ENCRYPT) {
mcrypt_generic(td, data_s, data_size);
} else {
mdecrypt_generic(td, data_s, data_size);
}
RETVAL_STRINGL(data_s, data_size, 1);
/* freeing vars */
mcrypt_generic_end(td);
if (key_s != NULL) {
efree (key_s);
}
if (iv_s != NULL) {
efree (iv_s);
}
efree (data_s);
}
/* }}} */
| 167,113
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHPAPI php_stream *_php_stream_memory_create(int mode STREAMS_DC TSRMLS_DC)
{
php_stream_memory_data *self;
php_stream *stream;
self = emalloc(sizeof(*self));
self->data = NULL;
self->fpos = 0;
self->fsize = 0;
self->smax = ~0u;
self->mode = mode;
stream = php_stream_alloc_rel(&php_stream_memory_ops, self, 0, mode & TEMP_STREAM_READONLY ? "rb" : "w+b");
stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
return stream;
}
Commit Message:
CWE ID: CWE-20
|
PHPAPI php_stream *_php_stream_memory_create(int mode STREAMS_DC TSRMLS_DC)
{
php_stream_memory_data *self;
php_stream *stream;
self = emalloc(sizeof(*self));
self->data = NULL;
self->fpos = 0;
self->fsize = 0;
self->smax = ~0u;
self->mode = mode;
stream = php_stream_alloc_rel(&php_stream_memory_ops, self, 0, mode & TEMP_STREAM_READONLY ? "rb" : "w+b");
stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
return stream;
}
| 165,474
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool PermissionsContainsFunction::RunImpl() {
scoped_ptr<Contains::Params> params(Contains::Params::Create(*args_));
scoped_refptr<PermissionSet> permissions =
helpers::UnpackPermissionSet(params->permissions, &error_);
if (!permissions.get())
return false;
results_ = Contains::Results::Create(
GetExtension()->GetActivePermissions()->Contains(*permissions));
return true;
}
Commit Message: Check prefs before allowing extension file access in the permissions API.
R=mpcomplete@chromium.org
BUG=169632
Review URL: https://chromiumcodereview.appspot.com/11884008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool PermissionsContainsFunction::RunImpl() {
scoped_ptr<Contains::Params> params(Contains::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
ExtensionPrefs* prefs = ExtensionSystem::Get(profile_)->extension_prefs();
scoped_refptr<PermissionSet> permissions =
helpers::UnpackPermissionSet(params->permissions,
prefs->AllowFileAccess(extension_->id()),
&error_);
if (!permissions.get())
return false;
results_ = Contains::Results::Create(
GetExtension()->GetActivePermissions()->Contains(*permissions));
return true;
}
| 171,442
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len,
gx_io_device *iodev, const char *permitgroup)
{
long i;
ref *permitlist = NULL;
/* an empty string (first character == 0) if '\' character is */
/* recognized as a file name separator as on DOS & Windows */
const char *win_sep2 = "\\";
bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1);
uint plen = gp_file_name_parents(fname, len);
/* we're protecting arbitrary file system accesses, not Postscript device accesses.
* Although, note that %pipe% is explicitly checked for and disallowed elsewhere
*/
if (iodev != iodev_default(imemory)) {
return 0;
}
/* Assuming a reduced file name. */
if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0)
return 0; /* if Permissions not found, just allow access */
for (i=0; i<r_size(permitlist); i++) {
ref permitstring;
const string_match_params win_filename_params = {
'*', '?', '\\', true, true /* ignore case & '/' == '\\' */
};
const byte *permstr;
uint permlen;
int cwd_len = 0;
if (array_get(imemory, permitlist, i, &permitstring) < 0 ||
r_type(&permitstring) != t_string
)
break; /* any problem, just fail */
permstr = permitstring.value.bytes;
permlen = r_size(&permitstring);
/*
* Check if any file name is permitted with "*".
*/
if (permlen == 1 && permstr[0] == '*')
return 0; /* success */
/*
* If the filename starts with parent references,
* the permission element must start with same number of parent references.
*/
if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen))
continue;
cwd_len = gp_file_name_cwds((const char *)permstr, permlen);
/*
* If the permission starts with "./", absolute paths
* are not permitted.
*/
if (cwd_len > 0 && gp_file_name_is_absolute(fname, len))
continue;
/*
* If the permission starts with "./", relative paths
* with no "./" are allowed as well as with "./".
* 'fname' has no "./" because it is reduced.
*/
if (string_match( (const unsigned char*) fname, len,
permstr + cwd_len, permlen - cwd_len,
use_windows_pathsep ? &win_filename_params : NULL))
return 0; /* success */
}
/* not found */
return gs_error_invalidfileaccess;
}
Commit Message:
CWE ID:
|
check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len,
gx_io_device *iodev, const char *permitgroup)
{
long i;
ref *permitlist = NULL;
/* an empty string (first character == 0) if '\' character is */
/* recognized as a file name separator as on DOS & Windows */
const char *win_sep2 = "\\";
bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1);
uint plen = gp_file_name_parents(fname, len);
/* we're protecting arbitrary file system accesses, not Postscript device accesses.
* Although, note that %pipe% is explicitly checked for and disallowed elsewhere
*/
if (iodev && iodev != iodev_default(imemory)) {
return 0;
}
/* Assuming a reduced file name. */
if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0)
return 0; /* if Permissions not found, just allow access */
for (i=0; i<r_size(permitlist); i++) {
ref permitstring;
const string_match_params win_filename_params = {
'*', '?', '\\', true, true /* ignore case & '/' == '\\' */
};
const byte *permstr;
uint permlen;
int cwd_len = 0;
if (array_get(imemory, permitlist, i, &permitstring) < 0 ||
r_type(&permitstring) != t_string
)
break; /* any problem, just fail */
permstr = permitstring.value.bytes;
permlen = r_size(&permitstring);
/*
* Check if any file name is permitted with "*".
*/
if (permlen == 1 && permstr[0] == '*')
return 0; /* success */
/*
* If the filename starts with parent references,
* the permission element must start with same number of parent references.
*/
if (plen != 0 && plen != gp_file_name_parents((const char *)permstr, permlen))
continue;
cwd_len = gp_file_name_cwds((const char *)permstr, permlen);
/*
* If the permission starts with "./", absolute paths
* are not permitted.
*/
if (cwd_len > 0 && gp_file_name_is_absolute(fname, len))
continue;
/*
* If the permission starts with "./", relative paths
* with no "./" are allowed as well as with "./".
* 'fname' has no "./" because it is reduced.
*/
if (string_match( (const unsigned char*) fname, len,
permstr + cwd_len, permlen - cwd_len,
use_windows_pathsep ? &win_filename_params : NULL))
return 0; /* success */
}
/* not found */
return gs_error_invalidfileaccess;
}
| 164,708
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.