instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: raptor_rdfxml_parse_start(raptor_parser* rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rdfxml_parser* rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
/* base URI required for RDF/XML */
if(!uri)
return 1;
/* Optionally normalize language to lowercase
* http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier
*/
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE));
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rdf_xml_parser->sax2, uri);
/* Delete any existing id_set */
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
/* Create a new id_set if needed */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) {
rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world);
if(!rdf_xml_parser->id_set)
return 1;
}
return 0;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200 | raptor_rdfxml_parse_start(raptor_parser* rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rdfxml_parser* rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
/* base URI required for RDF/XML */
if(!uri)
return 1;
/* Optionally normalize language to lowercase
* http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier
*/
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE));
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rdf_xml_parser->sax2, uri);
/* Delete any existing id_set */
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
/* Create a new id_set if needed */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) {
rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world);
if(!rdf_xml_parser->id_set)
return 1;
}
return 0;
}
| 165,660 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CheckSADs() {
unsigned int reference_sad, exp_sad[4];
SADs(exp_sad);
for (int block = 0; block < 4; block++) {
reference_sad = ReferenceSAD(UINT_MAX, block);
EXPECT_EQ(exp_sad[block], reference_sad) << "block " << block;
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void CheckSADs() {
unsigned int reference_sad, exp_sad[4];
SADs(exp_sad);
for (int block = 0; block < 4; ++block) {
reference_sad = ReferenceSAD(block);
EXPECT_EQ(reference_sad, exp_sad[block]) << "block " << block;
}
}
| 174,569 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __poke_user(struct task_struct *child, addr_t addr, addr_t data)
{
struct user *dummy = NULL;
addr_t offset;
if (addr < (addr_t) &dummy->regs.acrs) {
/*
* psw and gprs are stored on the stack
*/
if (addr == (addr_t) &dummy->regs.psw.mask) {
unsigned long mask = PSW_MASK_USER;
mask |= is_ri_task(child) ? PSW_MASK_RI : 0;
if ((data & ~mask) != PSW_USER_BITS)
return -EINVAL;
if ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA))
return -EINVAL;
}
*(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data;
} else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) {
/*
* access registers are stored in the thread structure
*/
offset = addr - (addr_t) &dummy->regs.acrs;
#ifdef CONFIG_64BIT
/*
* Very special case: old & broken 64 bit gdb writing
* to acrs[15] with a 64 bit value. Ignore the lower
* half of the value and write the upper 32 bit to
* acrs[15]. Sick...
*/
if (addr == (addr_t) &dummy->regs.acrs[15])
child->thread.acrs[15] = (unsigned int) (data >> 32);
else
#endif
*(addr_t *)((addr_t) &child->thread.acrs + offset) = data;
} else if (addr == (addr_t) &dummy->regs.orig_gpr2) {
/*
* orig_gpr2 is stored on the kernel stack
*/
task_pt_regs(child)->orig_gpr2 = data;
} else if (addr < (addr_t) &dummy->regs.fp_regs) {
/*
* prevent writes of padding hole between
* orig_gpr2 and fp_regs on s390.
*/
return 0;
} else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) {
/*
* floating point regs. are stored in the thread structure
*/
if (addr == (addr_t) &dummy->regs.fp_regs.fpc)
if ((unsigned int) data != 0 ||
test_fp_ctl(data >> (BITS_PER_LONG - 32)))
return -EINVAL;
offset = addr - (addr_t) &dummy->regs.fp_regs;
*(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data;
} else if (addr < (addr_t) (&dummy->regs.per_info + 1)) {
/*
* Handle access to the per_info structure.
*/
addr -= (addr_t) &dummy->regs.per_info;
__poke_user_per(child, addr, data);
}
return 0;
}
Commit Message: s390/ptrace: fix PSW mask check
The PSW mask check of the PTRACE_POKEUSR_AREA command is incorrect.
The PSW_MASK_USER define contains the PSW_MASK_ASC bits, the ptrace
interface accepts all combinations for the address-space-control
bits. To protect the kernel space the PSW mask check in ptrace needs
to reject the address-space-control bit combination for home space.
Fixes CVE-2014-3534
Cc: [email protected]
Signed-off-by: Martin Schwidefsky <[email protected]>
CWE ID: CWE-264 | static int __poke_user(struct task_struct *child, addr_t addr, addr_t data)
{
struct user *dummy = NULL;
addr_t offset;
if (addr < (addr_t) &dummy->regs.acrs) {
/*
* psw and gprs are stored on the stack
*/
if (addr == (addr_t) &dummy->regs.psw.mask) {
unsigned long mask = PSW_MASK_USER;
mask |= is_ri_task(child) ? PSW_MASK_RI : 0;
if ((data ^ PSW_USER_BITS) & ~mask)
/* Invalid psw mask. */
return -EINVAL;
if ((data & PSW_MASK_ASC) == PSW_ASC_HOME)
/* Invalid address-space-control bits */
return -EINVAL;
if ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA))
/* Invalid addressing mode bits */
return -EINVAL;
}
*(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data;
} else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) {
/*
* access registers are stored in the thread structure
*/
offset = addr - (addr_t) &dummy->regs.acrs;
#ifdef CONFIG_64BIT
/*
* Very special case: old & broken 64 bit gdb writing
* to acrs[15] with a 64 bit value. Ignore the lower
* half of the value and write the upper 32 bit to
* acrs[15]. Sick...
*/
if (addr == (addr_t) &dummy->regs.acrs[15])
child->thread.acrs[15] = (unsigned int) (data >> 32);
else
#endif
*(addr_t *)((addr_t) &child->thread.acrs + offset) = data;
} else if (addr == (addr_t) &dummy->regs.orig_gpr2) {
/*
* orig_gpr2 is stored on the kernel stack
*/
task_pt_regs(child)->orig_gpr2 = data;
} else if (addr < (addr_t) &dummy->regs.fp_regs) {
/*
* prevent writes of padding hole between
* orig_gpr2 and fp_regs on s390.
*/
return 0;
} else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) {
/*
* floating point regs. are stored in the thread structure
*/
if (addr == (addr_t) &dummy->regs.fp_regs.fpc)
if ((unsigned int) data != 0 ||
test_fp_ctl(data >> (BITS_PER_LONG - 32)))
return -EINVAL;
offset = addr - (addr_t) &dummy->regs.fp_regs;
*(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data;
} else if (addr < (addr_t) (&dummy->regs.per_info + 1)) {
/*
* Handle access to the per_info structure.
*/
addr -= (addr_t) &dummy->regs.per_info;
__poke_user_per(child, addr, data);
}
return 0;
}
| 166,362 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _client_protocol_timeout (GsmXSMPClient *client)
{
g_debug ("GsmXSMPClient: client_protocol_timeout for client '%s' in ICE status %d",
client->priv->description,
IceConnectionStatus (client->priv->ice_connection));
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FAILED);
gsm_client_disconnected (GSM_CLIENT (client));
return FALSE;
}
Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211
CWE ID: CWE-835 | _client_protocol_timeout (GsmXSMPClient *client)
| 168,048 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_process_context_token(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t token_buffer)
{
OM_uint32 ret;
ret = gss_process_context_token(minor_status,
context_handle,
token_buffer);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_process_context_token(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_buffer_t token_buffer)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
/* SPNEGO doesn't have its own context tokens. */
if (!sc->opened)
return (GSS_S_DEFECTIVE_TOKEN);
ret = gss_process_context_token(minor_status,
sc->ctx_handle,
token_buffer);
return (ret);
}
| 166,663 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
mask->matte=MagickFalse;
channel_image=mask;
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
Commit Message: Added missing null check.
CWE ID: CWE-476 | static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
mask->matte=MagickFalse;
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
| 168,332 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 VideoTrack::Seek(
long long time_ns,
const BlockEntry*& pResult) const
{
const long status = GetFirst(pResult);
if (status < 0) //buffer underflow, etc
return status;
assert(pResult);
if (pResult->EOS())
return 0;
const Cluster* pCluster = pResult->GetCluster();
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
return 0;
Cluster** const clusters = m_pSegment->m_clusters;
assert(clusters);
const long count = m_pSegment->GetCount(); //loaded only, not pre-loaded
assert(count > 0);
Cluster** const i = clusters + pCluster->GetIndex();
assert(i);
assert(*i == pCluster);
assert(pCluster->GetTime() <= time_ns);
Cluster** const j = clusters + count;
Cluster** lo = i;
Cluster** hi = j;
while (lo < hi)
{
Cluster** const mid = lo + (hi - lo) / 2;
assert(mid < hi);
pCluster = *mid;
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
const long long t = pCluster->GetTime();
if (t <= time_ns)
lo = mid + 1;
else
hi = mid;
assert(lo <= hi);
}
assert(lo == hi);
assert(lo > i);
assert(lo <= j);
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
pResult = pCluster->GetEntry(this, time_ns);
if ((pResult != 0) && !pResult->EOS()) //found a keyframe
return 0;
while (lo != i)
{
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
#if 0
pResult = pCluster->GetMaxKey(this);
#else
pResult = pCluster->GetEntry(this, time_ns);
#endif
if ((pResult != 0) && !pResult->EOS())
return 0;
}
pResult = GetEOS();
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long VideoTrack::Seek(
if (status < 0)
return status;
if (rate <= 0)
return E_FILE_FORMAT_INVALID;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
VideoTrack* const pTrack =
new (std::nothrow) VideoTrack(pSegment, element_start, element_size);
if (pTrack == NULL)
return -1; // generic error
const int status = info.Copy(pTrack->m_info);
if (status) { // error
delete pTrack;
return status;
}
pTrack->m_width = width;
pTrack->m_height = height;
pTrack->m_rate = rate;
pResult = pTrack;
return 0; // success
}
bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const {
return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey();
}
long VideoTrack::Seek(long long time_ns, const BlockEntry*& pResult) const {
const long status = GetFirst(pResult);
if (status < 0) // buffer underflow, etc
return status;
assert(pResult);
if (pResult->EOS())
return 0;
const Cluster* pCluster = pResult->GetCluster();
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
return 0;
Cluster** const clusters = m_pSegment->m_clusters;
assert(clusters);
const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded
assert(count > 0);
Cluster** const i = clusters + pCluster->GetIndex();
assert(i);
assert(*i == pCluster);
assert(pCluster->GetTime() <= time_ns);
Cluster** const j = clusters + count;
Cluster** lo = i;
Cluster** hi = j;
while (lo < hi) {
// INVARIANT:
//[i, lo) <= time_ns
//[lo, hi) ?
//[hi, j) > time_ns
Cluster** const mid = lo + (hi - lo) / 2;
assert(mid < hi);
pCluster = *mid;
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
const long long t = pCluster->GetTime();
if (t <= time_ns)
lo = mid + 1;
else
hi = mid;
assert(lo <= hi);
}
assert(lo == hi);
assert(lo > i);
assert(lo <= j);
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
pResult = pCluster->GetEntry(this, time_ns);
if ((pResult != 0) && !pResult->EOS()) // found a keyframe
return 0;
while (lo != i) {
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
#if 0
pResult = pCluster->GetMaxKey(this);
#else
pResult = pCluster->GetEntry(this, time_ns);
#endif
if ((pResult != 0) && !pResult->EOS())
return 0;
}
// weird: we're on the first cluster, but no keyframe found
// should never happen but we must return something anyway
pResult = GetEOS();
return 0;
}
long long VideoTrack::GetWidth() const { return m_width; }
long long VideoTrack::GetHeight() const { return m_height; }
double VideoTrack::GetFrameRate() const { return m_rate; }
AudioTrack::AudioTrack(Segment* pSegment, long long element_start,
long long element_size)
: Track(pSegment, element_start, element_size) {}
long AudioTrack::Parse(Segment* pSegment, const Info& info,
long long element_start, long long element_size,
AudioTrack*& pResult) {
if (pResult)
return -1;
if (info.type != Track::kAudio)
return -1;
IMkvReader* const pReader = pSegment->m_pReader;
const Settings& s = info.settings;
assert(s.start >= 0);
assert(s.size >= 0);
long long pos = s.start;
assert(pos >= 0);
const long long stop = pos + s.size;
double rate = 8000.0; // MKV default
long long channels = 1;
long long bit_depth = 0;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x35) { // Sample Rate
status = UnserializeFloat(pReader, pos, size, rate);
if (status < 0)
return status;
if (rate <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x1F) { // Channel Count
channels = UnserializeUInt(pReader, pos, size);
if (channels <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x2264) { // Bit Depth
bit_depth = UnserializeUInt(pReader, pos, size);
if (bit_depth <= 0)
return E_FILE_FORMAT_INVALID;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
AudioTrack* const pTrack =
new (std::nothrow) AudioTrack(pSegment, element_start, element_size);
if (pTrack == NULL)
return -1; // generic error
const int status = info.Copy(pTrack->m_info);
if (status) {
delete pTrack;
return status;
}
pTrack->m_rate = rate;
pTrack->m_channels = channels;
pTrack->m_bitDepth = bit_depth;
pResult = pTrack;
return 0; // success
}
| 174,436 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 pcrypt_create_aead(struct crypto_template *tmpl, struct rtattr **tb,
u32 type, u32 mask)
{
struct pcrypt_instance_ctx *ctx;
struct crypto_attr_type *algt;
struct aead_instance *inst;
struct aead_alg *alg;
const char *name;
int err;
algt = crypto_get_attr_type(tb);
if (IS_ERR(algt))
return PTR_ERR(algt);
name = crypto_attr_alg_name(tb[1]);
if (IS_ERR(name))
return PTR_ERR(name);
inst = kzalloc(sizeof(*inst) + sizeof(*ctx), GFP_KERNEL);
if (!inst)
return -ENOMEM;
ctx = aead_instance_ctx(inst);
crypto_set_aead_spawn(&ctx->spawn, aead_crypto_instance(inst));
err = crypto_grab_aead(&ctx->spawn, name, 0, 0);
if (err)
goto out_free_inst;
alg = crypto_spawn_aead_alg(&ctx->spawn);
err = pcrypt_init_instance(aead_crypto_instance(inst), &alg->base);
if (err)
goto out_drop_aead;
inst->alg.base.cra_flags = CRYPTO_ALG_ASYNC;
inst->alg.ivsize = crypto_aead_alg_ivsize(alg);
inst->alg.maxauthsize = crypto_aead_alg_maxauthsize(alg);
inst->alg.base.cra_ctxsize = sizeof(struct pcrypt_aead_ctx);
inst->alg.init = pcrypt_aead_init_tfm;
inst->alg.exit = pcrypt_aead_exit_tfm;
inst->alg.setkey = pcrypt_aead_setkey;
inst->alg.setauthsize = pcrypt_aead_setauthsize;
inst->alg.encrypt = pcrypt_aead_encrypt;
inst->alg.decrypt = pcrypt_aead_decrypt;
err = aead_register_instance(tmpl, inst);
if (err)
goto out_drop_aead;
out:
return err;
out_drop_aead:
crypto_drop_aead(&ctx->spawn);
out_free_inst:
kfree(inst);
goto out;
}
Commit Message: crypto: pcrypt - fix freeing pcrypt instances
pcrypt is using the old way of freeing instances, where the ->free()
method specified in the 'struct crypto_template' is passed a pointer to
the 'struct crypto_instance'. But the crypto_instance is being
kfree()'d directly, which is incorrect because the memory was actually
allocated as an aead_instance, which contains the crypto_instance at a
nonzero offset. Thus, the wrong pointer was being kfree()'d.
Fix it by switching to the new way to free aead_instance's where the
->free() method is specified in the aead_instance itself.
Reported-by: syzbot <[email protected]>
Fixes: 0496f56065e0 ("crypto: pcrypt - Add support for new AEAD interface")
Cc: <[email protected]> # v4.2+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-763 | static int pcrypt_create_aead(struct crypto_template *tmpl, struct rtattr **tb,
u32 type, u32 mask)
{
struct pcrypt_instance_ctx *ctx;
struct crypto_attr_type *algt;
struct aead_instance *inst;
struct aead_alg *alg;
const char *name;
int err;
algt = crypto_get_attr_type(tb);
if (IS_ERR(algt))
return PTR_ERR(algt);
name = crypto_attr_alg_name(tb[1]);
if (IS_ERR(name))
return PTR_ERR(name);
inst = kzalloc(sizeof(*inst) + sizeof(*ctx), GFP_KERNEL);
if (!inst)
return -ENOMEM;
ctx = aead_instance_ctx(inst);
crypto_set_aead_spawn(&ctx->spawn, aead_crypto_instance(inst));
err = crypto_grab_aead(&ctx->spawn, name, 0, 0);
if (err)
goto out_free_inst;
alg = crypto_spawn_aead_alg(&ctx->spawn);
err = pcrypt_init_instance(aead_crypto_instance(inst), &alg->base);
if (err)
goto out_drop_aead;
inst->alg.base.cra_flags = CRYPTO_ALG_ASYNC;
inst->alg.ivsize = crypto_aead_alg_ivsize(alg);
inst->alg.maxauthsize = crypto_aead_alg_maxauthsize(alg);
inst->alg.base.cra_ctxsize = sizeof(struct pcrypt_aead_ctx);
inst->alg.init = pcrypt_aead_init_tfm;
inst->alg.exit = pcrypt_aead_exit_tfm;
inst->alg.setkey = pcrypt_aead_setkey;
inst->alg.setauthsize = pcrypt_aead_setauthsize;
inst->alg.encrypt = pcrypt_aead_encrypt;
inst->alg.decrypt = pcrypt_aead_decrypt;
inst->free = pcrypt_free;
err = aead_register_instance(tmpl, inst);
if (err)
goto out_drop_aead;
out:
return err;
out_drop_aead:
crypto_drop_aead(&ctx->spawn);
out_free_inst:
kfree(inst);
goto out;
}
| 169,424 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile)
{
gdIOCtx *out = gdNewFileCtx(outFile);
if (out == NULL) {
return;
}
gdImageWebpCtx(im, out, -1);
out->gd_free(out);
}
Commit Message: Fix double-free in gdImageWebPtr()
The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and
the other WebP output functions to do the real work) does not return whether
it succeeded or failed, so this is not checked in gdImageWebpPtr() and the
function wrongly assumes everything is okay, which is not, in this case,
because there is a size limitation for WebP, namely that the width and
height must by less than 16383.
We can't change the signature of gdImageWebpCtx() for API compatibility
reasons, so we introduce the static helper _gdImageWebpCtx() which returns
success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can
check the return value. We leave it solely to libwebp for now to report
warnings regarding the failing write.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6912
CWE ID: CWE-415 | BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile)
{
gdIOCtx *out = gdNewFileCtx(outFile);
if (out == NULL) {
return;
}
_gdImageWebpCtx(im, out, -1);
out->gd_free(out);
}
| 168,816 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: char *strstr(char *s1, char *s2)
{ /* from libiberty */
char *p;
int len = strlen(s2);
if (*s2 == '\0') /* everything matches empty string */
return s1;
for (p = s1; (p = strchr(p, *s2)) != NULL; p = strchr(p + 1, *s2)) {
if (strncmp(p, s2, len) == 0)
return (p);
}
return NULL;
}
Commit Message: misc oom and possible memory leak fix
CWE ID: | char *strstr(char *s1, char *s2)
{ /* from libiberty */
char *p;
int len = strlen(s2);
if (*s2 == '\0') /* everything matches empty string */
return s1;
for (p = s1; (p = strchr(p, *s2)) != NULL; p++) {
if (strncmp(p, s2, len) == 0)
return (p);
}
return NULL;
}
| 169,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: IndexedDBCursor::~IndexedDBCursor() {
Close();
}
Commit Message: [IndexedDB] Fix Cursor UAF
If the connection is closed before we return a cursor, it dies in
IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on
the correct thread, but we also need to makes sure to remove it from its
transaction.
To make things simpler, we have the cursor remove itself from its
transaction on destruction.
R: [email protected]
Bug: 728887
Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2
Reviewed-on: https://chromium-review.googlesource.com/526284
Commit-Queue: Daniel Murphy <[email protected]>
Reviewed-by: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#477504}
CWE ID: CWE-416 | IndexedDBCursor::~IndexedDBCursor() {
if (transaction_)
transaction_->UnregisterOpenCursor(this);
Close();
}
| 172,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int64 GetOriginalListPrefValue(size_t index) {
return ListPrefInt64Value(*original_update_, index);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | int64 GetOriginalListPrefValue(size_t index) {
return original_.GetListPrefValue(index);
}
| 171,323 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ztype(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
ref tnref;
int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref);
if (code < 0)
return code;
if (!r_has_type(&tnref, t_name)) {
/* Must be either a stack underflow or a t_[a]struct. */
check_op(2);
{ /* Get the type name from the structure. */
if (op[-1].value.pstruct != 0x00) {
const char *sname =
gs_struct_type_name_string(gs_object_type(imemory,
op[-1].value.pstruct));
int code = name_ref(imemory, (const byte *)sname, strlen(sname),
(ref *) (op - 1), 0);
if (code < 0)
return code;
} else
return_error(gs_error_stackunderflow);
}
r_set_attrs(op - 1, a_executable);
} else {
ref_assign(op - 1, &tnref);
}
pop(1);
return 0;
}
Commit Message:
CWE ID: CWE-704 | ztype(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
ref tnref;
int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref);
if (code < 0)
return code;
if (!r_has_type(&tnref, t_name)) {
/* Must be either a stack underflow or a t_[a]struct. */
check_op(2);
{ /* Get the type name from the structure. */
if ((r_has_type(&op[-1], t_struct) || r_has_type(&op[-1], t_astruct)) && op[-1].value.pstruct != 0x00) {
const char *sname =
gs_struct_type_name_string(gs_object_type(imemory,
op[-1].value.pstruct));
int code = name_ref(imemory, (const byte *)sname, strlen(sname),
(ref *) (op - 1), 0);
if (code < 0)
return code;
} else
return_error(gs_error_stackunderflow);
}
r_set_attrs(op - 1, a_executable);
} else {
ref_assign(op - 1, &tnref);
}
pop(1);
return 0;
}
| 164,698 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: error::Error GLES2DecoderPassthroughImpl::DoEndQueryEXT(GLenum target,
uint32_t submit_count) {
if (IsEmulatedQueryTarget(target)) {
auto active_query_iter = active_queries_.find(target);
if (active_query_iter == active_queries_.end()) {
InsertError(GL_INVALID_OPERATION, "No active query on target.");
return error::kNoError;
}
if (target == GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM &&
!pending_read_pixels_.empty()) {
GLuint query_service_id = active_query_iter->second.service_id;
pending_read_pixels_.back().waiting_async_pack_queries.insert(
query_service_id);
}
} else {
CheckErrorCallbackState();
api()->glEndQueryFn(target);
if (CheckErrorCallbackState()) {
return error::kNoError;
}
}
DCHECK(active_queries_.find(target) != active_queries_.end());
ActiveQuery active_query = std::move(active_queries_[target]);
active_queries_.erase(target);
PendingQuery pending_query;
pending_query.target = target;
pending_query.service_id = active_query.service_id;
pending_query.shm = std::move(active_query.shm);
pending_query.sync = active_query.sync;
pending_query.submit_count = submit_count;
switch (target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
pending_query.commands_completed_fence = gl::GLFence::Create();
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
pending_query.buffer_shadow_update_fence = gl::GLFence::Create();
pending_query.buffer_shadow_updates = std::move(buffer_shadow_updates_);
buffer_shadow_updates_.clear();
break;
default:
break;
}
pending_queries_.push_back(std::move(pending_query));
return ProcessQueries(false);
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | error::Error GLES2DecoderPassthroughImpl::DoEndQueryEXT(GLenum target,
uint32_t submit_count) {
if (IsEmulatedQueryTarget(target)) {
auto active_query_iter = active_queries_.find(target);
if (active_query_iter == active_queries_.end()) {
InsertError(GL_INVALID_OPERATION, "No active query on target.");
return error::kNoError;
}
if (target == GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM &&
!pending_read_pixels_.empty()) {
GLuint query_service_id = active_query_iter->second.service_id;
pending_read_pixels_.back().waiting_async_pack_queries.insert(
query_service_id);
}
} else {
CheckErrorCallbackState();
api()->glEndQueryFn(target);
if (CheckErrorCallbackState()) {
return error::kNoError;
}
}
DCHECK(active_queries_.find(target) != active_queries_.end());
ActiveQuery active_query = std::move(active_queries_[target]);
active_queries_.erase(target);
PendingQuery pending_query;
pending_query.target = target;
pending_query.service_id = active_query.service_id;
pending_query.shm = std::move(active_query.shm);
pending_query.sync = active_query.sync;
pending_query.submit_count = submit_count;
switch (target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
pending_query.commands_completed_fence = gl::GLFence::Create();
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
pending_query.buffer_shadow_update_fence = gl::GLFence::Create();
pending_query.buffer_shadow_updates = std::move(buffer_shadow_updates_);
buffer_shadow_updates_.clear();
break;
case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM:
pending_query.program_service_id = linking_program_service_id_;
break;
default:
break;
}
pending_queries_.push_back(std::move(pending_query));
return ProcessQueries(false);
}
| 172,533 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PreProcessingFx_ProcessReverse(effect_handle_t self,
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer)
{
preproc_effect_t * effect = (preproc_effect_t *)self;
int status = 0;
if (effect == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL");
return -EINVAL;
}
preproc_session_t * session = (preproc_session_t *)effect->session;
if (inBuffer == NULL || inBuffer->raw == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer");
return -EINVAL;
}
session->revProcessedMsk |= (1<<effect->procId);
if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) {
effect->session->revProcessedMsk = 0;
if (session->revResampler != NULL) {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
if (session->revBufSize < session->framesRev + fr) {
session->revBufSize = session->framesRev + fr;
session->revBuf = (int16_t *)realloc(session->revBuf,
session->revBufSize * session->inChannelCount * sizeof(int16_t));
}
memcpy(session->revBuf + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
spx_uint32_t frIn = session->framesRev;
spx_uint32_t frOut = session->apmFrameCount;
if (session->inChannelCount == 1) {
speex_resampler_process_int(session->revResampler,
0,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
} else {
speex_resampler_process_interleaved_int(session->revResampler,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
}
memcpy(session->revBuf,
session->revBuf + frIn * session->inChannelCount,
(session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t));
session->framesRev -= frIn;
} else {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
memcpy(session->revFrame->_payloadData + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
session->framesRev = 0;
}
session->revFrame->_payloadDataLengthInSamples =
session->apmFrameCount * session->inChannelCount;
effect->session->apm->AnalyzeReverseStream(session->revFrame);
return 0;
} else {
return -ENODATA;
}
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119 | int PreProcessingFx_ProcessReverse(effect_handle_t self,
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer __unused)
{
preproc_effect_t * effect = (preproc_effect_t *)self;
int status = 0;
if (effect == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL");
return -EINVAL;
}
preproc_session_t * session = (preproc_session_t *)effect->session;
if (inBuffer == NULL || inBuffer->raw == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer");
return -EINVAL;
}
session->revProcessedMsk |= (1<<effect->procId);
if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) {
effect->session->revProcessedMsk = 0;
if (session->revResampler != NULL) {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
if (session->revBufSize < session->framesRev + fr) {
session->revBufSize = session->framesRev + fr;
session->revBuf = (int16_t *)realloc(session->revBuf,
session->revBufSize * session->inChannelCount * sizeof(int16_t));
}
memcpy(session->revBuf + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
spx_uint32_t frIn = session->framesRev;
spx_uint32_t frOut = session->apmFrameCount;
if (session->inChannelCount == 1) {
speex_resampler_process_int(session->revResampler,
0,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
} else {
speex_resampler_process_interleaved_int(session->revResampler,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
}
memcpy(session->revBuf,
session->revBuf + frIn * session->inChannelCount,
(session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t));
session->framesRev -= frIn;
} else {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
memcpy(session->revFrame->_payloadData + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
session->framesRev = 0;
}
session->revFrame->_payloadDataLengthInSamples =
session->apmFrameCount * session->inChannelCount;
effect->session->apm->AnalyzeReverseStream(session->revFrame);
return 0;
} else {
return -ENODATA;
}
}
| 173,354 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNConversionResult IDNToUnicodeWithAdjustmentsImpl(
base::StringPiece host,
base::OffsetAdjuster::Adjustments* adjustments,
bool enable_spoof_checks) {
if (adjustments)
adjustments->clear();
base::string16 input16;
input16.reserve(host.length());
input16.insert(input16.end(), host.begin(), host.end());
bool is_tld_ascii = true;
size_t last_dot = host.rfind('.');
if (last_dot != base::StringPiece::npos &&
host.substr(last_dot).starts_with(".xn--")) {
is_tld_ascii = false;
}
IDNConversionResult result;
base::string16 out16;
for (size_t component_start = 0, component_end;
component_start < input16.length();
component_start = component_end + 1) {
component_end = input16.find('.', component_start);
if (component_end == base::string16::npos)
component_end = input16.length(); // For getting the last component.
size_t component_length = component_end - component_start;
size_t new_component_start = out16.length();
bool converted_idn = false;
if (component_end > component_start) {
bool has_idn_component = false;
converted_idn = IDNToUnicodeOneComponent(
input16.data() + component_start, component_length, is_tld_ascii,
enable_spoof_checks, &out16, &has_idn_component);
result.has_idn_component |= has_idn_component;
}
size_t new_component_length = out16.length() - new_component_start;
if (converted_idn && adjustments) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
component_start, component_length, new_component_length));
}
if (component_end < input16.length())
out16.push_back('.');
}
result.result = out16;
if (result.has_idn_component) {
result.matching_top_domain =
g_idn_spoof_checker.Get().GetSimilarTopDomain(out16);
if (enable_spoof_checks && !result.matching_top_domain.domain.empty()) {
if (adjustments)
adjustments->clear();
result.result = input16;
}
}
return result;
}
Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains
This character (þ) can be confused with both b and p when used in a domain
name. IDN spoof checker doesn't have a good way of flagging a character as
confusable with multiple characters, so it can't catch spoofs containing
this character. As a practical fix, this CL restricts this character to
domains under Iceland's ccTLD (.is). With this change, a domain name containing
"þ" with a non-.is TLD will be displayed in punycode in the UI.
This change affects less than 10 real world domains with limited popularity.
Bug: 798892, 843352, 904327, 1017707
Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Christopher Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#709309}
CWE ID: | IDNConversionResult IDNToUnicodeWithAdjustmentsImpl(
base::StringPiece host,
base::OffsetAdjuster::Adjustments* adjustments,
bool enable_spoof_checks) {
if (adjustments)
adjustments->clear();
base::string16 input16;
input16.reserve(host.length());
input16.insert(input16.end(), host.begin(), host.end());
base::StringPiece top_level_domain;
size_t last_dot = host.rfind('.');
if (last_dot != base::StringPiece::npos) {
top_level_domain = host.substr(last_dot);
}
IDNConversionResult result;
base::string16 out16;
for (size_t component_start = 0, component_end;
component_start < input16.length();
component_start = component_end + 1) {
component_end = input16.find('.', component_start);
if (component_end == base::string16::npos)
component_end = input16.length(); // For getting the last component.
size_t component_length = component_end - component_start;
size_t new_component_start = out16.length();
bool converted_idn = false;
if (component_end > component_start) {
bool has_idn_component = false;
converted_idn = IDNToUnicodeOneComponent(
input16.data() + component_start, component_length, top_level_domain,
enable_spoof_checks, &out16, &has_idn_component);
result.has_idn_component |= has_idn_component;
}
size_t new_component_length = out16.length() - new_component_start;
if (converted_idn && adjustments) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
component_start, component_length, new_component_length));
}
if (component_end < input16.length())
out16.push_back('.');
}
result.result = out16;
if (result.has_idn_component) {
result.matching_top_domain =
g_idn_spoof_checker.Get().GetSimilarTopDomain(out16);
if (enable_spoof_checks && !result.matching_top_domain.domain.empty()) {
if (adjustments)
adjustments->clear();
result.result = input16;
}
}
return result;
}
| 172,729 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE)));
return NULL;
}
| 167,792 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RBinAddr *entry = NULL;
int i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
if (inifin) {
r_cons_printf ("[Constructors]\n");
} else {
r_cons_printf ("[Entrypoints]\n");
}
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 haddr = UT64_MAX;
if (mode != R_CORE_BIN_SET) {
if (inifin) {
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
} else {
if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
}
}
switch (entry->type) {
case R_BIN_ENTRY_TYPE_INIT:
case R_BIN_ENTRY_TYPE_FINI:
case R_BIN_ENTRY_TYPE_PREINIT:
if (r->io->va && entry->paddr == entry->vaddr) {
RIOMap *map = r_io_map_get (r->io, entry->vaddr);
if (map) {
paddr = entry->vaddr - map->itv.addr + map->delta;
}
}
}
if (entry->haddr) {
haddr = entry->haddr;
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.preinit", i);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
}
r_flag_set (r->flags, str, at, 1);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64d ","
"\"paddr\":%" PFMT64d ","
"\"baddr\":%" PFMT64d ","
"\"laddr\":%" PFMT64d ","
"\"haddr\":%" PFMT64d ","
"\"type\":\"%s\"}",
iter->p ? "," : "", at, paddr, baddr, laddr, haddr, type);
} else if (IS_MODE_RAD (mode)) {
char *name = NULL;
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
name = r_str_newf ("entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
name = r_str_newf ("entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
name = r_str_newf ("entry%i.preinit", i);
} else {
name = r_str_newf ("entry%i", i);
}
r_cons_printf ("f %s 1 @ 0x%08"PFMT64x"\n", name, at);
r_cons_printf ("f %s_haddr 1 @ 0x%08"PFMT64x"\n", name, haddr);
r_cons_printf ("s %s\n", name);
free (name);
} else {
r_cons_printf (
"vaddr=0x%08"PFMT64x
" paddr=0x%08"PFMT64x
" baddr=0x%08"PFMT64x
" laddr=0x%08"PFMT64x,
at, paddr, baddr, laddr);
if (haddr == UT64_MAX) {
r_cons_printf (
" haddr=%"PFMT64d
" type=%s\n",
haddr, type);
} else {
r_cons_printf (
" haddr=0x%08"PFMT64x
" type=%s\n",
haddr, type);
}
}
i++;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", i);
}
return true;
}
Commit Message: Fix #9904 - crash in r2_hoobr_r_read_le32 (over 9000 entrypoints) and read_le oobread (#9923)
CWE ID: CWE-125 | static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RBinAddr *entry = NULL;
int i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
if (inifin) {
r_cons_printf ("[Constructors]\n");
} else {
r_cons_printf ("[Entrypoints]\n");
}
}
if (r_list_length (entries) > 1024) {
eprintf ("Too many entrypoints (%d)\n", r_list_length (entries));
return false;
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 haddr = UT64_MAX;
if (mode != R_CORE_BIN_SET) {
if (inifin) {
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
} else {
if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
}
}
switch (entry->type) {
case R_BIN_ENTRY_TYPE_INIT:
case R_BIN_ENTRY_TYPE_FINI:
case R_BIN_ENTRY_TYPE_PREINIT:
if (r->io->va && entry->paddr == entry->vaddr) {
RIOMap *map = r_io_map_get (r->io, entry->vaddr);
if (map) {
paddr = entry->vaddr - map->itv.addr + map->delta;
}
}
}
if (entry->haddr) {
haddr = entry->haddr;
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.preinit", i);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
}
r_flag_set (r->flags, str, at, 1);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64d ","
"\"paddr\":%" PFMT64d ","
"\"baddr\":%" PFMT64d ","
"\"laddr\":%" PFMT64d ","
"\"haddr\":%" PFMT64d ","
"\"type\":\"%s\"}",
iter->p ? "," : "", at, paddr, baddr, laddr, haddr, type);
} else if (IS_MODE_RAD (mode)) {
char *name = NULL;
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
name = r_str_newf ("entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
name = r_str_newf ("entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
name = r_str_newf ("entry%i.preinit", i);
} else {
name = r_str_newf ("entry%i", i);
}
r_cons_printf ("f %s 1 @ 0x%08"PFMT64x"\n", name, at);
r_cons_printf ("f %s_haddr 1 @ 0x%08"PFMT64x"\n", name, haddr);
r_cons_printf ("s %s\n", name);
free (name);
} else {
r_cons_printf (
"vaddr=0x%08"PFMT64x
" paddr=0x%08"PFMT64x
" baddr=0x%08"PFMT64x
" laddr=0x%08"PFMT64x,
at, paddr, baddr, laddr);
if (haddr == UT64_MAX) {
r_cons_printf (
" haddr=%"PFMT64d
" type=%s\n",
haddr, type);
} else {
r_cons_printf (
" haddr=0x%08"PFMT64x
" type=%s\n",
haddr, type);
}
}
i++;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", i);
}
return true;
}
| 169,233 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res, resIp;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
resIp.value = 0;
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete)
{
res.flags.IpOK = FALSE;
res.flags.IpFailed = TRUE;
return res;
}
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
| 168,887 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftGSM::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
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) {
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 (inHeader->nFilledLen > kMaxNumSamplesPerFrame) {
ALOGE("input buffer too large (%d).", inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
}
if(((inHeader->nFilledLen / kMSGSMFrameSize) * kMSGSMFrameSize) != inHeader->nFilledLen) {
ALOGE("input buffer not multiple of %d (%d).", kMSGSMFrameSize, inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
}
uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset;
int n = mSignalledError ? 0 : DecodeGSM(mGsm,
reinterpret_cast<int16_t *>(outHeader->pBuffer), inputptr, inHeader->nFilledLen);
outHeader->nTimeStamp = inHeader->nTimeStamp;
outHeader->nOffset = 0;
outHeader->nFilledLen = n * sizeof(int16_t);
outHeader->nFlags = 0;
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
Commit Message: codecs: check OMX buffer size before use in (gsm|g711)dec
Bug: 27793163
Bug: 27793367
Change-Id: Iec3de8a237ee2379d87a8371c13e543878c6652c
CWE ID: CWE-119 | void SoftGSM::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
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) {
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 (inHeader->nFilledLen > kMaxNumSamplesPerFrame) {
ALOGE("input buffer too large (%d).", inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
}
if(((inHeader->nFilledLen / kMSGSMFrameSize) * kMSGSMFrameSize) != inHeader->nFilledLen) {
ALOGE("input buffer not multiple of %d (%d).", kMSGSMFrameSize, inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
}
if (outHeader->nAllocLen < (inHeader->nFilledLen / kMSGSMFrameSize) * 320) {
ALOGE("output buffer is not large enough (%d).", outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "27793367");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset;
int n = mSignalledError ? 0 : DecodeGSM(mGsm,
reinterpret_cast<int16_t *>(outHeader->pBuffer), inputptr, inHeader->nFilledLen);
outHeader->nTimeStamp = inHeader->nTimeStamp;
outHeader->nOffset = 0;
outHeader->nFilledLen = n * sizeof(int16_t);
outHeader->nFlags = 0;
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
| 173,779 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionUninstaller::Run() {
const extensions::Extension* extension =
extensions::ExtensionSystem::Get(profile_)->extension_service()->
GetInstalledExtension(app_id_);
if (!extension) {
CleanUp();
return;
}
controller_->OnShowChildDialog();
dialog_.reset(extensions::ExtensionUninstallDialog::Create(
profile_, controller_->GetAppListWindow(), this));
dialog_->ConfirmUninstall(extension,
extensions::UNINSTALL_REASON_USER_INITIATED);
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID: | void ExtensionUninstaller::Run() {
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(profile_)->GetInstalledExtension(
app_id_);
if (!extension) {
CleanUp();
return;
}
controller_->OnShowChildDialog();
dialog_.reset(extensions::ExtensionUninstallDialog::Create(
profile_, controller_->GetAppListWindow(), this));
dialog_->ConfirmUninstall(extension,
extensions::UNINSTALL_REASON_USER_INITIATED);
}
| 171,724 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ConvolveFunctions(convolve_fn_t h8, convolve_fn_t h8_avg,
convolve_fn_t v8, convolve_fn_t v8_avg,
convolve_fn_t hv8, convolve_fn_t hv8_avg)
: h8_(h8), v8_(v8), hv8_(hv8), h8_avg_(h8_avg), v8_avg_(v8_avg),
hv8_avg_(hv8_avg) {}
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 | ConvolveFunctions(convolve_fn_t h8, convolve_fn_t h8_avg,
| 174,503 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void rose_loopback_timer(unsigned long param)
{
struct sk_buff *skb;
struct net_device *dev;
rose_address *dest;
struct sock *sk;
unsigned short frametype;
unsigned int lci_i, lci_o;
while ((skb = skb_dequeue(&loopback_queue)) != NULL) {
lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);
frametype = skb->data[2];
dest = (rose_address *)(skb->data + 4);
lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i;
skb_reset_transport_header(skb);
sk = rose_find_socket(lci_o, rose_loopback_neigh);
if (sk) {
if (rose_process_rx_frame(sk, skb) == 0)
kfree_skb(skb);
continue;
}
if (frametype == ROSE_CALL_REQUEST) {
if ((dev = rose_dev_get(dest)) != NULL) {
if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0)
kfree_skb(skb);
} else {
kfree_skb(skb);
}
} else {
kfree_skb(skb);
}
}
}
Commit Message: rose: Add length checks to CALL_REQUEST parsing
Define some constant offsets for CALL_REQUEST based on the description
at <http://www.techfest.com/networking/wan/x25plp.htm> and the
definition of ROSE as using 10-digit (5-byte) addresses. Use them
consistently. Validate all implicit and explicit facilities lengths.
Validate the address length byte rather than either trusting or
assuming its value.
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static void rose_loopback_timer(unsigned long param)
{
struct sk_buff *skb;
struct net_device *dev;
rose_address *dest;
struct sock *sk;
unsigned short frametype;
unsigned int lci_i, lci_o;
while ((skb = skb_dequeue(&loopback_queue)) != NULL) {
if (skb->len < ROSE_MIN_LEN) {
kfree_skb(skb);
continue;
}
lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);
frametype = skb->data[2];
if (frametype == ROSE_CALL_REQUEST &&
(skb->len <= ROSE_CALL_REQ_FACILITIES_OFF ||
skb->data[ROSE_CALL_REQ_ADDR_LEN_OFF] !=
ROSE_CALL_REQ_ADDR_LEN_VAL)) {
kfree_skb(skb);
continue;
}
dest = (rose_address *)(skb->data + ROSE_CALL_REQ_DEST_ADDR_OFF);
lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i;
skb_reset_transport_header(skb);
sk = rose_find_socket(lci_o, rose_loopback_neigh);
if (sk) {
if (rose_process_rx_frame(sk, skb) == 0)
kfree_skb(skb);
continue;
}
if (frametype == ROSE_CALL_REQUEST) {
if ((dev = rose_dev_get(dest)) != NULL) {
if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0)
kfree_skb(skb);
} else {
kfree_skb(skb);
}
} else {
kfree_skb(skb);
}
}
}
| 165,670 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ScriptProcessorHandler::Process(size_t frames_to_process) {
AudioBus* input_bus = Input(0).Bus();
AudioBus* output_bus = Output(0).Bus();
unsigned double_buffer_index = this->DoubleBufferIndex();
bool is_double_buffer_index_good =
double_buffer_index < 2 && double_buffer_index < input_buffers_.size() &&
double_buffer_index < output_buffers_.size();
DCHECK(is_double_buffer_index_good);
if (!is_double_buffer_index_good)
return;
AudioBuffer* input_buffer = input_buffers_[double_buffer_index].Get();
AudioBuffer* output_buffer = output_buffers_[double_buffer_index].Get();
unsigned number_of_input_channels = internal_input_bus_->NumberOfChannels();
bool buffers_are_good =
output_buffer && BufferSize() == output_buffer->length() &&
buffer_read_write_index_ + frames_to_process <= BufferSize();
if (internal_input_bus_->NumberOfChannels())
buffers_are_good = buffers_are_good && input_buffer &&
BufferSize() == input_buffer->length();
DCHECK(buffers_are_good);
if (!buffers_are_good)
return;
bool is_frames_to_process_good = frames_to_process &&
BufferSize() >= frames_to_process &&
!(BufferSize() % frames_to_process);
DCHECK(is_frames_to_process_good);
if (!is_frames_to_process_good)
return;
unsigned number_of_output_channels = output_bus->NumberOfChannels();
bool channels_are_good =
(number_of_input_channels == number_of_input_channels_) &&
(number_of_output_channels == number_of_output_channels_);
DCHECK(channels_are_good);
if (!channels_are_good)
return;
for (unsigned i = 0; i < number_of_input_channels; ++i)
internal_input_bus_->SetChannelMemory(
i,
input_buffer->getChannelData(i).View()->Data() +
buffer_read_write_index_,
frames_to_process);
if (number_of_input_channels)
internal_input_bus_->CopyFrom(*input_bus);
for (unsigned i = 0; i < number_of_output_channels; ++i) {
memcpy(output_bus->Channel(i)->MutableData(),
output_buffer->getChannelData(i).View()->Data() +
buffer_read_write_index_,
sizeof(float) * frames_to_process);
}
buffer_read_write_index_ =
(buffer_read_write_index_ + frames_to_process) % BufferSize();
if (!buffer_read_write_index_) {
MutexTryLocker try_locker(process_event_lock_);
if (!try_locker.Locked()) {
output_buffer->Zero();
} else if (Context()->GetExecutionContext()) {
if (Context()->HasRealtimeConstraint()) {
TaskRunnerHelper::Get(TaskType::kMediaElementEvent,
Context()->GetExecutionContext())
->PostTask(BLINK_FROM_HERE,
CrossThreadBind(
&ScriptProcessorHandler::FireProcessEvent,
CrossThreadUnretained(this), double_buffer_index_));
} else {
std::unique_ptr<WaitableEvent> waitable_event =
WTF::MakeUnique<WaitableEvent>();
TaskRunnerHelper::Get(TaskType::kMediaElementEvent,
Context()->GetExecutionContext())
->PostTask(BLINK_FROM_HERE,
CrossThreadBind(
&ScriptProcessorHandler::
FireProcessEventForOfflineAudioContext,
CrossThreadUnretained(this), double_buffer_index_,
CrossThreadUnretained(waitable_event.get())));
waitable_event->Wait();
}
}
SwapBuffers();
}
}
Commit Message: Keep ScriptProcessorHandler alive across threads
When posting a task from the ScriptProcessorHandler::Process to fire a
process event, we need to keep the handler alive in case the
ScriptProcessorNode goes away (because it has no onaudioprocess
handler) and removes the its handler.
Bug: 765495
Test:
Change-Id: Ib4fa39d7b112c7051897700a1eff9f59a4a7a054
Reviewed-on: https://chromium-review.googlesource.com/677137
Reviewed-by: Hongchan Choi <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Commit-Queue: Raymond Toy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#503629}
CWE ID: CWE-416 | void ScriptProcessorHandler::Process(size_t frames_to_process) {
AudioBus* input_bus = Input(0).Bus();
AudioBus* output_bus = Output(0).Bus();
unsigned double_buffer_index = this->DoubleBufferIndex();
bool is_double_buffer_index_good =
double_buffer_index < 2 && double_buffer_index < input_buffers_.size() &&
double_buffer_index < output_buffers_.size();
DCHECK(is_double_buffer_index_good);
if (!is_double_buffer_index_good)
return;
AudioBuffer* input_buffer = input_buffers_[double_buffer_index].Get();
AudioBuffer* output_buffer = output_buffers_[double_buffer_index].Get();
unsigned number_of_input_channels = internal_input_bus_->NumberOfChannels();
bool buffers_are_good =
output_buffer && BufferSize() == output_buffer->length() &&
buffer_read_write_index_ + frames_to_process <= BufferSize();
if (internal_input_bus_->NumberOfChannels())
buffers_are_good = buffers_are_good && input_buffer &&
BufferSize() == input_buffer->length();
DCHECK(buffers_are_good);
if (!buffers_are_good)
return;
bool is_frames_to_process_good = frames_to_process &&
BufferSize() >= frames_to_process &&
!(BufferSize() % frames_to_process);
DCHECK(is_frames_to_process_good);
if (!is_frames_to_process_good)
return;
unsigned number_of_output_channels = output_bus->NumberOfChannels();
bool channels_are_good =
(number_of_input_channels == number_of_input_channels_) &&
(number_of_output_channels == number_of_output_channels_);
DCHECK(channels_are_good);
if (!channels_are_good)
return;
for (unsigned i = 0; i < number_of_input_channels; ++i)
internal_input_bus_->SetChannelMemory(
i,
input_buffer->getChannelData(i).View()->Data() +
buffer_read_write_index_,
frames_to_process);
if (number_of_input_channels)
internal_input_bus_->CopyFrom(*input_bus);
for (unsigned i = 0; i < number_of_output_channels; ++i) {
memcpy(output_bus->Channel(i)->MutableData(),
output_buffer->getChannelData(i).View()->Data() +
buffer_read_write_index_,
sizeof(float) * frames_to_process);
}
buffer_read_write_index_ =
(buffer_read_write_index_ + frames_to_process) % BufferSize();
if (!buffer_read_write_index_) {
MutexTryLocker try_locker(process_event_lock_);
if (!try_locker.Locked()) {
output_buffer->Zero();
} else if (Context()->GetExecutionContext()) {
if (Context()->HasRealtimeConstraint()) {
TaskRunnerHelper::Get(TaskType::kMediaElementEvent,
Context()->GetExecutionContext())
->PostTask(
BLINK_FROM_HERE,
CrossThreadBind(&ScriptProcessorHandler::FireProcessEvent,
WrapRefPtr(this), double_buffer_index_));
} else {
std::unique_ptr<WaitableEvent> waitable_event =
WTF::MakeUnique<WaitableEvent>();
TaskRunnerHelper::Get(TaskType::kMediaElementEvent,
Context()->GetExecutionContext())
->PostTask(
BLINK_FROM_HERE,
CrossThreadBind(&ScriptProcessorHandler::
FireProcessEventForOfflineAudioContext,
WrapRefPtr(this), double_buffer_index_,
CrossThreadUnretained(waitable_event.get())));
waitable_event->Wait();
}
}
SwapBuffers();
}
}
| 172,943 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_pixel_setf(image_pixel *this, unsigned int max)
{
this->redf = this->red / (double)max;
this->greenf = this->green / (double)max;
this->bluef = this->blue / (double)max;
this->alphaf = this->alpha / (double)max;
if (this->red < max)
this->rede = this->redf * DBL_EPSILON;
else
this->rede = 0;
if (this->green < max)
this->greene = this->greenf * DBL_EPSILON;
else
this->greene = 0;
if (this->blue < max)
this->bluee = this->bluef * DBL_EPSILON;
else
this->bluee = 0;
if (this->alpha < max)
this->alphae = this->alphaf * DBL_EPSILON;
else
this->alphae = 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_pixel_setf(image_pixel *this, unsigned int max)
image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax,
unsigned int bMax, unsigned int aMax)
{
this->redf = this->red / (double)rMax;
this->greenf = this->green / (double)gMax;
this->bluef = this->blue / (double)bMax;
this->alphaf = this->alpha / (double)aMax;
if (this->red < rMax)
this->rede = this->redf * DBL_EPSILON;
else
this->rede = 0;
if (this->green < gMax)
this->greene = this->greenf * DBL_EPSILON;
else
this->greene = 0;
if (this->blue < bMax)
this->bluee = this->bluef * DBL_EPSILON;
else
this->bluee = 0;
if (this->alpha < aMax)
this->alphae = this->alphaf * DBL_EPSILON;
else
this->alphae = 0;
}
| 173,618 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_cipher rcipher;
snprintf(rcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "cipher");
rcipher.blocksize = alg->cra_blocksize;
rcipher.min_keysize = alg->cra_cipher.cia_min_keysize;
rcipher.max_keysize = alg->cra_cipher.cia_max_keysize;
if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER,
sizeof(struct crypto_report_cipher), &rcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310 | static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_cipher rcipher;
strncpy(rcipher.type, "cipher", sizeof(rcipher.type));
rcipher.blocksize = alg->cra_blocksize;
rcipher.min_keysize = alg->cra_cipher.cia_min_keysize;
rcipher.max_keysize = alg->cra_cipher.cia_max_keysize;
if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER,
sizeof(struct crypto_report_cipher), &rcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 166,067 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20 | static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
| 168,900 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
fwd_txfm_(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 RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride);
}
| 174,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 db_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
if (!(svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
!svm->nmi_singlestep) {
kvm_queue_exception(&svm->vcpu, DB_VECTOR);
return 1;
}
if (svm->nmi_singlestep) {
svm->nmi_singlestep = false;
if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
svm->vmcb->save.rflags &=
~(X86_EFLAGS_TF | X86_EFLAGS_RF);
update_db_bp_intercept(&svm->vcpu);
}
if (svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc =
svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = DB_VECTOR;
return 0;
}
return 1;
}
Commit Message: KVM: svm: unconditionally intercept #DB
This is needed to avoid the possibility that the guest triggers
an infinite stream of #DB exceptions (CVE-2015-8104).
VMX is not affected: because it does not save DR6 in the VMCS,
it already intercepts #DB unconditionally.
Reported-by: Jan Beulich <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399 | static int db_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
if (!(svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
!svm->nmi_singlestep) {
kvm_queue_exception(&svm->vcpu, DB_VECTOR);
return 1;
}
if (svm->nmi_singlestep) {
svm->nmi_singlestep = false;
if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
svm->vmcb->save.rflags &=
~(X86_EFLAGS_TF | X86_EFLAGS_RF);
}
if (svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc =
svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = DB_VECTOR;
return 0;
}
return 1;
}
| 166,568 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetDelegateOnIO(content::ResourceDispatcherHostDelegate* new_delegate) {
content::ResourceDispatcherHost::Get()->SetDelegate(new_delegate);
}
Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service.
The functionality worked, as part of converting DICE, however the test code didn't work since it
depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to
better match production, which removes the dependency on net/.
Also:
-make GetFilePathWithReplacements replace strings in the mock headers if they're present
-add a global to google_util to ignore ports; that way other tests can be converted without having
to modify each callsite to google_util
Bug: 881976
Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058
Reviewed-on: https://chromium-review.googlesource.com/c/1328142
Commit-Queue: John Abd-El-Malek <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652}
CWE ID: | void SetDelegateOnIO(content::ResourceDispatcherHostDelegate* new_delegate) {
| 172,581 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mp_capable_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_capable *mpc = (const struct mp_capable *) opt;
if (!(opt_len == 12 && flags & TH_SYN) &&
!(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK))
return 0;
if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) {
ND_PRINT((ndo, " Unknown Version (%d)", MP_CAPABLE_OPT_VERSION(mpc->sub_ver)));
return 1;
}
if (mpc->flags & MP_CAPABLE_C)
ND_PRINT((ndo, " csum"));
ND_PRINT((ndo, " {0x%" PRIx64, EXTRACT_64BITS(mpc->sender_key)));
if (opt_len == 20) /* ACK */
ND_PRINT((ndo, ",0x%" PRIx64, EXTRACT_64BITS(mpc->receiver_key)));
ND_PRINT((ndo, "}"));
return 1;
}
Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption.
Do the length checking inline; that means we print stuff up to the point
at which we run out of option data.
First check to make sure we have at least 4 bytes of option, so we have
flags to check.
This fixes a buffer over-read discovered by Kim Gwan Yeong.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | mp_capable_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_capable *mpc = (const struct mp_capable *) opt;
if (!(opt_len == 12 && (flags & TH_SYN)) &&
!(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK))
return 0;
if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) {
ND_PRINT((ndo, " Unknown Version (%d)", MP_CAPABLE_OPT_VERSION(mpc->sub_ver)));
return 1;
}
if (mpc->flags & MP_CAPABLE_C)
ND_PRINT((ndo, " csum"));
ND_PRINT((ndo, " {0x%" PRIx64, EXTRACT_64BITS(mpc->sender_key)));
if (opt_len == 20) /* ACK */
ND_PRINT((ndo, ",0x%" PRIx64, EXTRACT_64BITS(mpc->receiver_key)));
ND_PRINT((ndo, "}"));
return 1;
}
| 167,835 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add additional Lao character to IDN confusables
U+0E01 (ก) => n
Prior Lao/Thai entries were added in crrev.com/c/1058710.
Test: components_unittests --gtest_filter=*IDN*
Bug: 882078
Change-Id: I1e90b144a1d791341b515d026a6bc4be7cbed57d
Reviewed-on: https://chromium-review.googlesource.com/1220773
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Christopher Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#591227}
CWE ID: CWE-20 | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+014B (ŋ), U+043F (п), U+0525 (ԥ), U+0E01 (ก)} => n
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error)
{
*len = 0;
g_hash_table_foreach (table, hash_foreach, len);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error)
| 165,121 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 udf_pc_to_char(struct super_block *sb, unsigned char *from,
int fromlen, unsigned char *to)
{
struct pathComponent *pc;
int elen = 0;
unsigned char *p = to;
while (elen < fromlen) {
pc = (struct pathComponent *)(from + elen);
switch (pc->componentType) {
case 1:
/*
* Symlink points to some place which should be agreed
* upon between originator and receiver of the media. Ignore.
*/
if (pc->lengthComponentIdent > 0)
break;
/* Fall through */
case 2:
p = to;
*p++ = '/';
break;
case 3:
memcpy(p, "../", 3);
p += 3;
break;
case 4:
memcpy(p, "./", 2);
p += 2;
/* that would be . - just ignore */
break;
case 5:
p += udf_get_filename(sb, pc->componentIdent, p,
pc->lengthComponentIdent);
*p++ = '/';
break;
}
elen += sizeof(struct pathComponent) + pc->lengthComponentIdent;
}
if (p > to + 1)
p[-1] = '\0';
else
p[0] = '\0';
}
Commit Message: udf: Check path length when reading symlink
Symlink reading code does not check whether the resulting path fits into
the page provided by the generic code. This isn't as easy as just
checking the symlink size because of various encoding conversions we
perform on path. So we have to check whether there is still enough space
in the buffer on the fly.
CC: [email protected]
Reported-by: Carl Henrik Lunde <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-17 | static void udf_pc_to_char(struct super_block *sb, unsigned char *from,
static int udf_pc_to_char(struct super_block *sb, unsigned char *from,
int fromlen, unsigned char *to, int tolen)
{
struct pathComponent *pc;
int elen = 0;
int comp_len;
unsigned char *p = to;
/* Reserve one byte for terminating \0 */
tolen--;
while (elen < fromlen) {
pc = (struct pathComponent *)(from + elen);
switch (pc->componentType) {
case 1:
/*
* Symlink points to some place which should be agreed
* upon between originator and receiver of the media. Ignore.
*/
if (pc->lengthComponentIdent > 0)
break;
/* Fall through */
case 2:
if (tolen == 0)
return -ENAMETOOLONG;
p = to;
*p++ = '/';
tolen--;
break;
case 3:
if (tolen < 3)
return -ENAMETOOLONG;
memcpy(p, "../", 3);
p += 3;
tolen -= 3;
break;
case 4:
if (tolen < 2)
return -ENAMETOOLONG;
memcpy(p, "./", 2);
p += 2;
tolen -= 2;
/* that would be . - just ignore */
break;
case 5:
comp_len = udf_get_filename(sb, pc->componentIdent,
pc->lengthComponentIdent,
p, tolen);
p += comp_len;
tolen -= comp_len;
if (tolen == 0)
return -ENAMETOOLONG;
*p++ = '/';
tolen--;
break;
}
elen += sizeof(struct pathComponent) + pc->lengthComponentIdent;
}
if (p > to + 1)
p[-1] = '\0';
else
p[0] = '\0';
return 0;
}
| 166,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb,
struct net_device *dev)
{
struct net_bridge *br = netdev_priv(dev);
struct net_bridge_mdb_htable *mdb;
struct nlattr *nest, *nest2;
int i, err = 0;
int idx = 0, s_idx = cb->args[1];
if (br->multicast_disabled)
return 0;
mdb = rcu_dereference(br->mdb);
if (!mdb)
return 0;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
return -EMSGSIZE;
for (i = 0; i < mdb->max; i++) {
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p, **pp;
struct net_bridge_port *port;
hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) {
if (idx < s_idx)
goto skip;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL) {
err = -EMSGSIZE;
goto out;
}
for (pp = &mp->ports;
(p = rcu_dereference(*pp)) != NULL;
pp = &p->next) {
port = p->port;
if (port) {
struct br_mdb_entry e;
e.ifindex = port->dev->ifindex;
e.state = p->state;
if (p->addr.proto == htons(ETH_P_IP))
e.addr.u.ip4 = p->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
if (p->addr.proto == htons(ETH_P_IPV6))
e.addr.u.ip6 = p->addr.u.ip6;
#endif
e.addr.proto = p->addr.proto;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) {
nla_nest_cancel(skb, nest2);
err = -EMSGSIZE;
goto out;
}
}
}
nla_nest_end(skb, nest2);
skip:
idx++;
}
}
out:
cb->args[1] = idx;
nla_nest_end(skb, nest);
return err;
}
Commit Message: bridge: fix mdb info leaks
The bridging code discloses heap and stack bytes via the RTM_GETMDB
netlink interface and via the notify messages send to group RTNLGRP_MDB
afer a successful add/del.
Fix both cases by initializing all unset members/padding bytes with
memset(0).
Cc: Stephen Hemminger <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb,
struct net_device *dev)
{
struct net_bridge *br = netdev_priv(dev);
struct net_bridge_mdb_htable *mdb;
struct nlattr *nest, *nest2;
int i, err = 0;
int idx = 0, s_idx = cb->args[1];
if (br->multicast_disabled)
return 0;
mdb = rcu_dereference(br->mdb);
if (!mdb)
return 0;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
return -EMSGSIZE;
for (i = 0; i < mdb->max; i++) {
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p, **pp;
struct net_bridge_port *port;
hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) {
if (idx < s_idx)
goto skip;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL) {
err = -EMSGSIZE;
goto out;
}
for (pp = &mp->ports;
(p = rcu_dereference(*pp)) != NULL;
pp = &p->next) {
port = p->port;
if (port) {
struct br_mdb_entry e;
memset(&e, 0, sizeof(e));
e.ifindex = port->dev->ifindex;
e.state = p->state;
if (p->addr.proto == htons(ETH_P_IP))
e.addr.u.ip4 = p->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
if (p->addr.proto == htons(ETH_P_IPV6))
e.addr.u.ip6 = p->addr.u.ip6;
#endif
e.addr.proto = p->addr.proto;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) {
nla_nest_cancel(skb, nest2);
err = -EMSGSIZE;
goto out;
}
}
}
nla_nest_end(skb, nest2);
skip:
idx++;
}
}
out:
cb->args[1] = idx;
nla_nest_end(skb, nest);
return err;
}
| 166,053 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_ecb)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_long_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_ecb)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_long_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC);
}
| 167,108 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
while (elements-- > 0) {
zval key, *data, d, *old_data;
zend_ulong idx;
ZVAL_UNDEF(&key);
if (!php_var_unserialize_internal(&key, p, max, NULL, classes)) {
zval_dtor(&key);
return 0;
}
data = NULL;
ZVAL_UNDEF(&d);
if (!objprops) {
if (Z_TYPE(key) == IS_LONG) {
idx = Z_LVAL(key);
numeric_key:
if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
var_push_dtor(var_hash, old_data);
data = zend_hash_index_update(ht, idx, &d);
} else {
data = zend_hash_index_add_new(ht, idx, &d);
}
} else if (Z_TYPE(key) == IS_STRING) {
if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
goto numeric_key;
}
if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
var_push_dtor(var_hash, old_data);
data = zend_hash_update(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else {
zval_dtor(&key);
return 0;
}
} else {
if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
if (Z_TYPE_P(old_data) == IS_INDIRECT) {
old_data = Z_INDIRECT_P(old_data);
}
var_push_dtor(var_hash, old_data);
data = zend_hash_update_ind(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else if (Z_TYPE(key) == IS_LONG) {
/* object properties should include no integers */
convert_to_string(&key);
goto string_key;
} else {
zval_dtor(&key);
return 0;
}
}
if (!php_var_unserialize_internal(data, p, max, var_hash, classes)) {
zval_dtor(&key);
return 0;
}
if (UNEXPECTED(Z_ISUNDEF_P(data))) {
if (Z_TYPE(key) == IS_LONG) {
zend_hash_index_del(ht, Z_LVAL(key));
} else {
zend_hash_del_ind(ht, Z_STR(key));
}
} else {
var_push_dtor(var_hash, data);
}
zval_dtor(&key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
Commit Message: Fixed bug #74103 and bug #75054
Directly fail unserialization when trying to acquire an r/R
reference to an UNDEF HT slot. Previously this left an UNDEF and
later deleted the index/key from the HT.
What actually caused the issue here is a combination of two
factors: First, the key deletion was performed using the hash API,
rather than the symtable API, such that the element was not actually
removed if it used an integral string key. Second, a subsequent
deletion operation, while collecting trailing UNDEF ranges, would
mark the element as available for reuse (leaving a corrupted HT
state with nNumOfElemnts > nNumUsed).
Fix this by failing early and dropping the deletion code.
CWE ID: CWE-416 | static zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
while (elements-- > 0) {
zval key, *data, d, *old_data;
zend_ulong idx;
ZVAL_UNDEF(&key);
if (!php_var_unserialize_internal(&key, p, max, NULL, classes)) {
zval_dtor(&key);
return 0;
}
data = NULL;
ZVAL_UNDEF(&d);
if (!objprops) {
if (Z_TYPE(key) == IS_LONG) {
idx = Z_LVAL(key);
numeric_key:
if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
var_push_dtor(var_hash, old_data);
data = zend_hash_index_update(ht, idx, &d);
} else {
data = zend_hash_index_add_new(ht, idx, &d);
}
} else if (Z_TYPE(key) == IS_STRING) {
if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
goto numeric_key;
}
if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
var_push_dtor(var_hash, old_data);
data = zend_hash_update(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else {
zval_dtor(&key);
return 0;
}
} else {
if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
if (Z_TYPE_P(old_data) == IS_INDIRECT) {
old_data = Z_INDIRECT_P(old_data);
}
var_push_dtor(var_hash, old_data);
data = zend_hash_update_ind(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else if (Z_TYPE(key) == IS_LONG) {
/* object properties should include no integers */
convert_to_string(&key);
goto string_key;
} else {
zval_dtor(&key);
return 0;
}
}
if (!php_var_unserialize_internal(data, p, max, var_hash, classes)) {
zval_dtor(&key);
return 0;
}
var_push_dtor(var_hash, data);
zval_dtor(&key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
| 167,934 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr, char* key_name TSRMLS_DC)
{
zval** ele_value = NULL;
int i = 0;
int isFirstSubtag = 0;
int max_value = 0;
/* Variant/ Extlang/Private etc. */
if( zend_hash_find( hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if( Z_TYPE_PP(ele_value) == IS_STRING ){
add_prefix( loc_name , key_name);
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
} else if(Z_TYPE_PP(ele_value) == IS_ARRAY ) {
HashPosition pos;
HashTable *arr = HASH_OF(*ele_value);
zval **data = NULL;
zend_hash_internal_pointer_reset_ex(arr, &pos);
while(zend_hash_get_current_data_ex(arr, (void **)&data, &pos) != FAILURE) {
if(Z_TYPE_PP(data) != IS_STRING) {
return FAILURE;
}
if (isFirstSubtag++ == 0){
add_prefix(loc_name , key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(data) , Z_STRLEN_PP(data));
zend_hash_move_forward_ex(arr, &pos);
}
return SUCCESS;
} else {
return FAILURE;
}
} else {
char cur_key_name[31];
/* Decide the max_value: the max. no. of elements allowed */
if( strcmp(key_name , LOC_VARIANT_TAG) ==0 ){
max_value = MAX_NO_VARIANT;
}
if( strcmp(key_name , LOC_EXTLANG_TAG) ==0 ){
max_value = MAX_NO_EXTLANG;
}
if( strcmp(key_name , LOC_PRIVATE_TAG) ==0 ){
max_value = MAX_NO_PRIVATE;
}
/* Multiple variant values as variant0, variant1 ,variant2 */
isFirstSubtag = 0;
for( i=0 ; i< max_value; i++ ){
snprintf( cur_key_name , 30, "%s%d", key_name , i);
if( zend_hash_find( hash_arr , cur_key_name , strlen(cur_key_name) + 1,(void **)&ele_value ) == SUCCESS ){
if( Z_TYPE_PP(ele_value)!= IS_STRING ){
/* variant is not a string */
return FAILURE;
}
/* Add the contents */
if (isFirstSubtag++ == 0){
add_prefix(loc_name , cur_key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
}
} /* end of for */
} /* end of else */
return SUCCESS;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static int append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr, char* key_name TSRMLS_DC)
{
zval** ele_value = NULL;
int i = 0;
int isFirstSubtag = 0;
int max_value = 0;
/* Variant/ Extlang/Private etc. */
if( zend_hash_find( hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if( Z_TYPE_PP(ele_value) == IS_STRING ){
add_prefix( loc_name , key_name);
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
} else if(Z_TYPE_PP(ele_value) == IS_ARRAY ) {
HashPosition pos;
HashTable *arr = HASH_OF(*ele_value);
zval **data = NULL;
zend_hash_internal_pointer_reset_ex(arr, &pos);
while(zend_hash_get_current_data_ex(arr, (void **)&data, &pos) != FAILURE) {
if(Z_TYPE_PP(data) != IS_STRING) {
return FAILURE;
}
if (isFirstSubtag++ == 0){
add_prefix(loc_name , key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(data) , Z_STRLEN_PP(data));
zend_hash_move_forward_ex(arr, &pos);
}
return SUCCESS;
} else {
return FAILURE;
}
} else {
char cur_key_name[31];
/* Decide the max_value: the max. no. of elements allowed */
if( strcmp(key_name , LOC_VARIANT_TAG) ==0 ){
max_value = MAX_NO_VARIANT;
}
if( strcmp(key_name , LOC_EXTLANG_TAG) ==0 ){
max_value = MAX_NO_EXTLANG;
}
if( strcmp(key_name , LOC_PRIVATE_TAG) ==0 ){
max_value = MAX_NO_PRIVATE;
}
/* Multiple variant values as variant0, variant1 ,variant2 */
isFirstSubtag = 0;
for( i=0 ; i< max_value; i++ ){
snprintf( cur_key_name , 30, "%s%d", key_name , i);
if( zend_hash_find( hash_arr , cur_key_name , strlen(cur_key_name) + 1,(void **)&ele_value ) == SUCCESS ){
if( Z_TYPE_PP(ele_value)!= IS_STRING ){
/* variant is not a string */
return FAILURE;
}
/* Add the contents */
if (isFirstSubtag++ == 0){
add_prefix(loc_name , cur_key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
}
} /* end of for */
} /* end of else */
return SUCCESS;
}
| 167,199 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Edition::GetAtomCount() const
{
return m_atoms_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 | int Chapters::Edition::GetAtomCount() const
long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const {
return GetTime(pChapters, m_stop_timecode);
}
| 174,282 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: lockd(void *vrqstp)
{
int err = 0;
struct svc_rqst *rqstp = vrqstp;
/* try_to_freeze() is called from svc_recv() */
set_freezable();
/* Allow SIGKILL to tell lockd to drop all of its locks */
allow_signal(SIGKILL);
dprintk("NFS locking service started (ver " LOCKD_VERSION ").\n");
/*
* The main request loop. We don't terminate until the last
* NFS mount or NFS daemon has gone away.
*/
while (!kthread_should_stop()) {
long timeout = MAX_SCHEDULE_TIMEOUT;
RPC_IFDEBUG(char buf[RPC_MAX_ADDRBUFLEN]);
/* update sv_maxconn if it has changed */
rqstp->rq_server->sv_maxconn = nlm_max_connections;
if (signalled()) {
flush_signals(current);
restart_grace();
continue;
}
timeout = nlmsvc_retry_blocked();
/*
* Find a socket with data available and call its
* recvfrom routine.
*/
err = svc_recv(rqstp, timeout);
if (err == -EAGAIN || err == -EINTR)
continue;
dprintk("lockd: request from %s\n",
svc_print_addr(rqstp, buf, sizeof(buf)));
svc_process(rqstp);
}
flush_signals(current);
if (nlmsvc_ops)
nlmsvc_invalidate_all();
nlm_shutdown_hosts();
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | lockd(void *vrqstp)
{
int err = 0;
struct svc_rqst *rqstp = vrqstp;
struct net *net = &init_net;
struct lockd_net *ln = net_generic(net, lockd_net_id);
/* try_to_freeze() is called from svc_recv() */
set_freezable();
/* Allow SIGKILL to tell lockd to drop all of its locks */
allow_signal(SIGKILL);
dprintk("NFS locking service started (ver " LOCKD_VERSION ").\n");
/*
* The main request loop. We don't terminate until the last
* NFS mount or NFS daemon has gone away.
*/
while (!kthread_should_stop()) {
long timeout = MAX_SCHEDULE_TIMEOUT;
RPC_IFDEBUG(char buf[RPC_MAX_ADDRBUFLEN]);
/* update sv_maxconn if it has changed */
rqstp->rq_server->sv_maxconn = nlm_max_connections;
if (signalled()) {
flush_signals(current);
restart_grace();
continue;
}
timeout = nlmsvc_retry_blocked();
/*
* Find a socket with data available and call its
* recvfrom routine.
*/
err = svc_recv(rqstp, timeout);
if (err == -EAGAIN || err == -EINTR)
continue;
dprintk("lockd: request from %s\n",
svc_print_addr(rqstp, buf, sizeof(buf)));
svc_process(rqstp);
}
flush_signals(current);
if (nlmsvc_ops)
nlmsvc_invalidate_all();
nlm_shutdown_hosts();
cancel_delayed_work_sync(&ln->grace_period_end);
locks_end_grace(&ln->lockd_manager);
return 0;
}
| 168,134 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
struct bsg_device *bd = file->private_data;
ssize_t bytes_written;
int ret;
dprintk("%s: write %Zd bytes\n", bd->name, count);
bsg_set_block(bd, file);
bytes_written = 0;
ret = __bsg_write(bd, buf, count, &bytes_written,
file->f_mode & FMODE_WRITE);
*ppos = bytes_written;
/*
* return bytes written on non-fatal errors
*/
if (!bytes_written || err_block_err(ret))
bytes_written = ret;
dprintk("%s: returning %Zd\n", bd->name, bytes_written);
return bytes_written;
}
Commit Message: sg_write()/bsg_write() is not fit to be called under KERNEL_DS
Both damn things interpret userland pointers embedded into the payload;
worse, they are actually traversing those. Leaving aside the bad
API design, this is very much _not_ safe to call with KERNEL_DS.
Bail out early if that happens.
Cc: [email protected]
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-416 | bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
struct bsg_device *bd = file->private_data;
ssize_t bytes_written;
int ret;
dprintk("%s: write %Zd bytes\n", bd->name, count);
if (unlikely(segment_eq(get_fs(), KERNEL_DS)))
return -EINVAL;
bsg_set_block(bd, file);
bytes_written = 0;
ret = __bsg_write(bd, buf, count, &bytes_written,
file->f_mode & FMODE_WRITE);
*ppos = bytes_written;
/*
* return bytes written on non-fatal errors
*/
if (!bytes_written || err_block_err(ret))
bytes_written = ret;
dprintk("%s: returning %Zd\n", bd->name, bytes_written);
return bytes_written;
}
| 166,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
const struct xfrm_link *link;
int type, err;
#ifdef CONFIG_COMPAT
if (in_compat_syscall())
return -EOPNOTSUPP;
#endif
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!netlink_net_capable(skb, CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs,
link->nla_max ? : XFRMA_MAX,
link->nla_pol ? : xfrma_policy, extack);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
Commit Message: ipsec: Fix aborted xfrm policy dump crash
An independent security researcher, Mohamed Ghannam, has reported
this vulnerability to Beyond Security's SecuriTeam Secure Disclosure
program.
The xfrm_dump_policy_done function expects xfrm_dump_policy to
have been called at least once or it will crash. This can be
triggered if a dump fails because the target socket's receive
buffer is full.
This patch fixes it by using the cb->start mechanism to ensure that
the initialisation is always done regardless of the buffer situation.
Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list")
Signed-off-by: Herbert Xu <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
CWE ID: CWE-416 | static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
const struct xfrm_link *link;
int type, err;
#ifdef CONFIG_COMPAT
if (in_compat_syscall())
return -EOPNOTSUPP;
#endif
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!netlink_net_capable(skb, CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.start = link->start,
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs,
link->nla_max ? : XFRMA_MAX,
link->nla_pol ? : xfrma_policy, extack);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
| 167,664 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t read_mem(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
phys_addr_t p = *ppos;
ssize_t read, sz;
void *ptr;
if (p != *ppos)
return 0;
if (!valid_phys_addr_range(p, count))
return -EFAULT;
read = 0;
#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
/* we don't have page 0 mapped on sparc and m68k.. */
if (p < PAGE_SIZE) {
sz = size_inside_page(p, count);
if (sz > 0) {
if (clear_user(buf, sz))
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
}
#endif
while (count > 0) {
unsigned long remaining;
sz = size_inside_page(p, count);
if (!range_is_allowed(p >> PAGE_SHIFT, count))
return -EPERM;
/*
* On ia64 if a page has been mapped somewhere as uncached, then
* it must also be accessed uncached by the kernel or data
* corruption may occur.
*/
ptr = xlate_dev_mem_ptr(p);
if (!ptr)
return -EFAULT;
remaining = copy_to_user(buf, ptr, sz);
unxlate_dev_mem_ptr(p, ptr);
if (remaining)
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
*ppos += read;
return read;
}
Commit Message: mm: Tighten x86 /dev/mem with zeroing reads
Under CONFIG_STRICT_DEVMEM, reading System RAM through /dev/mem is
disallowed. However, on x86, the first 1MB was always allowed for BIOS
and similar things, regardless of it actually being System RAM. It was
possible for heap to end up getting allocated in low 1MB RAM, and then
read by things like x86info or dd, which would trip hardened usercopy:
usercopy: kernel memory exposure attempt detected from ffff880000090000 (dma-kmalloc-256) (4096 bytes)
This changes the x86 exception for the low 1MB by reading back zeros for
System RAM areas instead of blindly allowing them. More work is needed to
extend this to mmap, but currently mmap doesn't go through usercopy, so
hardened usercopy won't Oops the kernel.
Reported-by: Tommi Rantala <[email protected]>
Tested-by: Tommi Rantala <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
CWE ID: CWE-732 | static ssize_t read_mem(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
phys_addr_t p = *ppos;
ssize_t read, sz;
void *ptr;
if (p != *ppos)
return 0;
if (!valid_phys_addr_range(p, count))
return -EFAULT;
read = 0;
#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
/* we don't have page 0 mapped on sparc and m68k.. */
if (p < PAGE_SIZE) {
sz = size_inside_page(p, count);
if (sz > 0) {
if (clear_user(buf, sz))
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
}
#endif
while (count > 0) {
unsigned long remaining;
int allowed;
sz = size_inside_page(p, count);
allowed = page_is_allowed(p >> PAGE_SHIFT);
if (!allowed)
return -EPERM;
if (allowed == 2) {
/* Show zeros for restricted memory. */
remaining = clear_user(buf, sz);
} else {
/*
* On ia64 if a page has been mapped somewhere as
* uncached, then it must also be accessed uncached
* by the kernel or data corruption may occur.
*/
ptr = xlate_dev_mem_ptr(p);
if (!ptr)
return -EFAULT;
remaining = copy_to_user(buf, ptr, sz);
unxlate_dev_mem_ptr(p, ptr);
}
if (remaining)
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
*ppos += read;
return read;
}
| 168,242 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 copyStereo24(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
*dst++ = src[1][i] >> 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyStereo24(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
*dst++ = src[1][i] >> 8;
}
}
| 174,022 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )
{
cJSON_AddItemToArray( array, create_reference( item ) );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )
| 167,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltFreeTemplateHashes(xsltStylesheetPtr style) {
if (style->templatesHash != NULL)
xmlHashFree((xmlHashTablePtr) style->templatesHash,
(xmlHashDeallocator) xsltFreeCompMatchList);
if (style->rootMatch != NULL)
xsltFreeCompMatchList(style->rootMatch);
if (style->keyMatch != NULL)
xsltFreeCompMatchList(style->keyMatch);
if (style->elemMatch != NULL)
xsltFreeCompMatchList(style->elemMatch);
if (style->attrMatch != NULL)
xsltFreeCompMatchList(style->attrMatch);
if (style->parentMatch != NULL)
xsltFreeCompMatchList(style->parentMatch);
if (style->textMatch != NULL)
xsltFreeCompMatchList(style->textMatch);
if (style->piMatch != NULL)
xsltFreeCompMatchList(style->piMatch);
if (style->commentMatch != NULL)
xsltFreeCompMatchList(style->commentMatch);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltFreeTemplateHashes(xsltStylesheetPtr style) {
if (style->templatesHash != NULL)
xmlHashFree((xmlHashTablePtr) style->templatesHash,
(xmlHashDeallocator) xsltFreeCompMatchList);
if (style->rootMatch != NULL)
xsltFreeCompMatchList(style->rootMatch);
if (style->keyMatch != NULL)
xsltFreeCompMatchList(style->keyMatch);
if (style->elemMatch != NULL)
xsltFreeCompMatchList(style->elemMatch);
if (style->attrMatch != NULL)
xsltFreeCompMatchList(style->attrMatch);
if (style->parentMatch != NULL)
xsltFreeCompMatchList(style->parentMatch);
if (style->textMatch != NULL)
xsltFreeCompMatchList(style->textMatch);
if (style->piMatch != NULL)
xsltFreeCompMatchList(style->piMatch);
if (style->commentMatch != NULL)
xsltFreeCompMatchList(style->commentMatch);
if (style->namedTemplates != NULL)
xmlHashFree(style->namedTemplates, NULL);
}
| 173,312 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)
{
struct hlist_head *hashent = ucounts_hashentry(ns, uid);
struct ucounts *ucounts, *new;
spin_lock_irq(&ucounts_lock);
ucounts = find_ucounts(ns, uid, hashent);
if (!ucounts) {
spin_unlock_irq(&ucounts_lock);
new = kzalloc(sizeof(*new), GFP_KERNEL);
if (!new)
return NULL;
new->ns = ns;
new->uid = uid;
atomic_set(&new->count, 0);
spin_lock_irq(&ucounts_lock);
ucounts = find_ucounts(ns, uid, hashent);
if (ucounts) {
kfree(new);
} else {
hlist_add_head(&new->node, hashent);
ucounts = new;
}
}
if (!atomic_add_unless(&ucounts->count, 1, INT_MAX))
ucounts = NULL;
spin_unlock_irq(&ucounts_lock);
return ucounts;
}
Commit Message: ucount: Remove the atomicity from ucount->count
Always increment/decrement ucount->count under the ucounts_lock. The
increments are there already and moving the decrements there means the
locking logic of the code is simpler. This simplification in the
locking logic fixes a race between put_ucounts and get_ucounts that
could result in a use-after-free because the count could go zero then
be found by get_ucounts and then be freed by put_ucounts.
A bug presumably this one was found by a combination of syzkaller and
KASAN. JongWhan Kim reported the syzkaller failure and Dmitry Vyukov
spotted the race in the code.
Cc: [email protected]
Fixes: f6b2db1a3e8d ("userns: Make the count of user namespaces per user")
Reported-by: JongHwan Kim <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Reviewed-by: Andrei Vagin <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-416 | static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)
{
struct hlist_head *hashent = ucounts_hashentry(ns, uid);
struct ucounts *ucounts, *new;
spin_lock_irq(&ucounts_lock);
ucounts = find_ucounts(ns, uid, hashent);
if (!ucounts) {
spin_unlock_irq(&ucounts_lock);
new = kzalloc(sizeof(*new), GFP_KERNEL);
if (!new)
return NULL;
new->ns = ns;
new->uid = uid;
new->count = 0;
spin_lock_irq(&ucounts_lock);
ucounts = find_ucounts(ns, uid, hashent);
if (ucounts) {
kfree(new);
} else {
hlist_add_head(&new->node, hashent);
ucounts = new;
}
}
if (ucounts->count == INT_MAX)
ucounts = NULL;
else
ucounts->count += 1;
spin_unlock_irq(&ucounts_lock);
return ucounts;
}
| 168,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 DownloadItemImpl::UpdateProgress(int64 bytes_so_far,
const std::string& hash_state) {
hash_state_ = hash_state;
received_bytes_ = bytes_so_far;
if (received_bytes_ > total_bytes_)
total_bytes_ = 0;
if (bound_net_log_.IsLoggingAllEvents()) {
bound_net_log_.AddEvent(
net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED,
net::NetLog::Int64Callback("bytes_so_far", received_bytes_));
}
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void DownloadItemImpl::UpdateProgress(int64 bytes_so_far,
int64 bytes_per_sec,
const std::string& hash_state) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!IsInProgress()) {
// Ignore if we're no longer in-progress. This can happen if we race a
// Cancel on the UI thread with an update on the FILE thread.
//
// TODO(rdsmith): Arguably we should let this go through, as this means
// the download really did get further than we know before it was
// cancelled. But the gain isn't very large, and the code is more
// fragile if it has to support in progress updates in a non-in-progress
// state. This issue should be readdressed when we revamp performance
// reporting.
return;
}
bytes_per_sec_ = bytes_per_sec;
hash_state_ = hash_state;
received_bytes_ = bytes_so_far;
if (received_bytes_ > total_bytes_)
total_bytes_ = 0;
if (bound_net_log_.IsLoggingAllEvents()) {
bound_net_log_.AddEvent(
net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED,
net::NetLog::Int64Callback("bytes_so_far", received_bytes_));
}
| 170,885 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: asmlinkage long sys_oabi_semtimedop(int semid,
struct oabi_sembuf __user *tsops,
unsigned nsops,
const struct timespec __user *timeout)
{
struct sembuf *sops;
struct timespec local_timeout;
long err;
int i;
if (nsops < 1)
return -EINVAL;
sops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL);
if (!sops)
return -ENOMEM;
err = 0;
for (i = 0; i < nsops; i++) {
__get_user_error(sops[i].sem_num, &tsops->sem_num, err);
__get_user_error(sops[i].sem_op, &tsops->sem_op, err);
__get_user_error(sops[i].sem_flg, &tsops->sem_flg, err);
tsops++;
}
if (timeout) {
/* copy this as well before changing domain protection */
err |= copy_from_user(&local_timeout, timeout, sizeof(*timeout));
timeout = &local_timeout;
}
if (err) {
err = -EFAULT;
} else {
mm_segment_t fs = get_fs();
set_fs(KERNEL_DS);
err = sys_semtimedop(semid, sops, nsops, timeout);
set_fs(fs);
}
kfree(sops);
return err;
}
Commit Message: ARM: 6891/1: prevent heap corruption in OABI semtimedop
When CONFIG_OABI_COMPAT is set, the wrapper for semtimedop does not
bound the nsops argument. A sufficiently large value will cause an
integer overflow in allocation size, followed by copying too much data
into the allocated buffer. Fix this by restricting nsops to SEMOPM.
Untested.
Cc: [email protected]
Signed-off-by: Dan Rosenberg <[email protected]>
Signed-off-by: Russell King <[email protected]>
CWE ID: CWE-189 | asmlinkage long sys_oabi_semtimedop(int semid,
struct oabi_sembuf __user *tsops,
unsigned nsops,
const struct timespec __user *timeout)
{
struct sembuf *sops;
struct timespec local_timeout;
long err;
int i;
if (nsops < 1 || nsops > SEMOPM)
return -EINVAL;
sops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL);
if (!sops)
return -ENOMEM;
err = 0;
for (i = 0; i < nsops; i++) {
__get_user_error(sops[i].sem_num, &tsops->sem_num, err);
__get_user_error(sops[i].sem_op, &tsops->sem_op, err);
__get_user_error(sops[i].sem_flg, &tsops->sem_flg, err);
tsops++;
}
if (timeout) {
/* copy this as well before changing domain protection */
err |= copy_from_user(&local_timeout, timeout, sizeof(*timeout));
timeout = &local_timeout;
}
if (err) {
err = -EFAULT;
} else {
mm_segment_t fs = get_fs();
set_fs(KERNEL_DS);
err = sys_semtimedop(semid, sops, nsops, timeout);
set_fs(fs);
}
kfree(sops);
return err;
}
| 165,885 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::setConfig(
OMX_INDEXTYPE index, const void *params, size_t size) {
Mutex::Autolock autoLock(mLock);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
CLOG_CONFIG(setConfig, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params);
OMX_ERRORTYPE err = OMX_SetConfig(
mHandle, index, const_cast<void *>(params));
CLOG_IF_ERROR(setConfig, err, "%s(%#x)", asString(extIndex), index);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::setConfig(
OMX_INDEXTYPE index, const void *params, size_t size) {
Mutex::Autolock autoLock(mLock);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
CLOG_CONFIG(setConfig, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_SetConfig(
mHandle, index, const_cast<void *>(params));
CLOG_IF_ERROR(setConfig, err, "%s(%#x)", asString(extIndex), index);
return StatusFromOMXError(err);
}
| 174,138 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: wb_print(netdissect_options *ndo,
register const void *hdr, register u_int len)
{
register const struct pkt_hdr *ph;
ph = (const struct pkt_hdr *)hdr;
if (len < sizeof(*ph) || !ND_TTEST(*ph)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
len -= sizeof(*ph);
if (ph->ph_flags)
ND_PRINT((ndo, "*"));
switch (ph->ph_type) {
case PT_KILL:
ND_PRINT((ndo, " wb-kill"));
return;
case PT_ID:
if (wb_id(ndo, (const struct pkt_id *)(ph + 1), len) >= 0)
return;
break;
case PT_RREQ:
if (wb_rreq(ndo, (const struct pkt_rreq *)(ph + 1), len) >= 0)
return;
break;
case PT_RREP:
if (wb_rrep(ndo, (const struct pkt_rrep *)(ph + 1), len) >= 0)
return;
break;
case PT_DRAWOP:
if (wb_drawop(ndo, (const struct pkt_dop *)(ph + 1), len) >= 0)
return;
break;
case PT_PREQ:
if (wb_preq(ndo, (const struct pkt_preq *)(ph + 1), len) >= 0)
return;
break;
case PT_PREP:
if (wb_prep(ndo, (const struct pkt_prep *)(ph + 1), len) >= 0)
return;
break;
default:
ND_PRINT((ndo, " wb-%d!", ph->ph_type));
return;
}
}
Commit Message: CVE-2017-13014/White Board: Do more bounds checks.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
While we're at it, print a truncation error if the packets are
truncated, rather than just, in effect, ignoring the result of the
routines that print particular packet types.
CWE ID: CWE-125 | wb_print(netdissect_options *ndo,
register const void *hdr, register u_int len)
{
register const struct pkt_hdr *ph;
ph = (const struct pkt_hdr *)hdr;
if (len < sizeof(*ph) || !ND_TTEST(*ph)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
len -= sizeof(*ph);
if (ph->ph_flags)
ND_PRINT((ndo, "*"));
switch (ph->ph_type) {
case PT_KILL:
ND_PRINT((ndo, " wb-kill"));
return;
case PT_ID:
if (wb_id(ndo, (const struct pkt_id *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_RREQ:
if (wb_rreq(ndo, (const struct pkt_rreq *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_RREP:
if (wb_rrep(ndo, (const struct pkt_rrep *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_DRAWOP:
if (wb_drawop(ndo, (const struct pkt_dop *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_PREQ:
if (wb_preq(ndo, (const struct pkt_preq *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_PREP:
if (wb_prep(ndo, (const struct pkt_prep *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
default:
ND_PRINT((ndo, " wb-%d!", ph->ph_type));
return;
}
}
| 167,879 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderThreadImpl::EnsureWebKitInitialized() {
if (webkit_platform_support_)
return;
webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
blink::initialize(webkit_platform_support_.get());
main_thread_compositor_task_runner_ =
make_scoped_refptr(new SchedulerProxyTaskRunner<
&blink::WebSchedulerProxy::postCompositorTask>());
v8::Isolate* isolate = blink::mainThreadIsolate();
isolate->SetCounterFunction(base::StatsTable::FindLocation);
isolate->SetCreateHistogramFunction(CreateHistogram);
isolate->SetAddHistogramSampleFunction(AddHistogramSample);
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
if (enable) {
#if defined(OS_ANDROID)
if (SynchronousCompositorFactory* factory =
SynchronousCompositorFactory::GetInstance())
compositor_message_loop_proxy_ =
factory->GetCompositorMessageLoop();
#endif
if (!compositor_message_loop_proxy_.get()) {
compositor_thread_.reset(new base::Thread("Compositor"));
compositor_thread_->Start();
#if defined(OS_ANDROID)
compositor_thread_->SetPriority(base::kThreadPriority_Display);
#endif
compositor_message_loop_proxy_ =
compositor_thread_->message_loop_proxy();
compositor_message_loop_proxy_->PostTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
false));
}
InputHandlerManagerClient* input_handler_manager_client = NULL;
#if defined(OS_ANDROID)
if (SynchronousCompositorFactory* factory =
SynchronousCompositorFactory::GetInstance()) {
input_handler_manager_client = factory->GetInputHandlerManagerClient();
}
#endif
if (!input_handler_manager_client) {
input_event_filter_ =
new InputEventFilter(this,
main_thread_compositor_task_runner_,
compositor_message_loop_proxy_);
AddFilter(input_event_filter_.get());
input_handler_manager_client = input_event_filter_.get();
}
input_handler_manager_.reset(
new InputHandlerManager(compositor_message_loop_proxy_,
input_handler_manager_client));
}
scoped_refptr<base::MessageLoopProxy> output_surface_loop;
if (enable)
output_surface_loop = compositor_message_loop_proxy_;
else
output_surface_loop = base::MessageLoopProxy::current();
compositor_output_surface_filter_ =
CompositorOutputSurface::CreateFilter(output_surface_loop.get());
AddFilter(compositor_output_surface_filter_.get());
RenderThreadImpl::RegisterSchemes();
EnableBlinkPlatformLogChannels(
command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
if (!media::IsMediaLibraryInitialized()) {
WebRuntimeFeatures::enableWebAudio(false);
}
FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
devtools_agent_message_filter_ = new DevToolsAgentFilter();
AddFilter(devtools_agent_message_filter_.get());
if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
ScheduleIdleHandler(kLongIdleHandlerDelayMs);
cc_blink::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction);
if (!command_line.HasSwitch(switches::kEnableDeferredImageDecoding) &&
!is_impl_side_painting_enabled_)
SkGraphics::SetImageCacheByteLimit(0u);
SkGraphics::SetImageCacheSingleAllocationByteLimit(
kImageCacheSingleAllocationByteLimit);
if (command_line.HasSwitch(switches::kMemoryMetrics)) {
memory_observer_.reset(new MemoryObserver());
message_loop()->AddTaskObserver(memory_observer_.get());
}
}
Commit Message: Disable forwarding tasks to the Blink scheduler
Disable forwarding tasks to the Blink scheduler to avoid some
regressions which it has introduced.
BUG=391005,415758,415478,412714,416362,416827,417608
[email protected]
Review URL: https://codereview.chromium.org/609483002
Cr-Commit-Position: refs/heads/master@{#296916}
CWE ID: | void RenderThreadImpl::EnsureWebKitInitialized() {
if (webkit_platform_support_)
return;
webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
blink::initialize(webkit_platform_support_.get());
main_thread_compositor_task_runner_ = base::MessageLoopProxy::current();
v8::Isolate* isolate = blink::mainThreadIsolate();
isolate->SetCounterFunction(base::StatsTable::FindLocation);
isolate->SetCreateHistogramFunction(CreateHistogram);
isolate->SetAddHistogramSampleFunction(AddHistogramSample);
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing);
if (enable) {
#if defined(OS_ANDROID)
if (SynchronousCompositorFactory* factory =
SynchronousCompositorFactory::GetInstance())
compositor_message_loop_proxy_ =
factory->GetCompositorMessageLoop();
#endif
if (!compositor_message_loop_proxy_.get()) {
compositor_thread_.reset(new base::Thread("Compositor"));
compositor_thread_->Start();
#if defined(OS_ANDROID)
compositor_thread_->SetPriority(base::kThreadPriority_Display);
#endif
compositor_message_loop_proxy_ =
compositor_thread_->message_loop_proxy();
compositor_message_loop_proxy_->PostTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
false));
}
InputHandlerManagerClient* input_handler_manager_client = NULL;
#if defined(OS_ANDROID)
if (SynchronousCompositorFactory* factory =
SynchronousCompositorFactory::GetInstance()) {
input_handler_manager_client = factory->GetInputHandlerManagerClient();
}
#endif
if (!input_handler_manager_client) {
input_event_filter_ =
new InputEventFilter(this,
main_thread_compositor_task_runner_,
compositor_message_loop_proxy_);
AddFilter(input_event_filter_.get());
input_handler_manager_client = input_event_filter_.get();
}
input_handler_manager_.reset(
new InputHandlerManager(compositor_message_loop_proxy_,
input_handler_manager_client));
}
scoped_refptr<base::MessageLoopProxy> output_surface_loop;
if (enable)
output_surface_loop = compositor_message_loop_proxy_;
else
output_surface_loop = base::MessageLoopProxy::current();
compositor_output_surface_filter_ =
CompositorOutputSurface::CreateFilter(output_surface_loop.get());
AddFilter(compositor_output_surface_filter_.get());
RenderThreadImpl::RegisterSchemes();
EnableBlinkPlatformLogChannels(
command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels));
SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
if (!media::IsMediaLibraryInitialized()) {
WebRuntimeFeatures::enableWebAudio(false);
}
FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
devtools_agent_message_filter_ = new DevToolsAgentFilter();
AddFilter(devtools_agent_message_filter_.get());
if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
ScheduleIdleHandler(kLongIdleHandlerDelayMs);
cc_blink::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction);
if (!command_line.HasSwitch(switches::kEnableDeferredImageDecoding) &&
!is_impl_side_painting_enabled_)
SkGraphics::SetImageCacheByteLimit(0u);
SkGraphics::SetImageCacheSingleAllocationByteLimit(
kImageCacheSingleAllocationByteLimit);
if (command_line.HasSwitch(switches::kMemoryMetrics)) {
memory_observer_.reset(new MemoryObserver());
message_loop()->AddTaskObserver(memory_observer_.get());
}
}
| 171,886 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TestPlaybackRate(double playback_rate,
int buffer_size_in_frames,
int total_frames_requested) {
int initial_bytes_enqueued = bytes_enqueued_;
int initial_bytes_buffered = algorithm_.bytes_buffered();
algorithm_.SetPlaybackRate(static_cast<float>(playback_rate));
scoped_array<uint8> buffer(
new uint8[buffer_size_in_frames * algorithm_.bytes_per_frame()]);
if (playback_rate == 0.0) {
int frames_written =
algorithm_.FillBuffer(buffer.get(), buffer_size_in_frames);
EXPECT_EQ(0, frames_written);
return;
}
int frames_remaining = total_frames_requested;
while (frames_remaining > 0) {
int frames_requested = std::min(buffer_size_in_frames, frames_remaining);
int frames_written =
algorithm_.FillBuffer(buffer.get(), frames_requested);
CHECK_GT(frames_written, 0);
CheckFakeData(buffer.get(), frames_written, playback_rate);
frames_remaining -= frames_written;
}
int bytes_requested = total_frames_requested * algorithm_.bytes_per_frame();
int bytes_consumed = ComputeConsumedBytes(initial_bytes_enqueued,
initial_bytes_buffered);
if (playback_rate == 1.0) {
EXPECT_EQ(bytes_requested, bytes_consumed);
return;
}
static const double kMaxAcceptableDelta = 0.01;
double actual_playback_rate = 1.0 * bytes_consumed / bytes_requested;
double delta = std::abs(1.0 - (actual_playback_rate / playback_rate));
EXPECT_LE(delta, kMaxAcceptableDelta);
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void TestPlaybackRate(double playback_rate,
int buffer_size_in_frames,
int total_frames_requested) {
int initial_bytes_enqueued = bytes_enqueued_;
int initial_bytes_buffered = algorithm_.bytes_buffered();
algorithm_.SetPlaybackRate(static_cast<float>(playback_rate));
scoped_array<uint8> buffer(
new uint8[buffer_size_in_frames * algorithm_.bytes_per_frame()]);
if (playback_rate == 0.0) {
int frames_written =
algorithm_.FillBuffer(buffer.get(), buffer_size_in_frames);
EXPECT_EQ(0, frames_written);
return;
}
int frames_remaining = total_frames_requested;
while (frames_remaining > 0) {
int frames_requested = std::min(buffer_size_in_frames, frames_remaining);
int frames_written =
algorithm_.FillBuffer(buffer.get(), frames_requested);
ASSERT_GT(frames_written, 0);
CheckFakeData(buffer.get(), frames_written);
frames_remaining -= frames_written;
}
int bytes_requested = total_frames_requested * algorithm_.bytes_per_frame();
int bytes_consumed = ComputeConsumedBytes(initial_bytes_enqueued,
initial_bytes_buffered);
if (playback_rate == 1.0) {
EXPECT_EQ(bytes_requested, bytes_consumed);
return;
}
static const double kMaxAcceptableDelta = 0.01;
double actual_playback_rate = 1.0 * bytes_consumed / bytes_requested;
double delta = std::abs(1.0 - (actual_playback_rate / playback_rate));
EXPECT_LE(delta, kMaxAcceptableDelta);
}
| 171,536 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags);
if (offset == 0)
break;
}
}
return 0;
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399 | dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, uint16_t *notecount)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags, notecount);
if (offset == 0)
break;
}
}
return 0;
}
| 166,777 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 EBMLHeader::Init()
{
m_version = 1;
m_readVersion = 1;
m_maxIdLength = 4;
m_maxSizeLength = 8;
if (m_docType)
{
delete[] m_docType;
m_docType = NULL;
}
m_docTypeVersion = 1;
m_docTypeReadVersion = 1;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void EBMLHeader::Init()
long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) {
assert(pReader);
long long total, available;
| 174,389 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LoginLibrary* CrosLibrary::GetLoginLibrary() {
return login_lib_.GetDefaultImpl(use_stub_impl_);
}
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 | LoginLibrary* CrosLibrary::GetLoginLibrary() {
| 170,625 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&)
{
ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN || !m_imageResource->hasImage())
return;
FloatRect boundingBox = repaintRectInLocalCoordinates();
if (!SVGRenderSupport::paintInfoIntersectsRepaintRect(boundingBox, m_localTransform, paintInfo))
return;
PaintInfo childPaintInfo(paintInfo);
bool drawsOutline = style()->outlineWidth() && (childPaintInfo.phase == PaintPhaseOutline || childPaintInfo.phase == PaintPhaseSelfOutline);
if (drawsOutline || childPaintInfo.phase == PaintPhaseForeground) {
GraphicsContextStateSaver stateSaver(*childPaintInfo.context);
childPaintInfo.applyTransform(m_localTransform);
if (childPaintInfo.phase == PaintPhaseForeground) {
SVGRenderingContext renderingContext(this, childPaintInfo);
if (renderingContext.isRenderingPrepared()) {
if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground))
return;
paintForeground(childPaintInfo);
}
}
if (drawsOutline)
paintOutline(childPaintInfo, IntRect(boundingBox));
}
}
Commit Message: Avoid drawing SVG image content when the image is of zero size.
R=pdr
BUG=330420
Review URL: https://codereview.chromium.org/109753004
git-svn-id: svn://svn.chromium.org/blink/trunk@164536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&)
{
ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN || !m_imageResource->hasImage())
return;
FloatRect boundingBox = repaintRectInLocalCoordinates();
if (!SVGRenderSupport::paintInfoIntersectsRepaintRect(boundingBox, m_localTransform, paintInfo))
return;
PaintInfo childPaintInfo(paintInfo);
bool drawsOutline = style()->outlineWidth() && (childPaintInfo.phase == PaintPhaseOutline || childPaintInfo.phase == PaintPhaseSelfOutline);
if (drawsOutline || childPaintInfo.phase == PaintPhaseForeground) {
GraphicsContextStateSaver stateSaver(*childPaintInfo.context);
childPaintInfo.applyTransform(m_localTransform);
if (childPaintInfo.phase == PaintPhaseForeground && !m_objectBoundingBox.isEmpty()) {
SVGRenderingContext renderingContext(this, childPaintInfo);
if (renderingContext.isRenderingPrepared()) {
if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground))
return;
paintForeground(childPaintInfo);
}
}
if (drawsOutline)
paintOutline(childPaintInfo, IntRect(boundingBox));
}
}
| 171,705 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SetUp() {
source_stride_ = (width_ + 31) & ~31;
reference_stride_ = width_ * 2;
rnd_.Reset(ACMRandom::DeterministicSeed());
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void SetUp() {
if (bd_ == -1) {
use_high_bit_depth_ = false;
bit_depth_ = VPX_BITS_8;
source_data_ = source_data8_;
reference_data_ = reference_data8_;
second_pred_ = second_pred8_;
#if CONFIG_VP9_HIGHBITDEPTH
} else {
use_high_bit_depth_ = true;
bit_depth_ = static_cast<vpx_bit_depth_t>(bd_);
source_data_ = CONVERT_TO_BYTEPTR(source_data16_);
reference_data_ = CONVERT_TO_BYTEPTR(reference_data16_);
second_pred_ = CONVERT_TO_BYTEPTR(second_pred16_);
#endif // CONFIG_VP9_HIGHBITDEPTH
}
mask_ = (1 << bit_depth_) - 1;
source_stride_ = (width_ + 31) & ~31;
reference_stride_ = width_ * 2;
rnd_.Reset(ACMRandom::DeterministicSeed());
}
| 174,577 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vfs_open(const struct path *path, struct file *file,
const struct cred *cred)
{
struct dentry *dentry = path->dentry;
struct inode *inode = dentry->d_inode;
file->f_path = *path;
if (dentry->d_flags & DCACHE_OP_SELECT_INODE) {
inode = dentry->d_op->d_select_inode(dentry, file->f_flags);
if (IS_ERR(inode))
return PTR_ERR(inode);
}
return do_dentry_open(file, inode, NULL, cred);
}
Commit Message: vfs: add vfs_select_inode() helper
Signed-off-by: Miklos Szeredi <[email protected]>
Cc: <[email protected]> # v4.2+
CWE ID: CWE-284 | int vfs_open(const struct path *path, struct file *file,
const struct cred *cred)
{
struct inode *inode = vfs_select_inode(path->dentry, file->f_flags);
if (IS_ERR(inode))
return PTR_ERR(inode);
file->f_path = *path;
return do_dentry_open(file, inode, NULL, cred);
}
| 169,943 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: feed_table_block_tag(struct table *tbl,
char *line, struct table_mode *mode, int indent, int cmd)
{
int offset;
if (mode->indent_level <= 0 && indent == -1)
return;
if (mode->indent_level >= CHAR_MAX && indent == 1)
return;
setwidth(tbl, mode);
feed_table_inline_tag(tbl, line, mode, -1);
clearcontentssize(tbl, mode);
if (indent == 1) {
mode->indent_level++;
if (mode->indent_level <= MAX_INDENT_LEVEL)
tbl->indent += INDENT_INCR;
}
else if (indent == -1) {
mode->indent_level--;
if (mode->indent_level < MAX_INDENT_LEVEL)
tbl->indent -= INDENT_INCR;
}
offset = tbl->indent;
if (cmd == HTML_DT) {
if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL)
offset -= INDENT_INCR;
}
if (tbl->indent > 0) {
check_minimum0(tbl, 0);
addcontentssize(tbl, offset);
}
}
Commit Message: Prevent negative indent value in feed_table_block_tag()
Bug-Debian: https://github.com/tats/w3m/issues/88
CWE ID: CWE-835 | feed_table_block_tag(struct table *tbl,
char *line, struct table_mode *mode, int indent, int cmd)
{
int offset;
if (mode->indent_level <= 0 && indent == -1)
return;
if (mode->indent_level >= CHAR_MAX && indent == 1)
return;
setwidth(tbl, mode);
feed_table_inline_tag(tbl, line, mode, -1);
clearcontentssize(tbl, mode);
if (indent == 1) {
mode->indent_level++;
if (mode->indent_level <= MAX_INDENT_LEVEL)
tbl->indent += INDENT_INCR;
}
else if (indent == -1) {
mode->indent_level--;
if (mode->indent_level < MAX_INDENT_LEVEL)
tbl->indent -= INDENT_INCR;
}
if (tbl->indent < 0)
tbl->indent = 0;
offset = tbl->indent;
if (cmd == HTML_DT) {
if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL)
offset -= INDENT_INCR;
if (offset < 0)
offset = 0;
}
if (tbl->indent > 0) {
check_minimum0(tbl, 0);
addcontentssize(tbl, offset);
}
}
| 169,348 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ft_bitmap_assure_buffer( FT_Memory memory,
FT_Bitmap* bitmap,
FT_UInt xpixels,
FT_UInt ypixels )
{
FT_Error error;
int pitch;
int new_pitch;
FT_UInt bpp;
FT_Int i, width, height;
unsigned char* buffer = NULL;
width = bitmap->width;
height = bitmap->rows;
pitch = bitmap->pitch;
if ( pitch < 0 )
pitch = -pitch;
switch ( bitmap->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
bpp = 1;
new_pitch = ( width + xpixels + 7 ) >> 3;
break;
case FT_PIXEL_MODE_GRAY2:
bpp = 2;
new_pitch = ( width + xpixels + 3 ) >> 2;
break;
case FT_PIXEL_MODE_GRAY4:
bpp = 4;
new_pitch = ( width + xpixels + 1 ) >> 1;
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
bpp = 8;
new_pitch = ( width + xpixels );
break;
default:
return FT_THROW( Invalid_Glyph_Format );
}
/* if no need to allocate memory */
if ( ypixels == 0 && new_pitch <= pitch )
{
/* zero the padding */
FT_Int bit_width = pitch * 8;
FT_Int bit_last = ( width + xpixels ) * bpp;
if ( bit_last < bit_width )
{
FT_Byte* line = bitmap->buffer + ( bit_last >> 3 );
FT_Byte* end = bitmap->buffer + pitch;
FT_Int shift = bit_last & 7;
FT_UInt mask = 0xFF00U >> shift;
FT_Int count = height;
for ( ; count > 0; count--, line += pitch, end += pitch )
{
FT_Byte* write = line;
if ( shift > 0 )
{
write[0] = (FT_Byte)( write[0] & mask );
write++;
}
if ( write < end )
FT_MEM_ZERO( write, end - write );
}
}
return FT_Err_Ok;
}
/* otherwise allocate new buffer */
if ( FT_QALLOC_MULT( buffer, new_pitch, bitmap->rows + ypixels ) )
return error;
/* new rows get added at the top of the bitmap, */
/* thus take care of the flow direction */
if ( bitmap->pitch > 0 )
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * ( ypixels + i ),
bitmap->buffer + pitch * i, len );
}
else
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * i,
bitmap->buffer + pitch * i, len );
}
FT_FREE( bitmap->buffer );
bitmap->buffer = buffer;
if ( bitmap->pitch < 0 )
new_pitch = -new_pitch;
/* set pitch only, width and height are left untouched */
bitmap->pitch = new_pitch;
return FT_Err_Ok;
}
Commit Message:
CWE ID: CWE-119 | ft_bitmap_assure_buffer( FT_Memory memory,
FT_Bitmap* bitmap,
FT_UInt xpixels,
FT_UInt ypixels )
{
FT_Error error;
int pitch;
int new_pitch;
FT_UInt bpp;
FT_UInt i, width, height;
unsigned char* buffer = NULL;
width = bitmap->width;
height = bitmap->rows;
pitch = bitmap->pitch;
if ( pitch < 0 )
pitch = -pitch;
switch ( bitmap->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
bpp = 1;
new_pitch = ( width + xpixels + 7 ) >> 3;
break;
case FT_PIXEL_MODE_GRAY2:
bpp = 2;
new_pitch = ( width + xpixels + 3 ) >> 2;
break;
case FT_PIXEL_MODE_GRAY4:
bpp = 4;
new_pitch = ( width + xpixels + 1 ) >> 1;
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
bpp = 8;
new_pitch = ( width + xpixels );
break;
default:
return FT_THROW( Invalid_Glyph_Format );
}
/* if no need to allocate memory */
if ( ypixels == 0 && new_pitch <= pitch )
{
/* zero the padding */
FT_UInt bit_width = pitch * 8;
FT_UInt bit_last = ( width + xpixels ) * bpp;
if ( bit_last < bit_width )
{
FT_Byte* line = bitmap->buffer + ( bit_last >> 3 );
FT_Byte* end = bitmap->buffer + pitch;
FT_UInt shift = bit_last & 7;
FT_UInt mask = 0xFF00U >> shift;
FT_UInt count = height;
for ( ; count > 0; count--, line += pitch, end += pitch )
{
FT_Byte* write = line;
if ( shift > 0 )
{
write[0] = (FT_Byte)( write[0] & mask );
write++;
}
if ( write < end )
FT_MEM_ZERO( write, end - write );
}
}
return FT_Err_Ok;
}
/* otherwise allocate new buffer */
if ( FT_QALLOC_MULT( buffer, new_pitch, bitmap->rows + ypixels ) )
return error;
/* new rows get added at the top of the bitmap, */
/* thus take care of the flow direction */
if ( bitmap->pitch > 0 )
{
FT_UInt len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * ( ypixels + i ),
bitmap->buffer + pitch * i, len );
}
else
{
FT_UInt len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * i,
bitmap->buffer + pitch * i, len );
}
FT_FREE( bitmap->buffer );
bitmap->buffer = buffer;
if ( bitmap->pitch < 0 )
new_pitch = -new_pitch;
/* set pitch only, width and height are left untouched */
bitmap->pitch = new_pitch;
return FT_Err_Ok;
}
| 164,850 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DiscardAndActivateTest(DiscardReason reason) {
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true));
background_lifecycle_unit->Discard(reason);
testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false));
tab_strip_model_->ActivateTabAt(0, true);
testing::Mock::VerifyAndClear(&tab_observer_);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
}
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 <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID: | void DiscardAndActivateTest(DiscardReason reason) {
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true));
background_lifecycle_unit->Discard(reason);
::testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false));
tab_strip_model_->ActivateTabAt(0, true);
::testing::Mock::VerifyAndClear(&tab_observer_);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
}
| 172,224 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xen_netbk_tx_check_gop(struct xen_netbk *netbk,
struct sk_buff *skb,
struct gnttab_copy **gopp)
{
struct gnttab_copy *gop = *gopp;
u16 pending_idx = *((u16 *)skb->data);
struct pending_tx_info *pending_tx_info = netbk->pending_tx_info;
struct xenvif *vif = pending_tx_info[pending_idx].vif;
struct xen_netif_tx_request *txp;
struct skb_shared_info *shinfo = skb_shinfo(skb);
int nr_frags = shinfo->nr_frags;
int i, err, start;
/* Check status of header. */
err = gop->status;
if (unlikely(err)) {
pending_ring_idx_t index;
index = pending_index(netbk->pending_prod++);
txp = &pending_tx_info[pending_idx].req;
make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
}
/* Skip first skb fragment if it is on same page as header fragment. */
start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
for (i = start; i < nr_frags; i++) {
int j, newerr;
pending_ring_idx_t index;
pending_idx = frag_get_pending_idx(&shinfo->frags[i]);
/* Check error status: if okay then remember grant handle. */
newerr = (++gop)->status;
if (likely(!newerr)) {
/* Had a previous error? Invalidate this fragment. */
if (unlikely(err))
xen_netbk_idx_release(netbk, pending_idx);
continue;
}
/* Error on this fragment: respond to client with an error. */
txp = &netbk->pending_tx_info[pending_idx].req;
make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
index = pending_index(netbk->pending_prod++);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
/* Not the first error? Preceding frags already invalidated. */
if (err)
continue;
/* First error: invalidate header and preceding fragments. */
pending_idx = *((u16 *)skb->data);
xen_netbk_idx_release(netbk, pending_idx);
for (j = start; j < i; j++) {
pending_idx = frag_get_pending_idx(&shinfo->frags[j]);
xen_netbk_idx_release(netbk, pending_idx);
}
/* Remember the error: invalidate all subsequent fragments. */
err = newerr;
}
*gopp = gop + 1;
return err;
}
Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop.
Signed-off-by: Matthew Daley <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Ian Campbell <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,
struct sk_buff *skb,
struct gnttab_copy **gopp)
{
struct gnttab_copy *gop = *gopp;
u16 pending_idx = *((u16 *)skb->data);
struct skb_shared_info *shinfo = skb_shinfo(skb);
int nr_frags = shinfo->nr_frags;
int i, err, start;
/* Check status of header. */
err = gop->status;
if (unlikely(err))
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);
/* Skip first skb fragment if it is on same page as header fragment. */
start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
for (i = start; i < nr_frags; i++) {
int j, newerr;
pending_idx = frag_get_pending_idx(&shinfo->frags[i]);
/* Check error status: if okay then remember grant handle. */
newerr = (++gop)->status;
if (likely(!newerr)) {
/* Had a previous error? Invalidate this fragment. */
if (unlikely(err))
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
continue;
}
/* Error on this fragment: respond to client with an error. */
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);
/* Not the first error? Preceding frags already invalidated. */
if (err)
continue;
/* First error: invalidate header and preceding fragments. */
pending_idx = *((u16 *)skb->data);
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
for (j = start; j < i; j++) {
pending_idx = frag_get_pending_idx(&shinfo->frags[j]);
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
}
/* Remember the error: invalidate all subsequent fragments. */
err = newerr;
}
*gopp = gop + 1;
return err;
}
| 166,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
JAS_DBGLOG(1, (
"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n",
hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off
));
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
JAS_DBGLOG(1,
("BMP information: len %d; width %d; height %d; numplanes %d; "
"depth %d; enctype %d; siz %d; hres %d; vres %d; numcolors %d; "
"mincolors %d\n", info->len, info->width, info->height, info->numplanes,
info->depth, info->enctype, info->siz, info->hres, info->vres,
info->numcolors, info->mincolors));
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
Commit Message: Fixed a problem with a null pointer dereference in the BMP decoder.
CWE ID: CWE-476 | jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
image = 0;
info = 0;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
goto error;
//return 0;
}
JAS_DBGLOG(1, (
"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n",
hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off
));
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
//return 0;
goto error;
}
JAS_DBGLOG(1,
("BMP information: len %ld; width %ld; height %ld; numplanes %d; "
"depth %d; enctype %ld; siz %ld; hres %ld; vres %ld; numcolors %ld; "
"mincolors %ld\n", JAS_CAST(long, info->len),
JAS_CAST(long, info->width), JAS_CAST(long, info->height),
JAS_CAST(long, info->numplanes), JAS_CAST(long, info->depth),
JAS_CAST(long, info->enctype), JAS_CAST(long, info->siz),
JAS_CAST(long, info->hres), JAS_CAST(long, info->vres),
JAS_CAST(long, info->numcolors), JAS_CAST(long, info->mincolors)));
if (info->width < 0 || info->height < 0 || info->numplanes < 0 ||
info->depth < 0 || info->siz < 0 || info->hres < 0 || info->vres < 0) {
jas_eprintf("corrupt bit stream\n");
goto error;
}
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
//bmp_info_destroy(info);
//return 0;
goto error;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
goto error;
//return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
//bmp_info_destroy(info);
//return 0;
goto error;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
//bmp_info_destroy(info);
//return 0;
goto error;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
//bmp_info_destroy(info);
//jas_image_destroy(image);
//return 0;
goto error;
}
bmp_info_destroy(info);
return image;
error:
if (info) {
bmp_info_destroy(info);
}
if (image) {
jas_image_destroy(image);
}
return 0;
}
| 168,756 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int em_call(struct x86_emulate_ctxt *ctxt)
{
long rel = ctxt->src.val;
ctxt->src.val = (unsigned long)ctxt->_eip;
jmp_rel(ctxt, rel);
return em_push(ctxt);
}
Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches
Before changing rip (during jmp, call, ret, etc.) the target should be asserted
to be canonical one, as real CPUs do. During sysret, both target rsp and rip
should be canonical. If any of these values is noncanonical, a #GP exception
should occur. The exception to this rule are syscall and sysenter instructions
in which the assigned rip is checked during the assignment to the relevant
MSRs.
This patch fixes the emulator to behave as real CPUs do for near branches.
Far branches are handled by the next patch.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int em_call(struct x86_emulate_ctxt *ctxt)
{
int rc;
long rel = ctxt->src.val;
ctxt->src.val = (unsigned long)ctxt->_eip;
rc = jmp_rel(ctxt, rel);
if (rc != X86EMUL_CONTINUE)
return rc;
return em_push(ctxt);
}
| 169,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 enum_dir(sc_path_t path, int depth)
{
sc_file_t *file;
int r, file_type;
u8 files[SC_MAX_APDU_BUFFER_SIZE];
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_select_file(card, &path, &file);
sc_unlock(card);
if (r) {
fprintf(stderr, "SELECT FILE failed: %s\n", sc_strerror(r));
return 1;
}
print_file(card, file, &path, depth);
file_type = file->type;
sc_file_free(file);
if (file_type == SC_FILE_TYPE_DF) {
int i;
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_list_files(card, files, sizeof(files));
sc_unlock(card);
if (r < 0) {
fprintf(stderr, "sc_list_files() failed: %s\n", sc_strerror(r));
return 1;
}
if (r == 0) {
printf("Empty directory\n");
} else
for (i = 0; i < r/2; i++) {
sc_path_t tmppath;
memset(&tmppath, 0, sizeof(tmppath));
memcpy(&tmppath, &path, sizeof(path));
memcpy(tmppath.value + tmppath.len, files + 2*i, 2);
tmppath.len += 2;
enum_dir(tmppath, depth + 1);
}
}
return 0;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static int enum_dir(sc_path_t path, int depth)
{
sc_file_t *file;
int r, file_type;
u8 files[SC_MAX_EXT_APDU_BUFFER_SIZE];
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_select_file(card, &path, &file);
sc_unlock(card);
if (r) {
fprintf(stderr, "SELECT FILE failed: %s\n", sc_strerror(r));
return 1;
}
print_file(card, file, &path, depth);
file_type = file->type;
sc_file_free(file);
if (file_type == SC_FILE_TYPE_DF) {
int i;
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_list_files(card, files, sizeof(files));
sc_unlock(card);
if (r < 0) {
fprintf(stderr, "sc_list_files() failed: %s\n", sc_strerror(r));
return 1;
}
if (r == 0) {
printf("Empty directory\n");
} else {
for (i = 0; i < r/2; i++) {
sc_path_t tmppath;
memset(&tmppath, 0, sizeof(tmppath));
memcpy(&tmppath, &path, sizeof(path));
memcpy(tmppath.value + tmppath.len, files + 2*i, 2);
tmppath.len += 2;
enum_dir(tmppath, depth + 1);
}
}
}
return 0;
}
| 169,069 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session,
TargetRegistry* registry) {
if (!ShouldAllowSession(session))
return false;
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(
GetId(),
frame_tree_node_ ? frame_tree_node_->devtools_frame_token()
: base::UnguessableToken(),
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler(
session->client()->MayDiscoverTargets()
? protocol::TargetHandler::AccessMode::kRegular
: protocol::TargetHandler::AccessMode::kAutoAttachOnly,
GetId(), registry)));
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (!frame_tree_node_ || !frame_tree_node_->parent()) {
session->AddHandler(base::WrapUnique(
new protocol::TracingHandler(frame_tree_node_, GetIOContext())));
}
if (sessions().empty()) {
bool use_video_capture_api = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
use_video_capture_api = false;
#endif
if (!use_video_capture_api)
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions
Bug: 866426
Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4
Reviewed-on: https://chromium-review.googlesource.com/c/1270007
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598004}
CWE ID: CWE-20 | bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session,
TargetRegistry* registry) {
if (!ShouldAllowSession(session))
return false;
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(
GetId(),
frame_tree_node_ ? frame_tree_node_->devtools_frame_token()
: base::UnguessableToken(),
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler(
session->client()->MayDiscoverTargets()
? protocol::TargetHandler::AccessMode::kRegular
: protocol::TargetHandler::AccessMode::kAutoAttachOnly,
GetId(), registry)));
session->AddHandler(base::WrapUnique(new protocol::PageHandler(
emulation_handler, session->client()->MayAffectLocalFiles())));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (!frame_tree_node_ || !frame_tree_node_->parent()) {
session->AddHandler(base::WrapUnique(
new protocol::TracingHandler(frame_tree_node_, GetIOContext())));
}
if (sessions().empty()) {
bool use_video_capture_api = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
use_video_capture_api = false;
#endif
if (!use_video_capture_api)
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
| 172,609 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_get_asm_flags (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
return (png_ptr? 0L: 0L);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_get_asm_flags (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
PNG_UNUSED(png_ptr)
return 0L;
}
| 172,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: bool SimplifiedBackwardsTextIterator::handleTextNode()
{
m_lastTextNode = m_node;
int startOffset;
int offsetInNode;
RenderText* renderer = handleFirstLetter(startOffset, offsetInNode);
if (!renderer)
return true;
String text = renderer->text();
if (!renderer->firstTextBox() && text.length() > 0)
return true;
m_positionEndOffset = m_offset;
m_offset = startOffset + offsetInNode;
m_positionNode = m_node;
m_positionStartOffset = m_offset;
ASSERT(0 <= m_positionStartOffset - offsetInNode && m_positionStartOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(1 <= m_positionEndOffset - offsetInNode && m_positionEndOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(m_positionStartOffset <= m_positionEndOffset);
m_textLength = m_positionEndOffset - m_positionStartOffset;
m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode);
ASSERT(m_textCharacters >= text.characters());
ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length()));
m_lastCharacter = text[m_positionEndOffset - 1];
return !m_shouldHandleFirstLetter;
}
Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure.
BUG=156930,177197
[email protected]
Review URL: https://codereview.chromium.org/15057010
git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | bool SimplifiedBackwardsTextIterator::handleTextNode()
{
m_lastTextNode = m_node;
int startOffset;
int offsetInNode;
RenderText* renderer = handleFirstLetter(startOffset, offsetInNode);
if (!renderer)
return true;
String text = renderer->text();
if (!renderer->firstTextBox() && text.length() > 0)
return true;
m_positionEndOffset = m_offset;
m_offset = startOffset + offsetInNode;
m_positionNode = m_node;
m_positionStartOffset = m_offset;
ASSERT(0 <= m_positionStartOffset - offsetInNode && m_positionStartOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(1 <= m_positionEndOffset - offsetInNode && m_positionEndOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(m_positionStartOffset <= m_positionEndOffset);
m_textLength = m_positionEndOffset - m_positionStartOffset;
m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode);
ASSERT(m_textCharacters >= text.characters());
RELEASE_ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length()));
m_lastCharacter = text[m_positionEndOffset - 1];
return !m_shouldHandleFirstLetter;
}
| 171,311 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void sum_init(int csum_type, int seed)
{
char s[4];
if (csum_type < 0)
csum_type = parse_csum_name(NULL, 0);
cursum_type = csum_type;
switch (csum_type) {
case CSUM_MD5:
md5_begin(&md);
break;
case CSUM_MD4:
mdfour_begin(&md);
sumresidue = 0;
break;
case CSUM_MD4_OLD:
break;
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
mdfour_begin(&md);
sumresidue = 0;
SIVAL(s, 0, seed);
break;
}
}
Commit Message:
CWE ID: CWE-354 | void sum_init(int csum_type, int seed)
{
char s[4];
if (csum_type < 0)
csum_type = parse_csum_name(NULL, 0);
cursum_type = csum_type;
switch (csum_type) {
case CSUM_MD5:
md5_begin(&md);
break;
case CSUM_MD4:
mdfour_begin(&md);
sumresidue = 0;
break;
case CSUM_MD4_OLD:
break;
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
case CSUM_MD4_ARCHAIC:
mdfour_begin(&md);
sumresidue = 0;
SIVAL(s, 0, seed);
break;
}
}
| 164,646 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionTtsController::SpeakNextUtterance() {
while (!utterance_queue_.empty() && !current_utterance_) {
Utterance* utterance = utterance_queue_.front();
utterance_queue_.pop();
SpeakNow(utterance);
}
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ExtensionTtsController::SpeakNextUtterance() {
| 170,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: void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) {
cached_width_ = width;
cached_height_ = height;
gl_->ResizeCHROMIUM(width, height);
#ifdef FLIP_FRAMEBUFFER_VERTICALLY
scanline_.reset(new uint8[width * 4]);
#endif // FLIP_FRAMEBUFFER_VERTICALLY
}
Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip.
BUG=116637
TEST=manual test from bug report with ASAN
Review URL: https://chromiumcodereview.appspot.com/9617038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) {
cached_width_ = width;
cached_height_ = height;
gl_->ResizeCHROMIUM(width, height);
}
| 171,064 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ossl_cipher_update(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
unsigned char *in;
long in_len, out_len;
VALUE data, str;
rb_scan_args(argc, argv, "11", &data, &str);
StringValue(data);
in = (unsigned char *)RSTRING_PTR(data);
if ((in_len = RSTRING_LEN(data)) == 0)
ossl_raise(rb_eArgError, "data must not be empty");
GetCipher(self, ctx);
out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);
if (out_len <= 0) {
ossl_raise(rb_eRangeError,
"data too big to make output buffer: %ld bytes", in_len);
}
if (NIL_P(str)) {
str = rb_str_new(0, out_len);
} else {
StringValue(str);
rb_str_resize(str, out_len);
}
if (!ossl_cipher_update_long(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len))
ossl_raise(eCipherError, NULL);
assert(out_len < RSTRING_LEN(str));
rb_str_set_len(str, out_len);
return str;
}
Commit Message: cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49
CWE ID: CWE-310 | ossl_cipher_update(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
unsigned char *in;
long in_len, out_len;
VALUE data, str;
rb_scan_args(argc, argv, "11", &data, &str);
if (!RTEST(rb_attr_get(self, id_key_set)))
ossl_raise(eCipherError, "key not set");
StringValue(data);
in = (unsigned char *)RSTRING_PTR(data);
if ((in_len = RSTRING_LEN(data)) == 0)
ossl_raise(rb_eArgError, "data must not be empty");
GetCipher(self, ctx);
out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);
if (out_len <= 0) {
ossl_raise(rb_eRangeError,
"data too big to make output buffer: %ld bytes", in_len);
}
if (NIL_P(str)) {
str = rb_str_new(0, out_len);
} else {
StringValue(str);
rb_str_resize(str, out_len);
}
if (!ossl_cipher_update_long(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len))
ossl_raise(eCipherError, NULL);
assert(out_len < RSTRING_LEN(str));
rb_str_set_len(str, out_len);
return str;
}
| 168,783 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IsValidSymbolicLink(const FilePath& file_path,
GDataCache::CacheSubDirectoryType sub_dir_type,
const std::vector<FilePath>& cache_paths,
std::string* reason) {
DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PINNED ||
sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING);
FilePath destination;
if (!file_util::ReadSymbolicLink(file_path, &destination)) {
*reason = "failed to read the symlink (maybe not a symlink)";
return false;
}
if (!file_util::PathExists(destination)) {
*reason = "pointing to a non-existent file";
return false;
}
if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED &&
destination == FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull)) {
return true;
}
if (!cache_paths[GDataCache::CACHE_TYPE_PERSISTENT].IsParent(destination)) {
*reason = "pointing to a file outside of persistent directory";
return false;
}
return true;
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool IsValidSymbolicLink(const FilePath& file_path,
| 170,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) {
return -1;
}
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
supported_features = k->get_features(qbus->parent);
error_report("Features 0x%x unsupported. Allowed features: 0x%x",
features, supported_features);
features, supported_features);
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
Commit Message:
CWE ID: CWE-119 | int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
int32_t config_len;
uint32_t num;
uint32_t features;
uint32_t supported_features;
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) {
return -1;
}
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
supported_features = k->get_features(qbus->parent);
error_report("Features 0x%x unsupported. Allowed features: 0x%x",
features, supported_features);
features, supported_features);
return -1;
}
config_len = qemu_get_be32(f);
if (config_len != vdev->config_len) {
error_report("Unexpected config length 0x%x. Expected 0x%zx",
config_len, vdev->config_len);
return -1;
}
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
| 165,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len, addr_len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_msg(skb, sizeof(struct udphdr),
msg, copied);
else {
err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr),
msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv_offset(msg, skb, sizeof(struct udphdr));
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
Commit Message: udp: fix behavior of wrong checksums
We have two problems in UDP stack related to bogus checksums :
1) We return -EAGAIN to application even if receive queue is not empty.
This breaks applications using edge trigger epoll()
2) Under UDP flood, we can loop forever without yielding to other
processes, potentially hanging the host, especially on non SMP.
This patch is an attempt to make things better.
We might in the future add extra support for rt applications
wanting to better control time spent doing a recv() in a hostile
environment. For example we could validate checksums before queuing
packets in socket receive queue.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len, addr_len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_msg(skb, sizeof(struct udphdr),
msg, copied);
else {
err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr),
msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv_offset(msg, skb, sizeof(struct udphdr));
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
}
unlock_sock_fast(sk, slow);
/* starting over for a new packet, but check if we need to yield */
cond_resched();
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
| 166,596 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GLSurfaceEGLSurfaceControl::CommitOverlayPlanesAsync(
SwapCompletionCallback completion_callback,
PresentationCallback presentation_callback) {
CommitPendingTransaction(std::move(completion_callback),
std::move(presentation_callback));
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
[email protected]
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <[email protected]>
Commit-Queue: Antoine Labour <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID: | void GLSurfaceEGLSurfaceControl::CommitOverlayPlanesAsync(
SwapCompletionCallback completion_callback,
PresentationCallback presentation_callback) {
CommitPendingTransaction(window_rect_, std::move(completion_callback),
std::move(presentation_callback));
}
void GLSurfaceEGLSurfaceControl::PostSubBufferAsync(
int x,
int y,
int width,
int height,
SwapCompletionCallback completion_callback,
PresentationCallback presentation_callback) {
CommitPendingTransaction(gfx::Rect(x, y, width, height),
std::move(completion_callback),
std::move(presentation_callback));
}
| 172,107 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PresentationConnectionProxy::OnClose() {
DCHECK(target_connection_ptr_);
source_connection_->didChangeState(
blink::WebPresentationConnectionState::Closed);
target_connection_ptr_->DidChangeState(
content::PRESENTATION_CONNECTION_STATE_CLOSED);
}
Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures
Add layout test.
1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead.
BUG=697719
Review-Url: https://codereview.chromium.org/2730123003
Cr-Commit-Position: refs/heads/master@{#455225}
CWE ID: | void PresentationConnectionProxy::OnClose() {
DCHECK(target_connection_ptr_);
source_connection_->didClose();
target_connection_ptr_->DidChangeState(
content::PRESENTATION_CONNECTION_STATE_CLOSED);
}
| 172,045 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_push_save_buffer(png_structp png_ptr)
{
if (png_ptr->save_buffer_size)
{
if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
{
png_size_t i, istop;
png_bytep sp;
png_bytep dp;
istop = png_ptr->save_buffer_size;
for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
i < istop; i++, sp++, dp++)
{
*dp = *sp;
}
}
}
if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
png_ptr->save_buffer_max)
{
png_size_t new_max;
png_bytep old_buffer;
if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
(png_ptr->current_buffer_size + 256))
{
png_error(png_ptr, "Potential overflow of save_buffer");
}
new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
old_buffer = png_ptr->save_buffer;
png_ptr->save_buffer = (png_bytep)png_malloc_warn(png_ptr,
(png_uint_32)new_max);
if (png_ptr->save_buffer == NULL)
{
png_free(png_ptr, old_buffer);
png_error(png_ptr, "Insufficient memory for save_buffer");
}
png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
png_free(png_ptr, old_buffer);
png_ptr->save_buffer_max = new_max;
}
if (png_ptr->current_buffer_size)
{
png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
png_ptr->save_buffer_size += png_ptr->current_buffer_size;
png_ptr->current_buffer_size = 0;
}
png_ptr->save_buffer_ptr = png_ptr->save_buffer;
png_ptr->buffer_size = 0;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_push_save_buffer(png_structp png_ptr)
{
if (png_ptr->save_buffer_size)
{
if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
{
png_size_t i, istop;
png_bytep sp;
png_bytep dp;
istop = png_ptr->save_buffer_size;
for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
i < istop; i++, sp++, dp++)
{
*dp = *sp;
}
}
}
if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
png_ptr->save_buffer_max)
{
png_size_t new_max;
png_bytep old_buffer;
if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
(png_ptr->current_buffer_size + 256))
{
png_error(png_ptr, "Potential overflow of save_buffer");
}
new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
old_buffer = png_ptr->save_buffer;
png_ptr->save_buffer = (png_bytep)png_malloc_warn(png_ptr,
(png_uint_32)new_max);
if (png_ptr->save_buffer == NULL)
{
png_free(png_ptr, old_buffer);
png_error(png_ptr, "Insufficient memory for save_buffer");
}
else
{
png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
png_free(png_ptr, old_buffer);
png_ptr->save_buffer_max = new_max;
}
}
if (png_ptr->current_buffer_size)
{
png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
png_ptr->save_buffer_size += png_ptr->current_buffer_size;
png_ptr->current_buffer_size = 0;
}
png_ptr->save_buffer_ptr = png_ptr->save_buffer;
png_ptr->buffer_size = 0;
}
| 172,168 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: untrusted_launcher_response_callback (GtkDialog *dialog,
int response_id,
ActivateParametersDesktop *parameters)
{
GdkScreen *screen;
char *uri;
GFile *file;
switch (response_id)
{
case RESPONSE_RUN:
{
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
uri = nautilus_file_get_uri (parameters->file);
DEBUG ("Launching untrusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
}
break;
case RESPONSE_MARK_TRUSTED:
{
file = nautilus_file_get_location (parameters->file);
nautilus_file_mark_desktop_file_trusted (file,
parameters->parent_window,
TRUE,
NULL, NULL);
g_object_unref (file);
}
break;
default:
{
/* Just destroy dialog */
}
break;
}
gtk_widget_destroy (GTK_WIDGET (dialog));
activate_parameters_desktop_free (parameters);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | untrusted_launcher_response_callback (GtkDialog *dialog,
int response_id,
ActivateParametersDesktop *parameters)
{
GdkScreen *screen;
char *uri;
GFile *file;
switch (response_id)
{
case GTK_RESPONSE_OK:
{
file = nautilus_file_get_location (parameters->file);
/* We need to do this in order to prevent malicious desktop files
* with the executable bit already set.
* See https://bugzilla.gnome.org/show_bug.cgi?id=777991
*/
nautilus_file_set_metadata (parameters->file, NAUTILUS_METADATA_KEY_DESKTOP_FILE_TRUSTED,
NULL,
"yes");
nautilus_file_mark_desktop_file_executable (file,
parameters->parent_window,
TRUE,
NULL, NULL);
/* Need to force a reload of the attributes so is_trusted is marked
* correctly. Not sure why the general monitor doesn't fire in this
* case when setting the metadata
*/
nautilus_file_invalidate_all_attributes (parameters->file);
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
uri = nautilus_file_get_uri (parameters->file);
DEBUG ("Launching untrusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
g_object_unref (file);
}
break;
default:
{
/* Just destroy dialog */
}
break;
}
gtk_widget_destroy (GTK_WIDGET (dialog));
activate_parameters_desktop_free (parameters);
}
| 167,753 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::Load(long long& pos, long& len) const
{
assert(m_pSegment);
assert(m_pos >= m_element_start);
if (m_timecode >= 0) //at least partially loaded
return 0;
assert(m_pos == m_element_start);
assert(m_element_size < 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
const int status = pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
assert((total < 0) || (m_pos <= total)); //TODO: verify this
pos = m_pos;
long long cluster_size = -1;
{
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error or underflow
return static_cast<long>(result);
if (result > 0) //underflow (weird)
return E_BUFFER_NOT_FULL;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id_ = ReadUInt(pReader, pos, len);
if (id_ < 0) //error
return static_cast<long>(id_);
if (id_ != 0x0F43B675) //Cluster ID
return E_FILE_FORMAT_INVALID;
pos += len; //consume id
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(cluster_size);
if (size == 0)
return E_FILE_FORMAT_INVALID; //TODO: verify this
pos += len; //consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size != unknown_size)
cluster_size = size;
}
//// pos points to start of payload
#if 0
len = static_cast<long>(size_);
if (cluster_stop > avail)
return E_BUFFER_NOT_FULL;
#endif
long long timecode = -1;
long long new_pos = -1;
bool bBlock = false;
long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size;
for (;;)
{
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return static_cast<long>(id);
if (id == 0)
return E_FILE_FORMAT_INVALID;
if (id == 0x0F43B675) //Cluster ID
break;
if (id == 0x0C53BB6B) //Cues ID
break;
pos += len; //consume ID field
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; //consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) //weird
continue;
if ((cluster_stop >= 0) && ((pos + size) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (id == 0x67) //TimeCode ID
{
len = static_cast<long>(size);
if ((pos + size) > avail)
return E_BUFFER_NOT_FULL;
timecode = UnserializeUInt(pReader, pos, size);
if (timecode < 0) //error (or underflow)
return static_cast<long>(timecode);
new_pos = pos + size;
if (bBlock)
break;
}
else if (id == 0x20) //BlockGroup ID
{
bBlock = true;
break;
}
else if (id == 0x23) //SimpleBlock ID
{
bBlock = true;
break;
}
pos += size; //consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert((cluster_stop < 0) || (pos <= cluster_stop));
if (timecode < 0) //no timecode found
return E_FILE_FORMAT_INVALID;
if (!bBlock)
return E_FILE_FORMAT_INVALID;
m_pos = new_pos; //designates position just beyond timecode payload
m_timecode = timecode; // m_timecode >= 0 means we're partially loaded
if (cluster_size >= 0)
m_element_size = cluster_stop - m_element_start;
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Cluster::Load(long long& pos, long& len) const
if (m_timecode >= 0) // at least partially loaded
return 0;
assert(m_pos == m_element_start);
assert(m_element_size < 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
const int status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
assert((total < 0) || (m_pos <= total)); // TODO: verify this
pos = m_pos;
long long cluster_size = -1;
{
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error or underflow
return static_cast<long>(result);
if (result > 0) // underflow (weird)
return E_BUFFER_NOT_FULL;
// if ((pos + len) > segment_stop)
// return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id_ = ReadUInt(pReader, pos, len);
if (id_ < 0) // error
return static_cast<long>(id_);
if (id_ != 0x0F43B675) // Cluster ID
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
// read cluster size
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
// if ((pos + len) > segment_stop)
// return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(cluster_size);
if (size == 0)
return E_FILE_FORMAT_INVALID; // TODO: verify this
pos += len; // consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size != unknown_size)
cluster_size = size;
}
//// pos points to start of payload
#if 0
len = static_cast<long>(size_);
if (cluster_stop > avail)
return E_BUFFER_NOT_FULL;
#endif
long long timecode = -1;
long long new_pos = -1;
bool bBlock = false;
long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size;
for (;;) {
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
// Parse ID
| 174,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: l2tp_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
ND_PRINT((ndo, "%04x, ", EXTRACT_16BITS(ptr))); ptr++; /* Disconnect Code */
ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(ptr))); ptr++; /* Control Protocol Number */
ND_PRINT((ndo, "%s", tok2str(l2tp_cc_direction2str,
"Direction-#%u", *((const u_char *)ptr++))));
if (length > 5) {
ND_PRINT((ndo, " "));
print_string(ndo, (const u_char *)ptr, length-5);
}
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | l2tp_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
if (length < 5) {
ND_PRINT((ndo, "AVP too short"));
return;
}
/* Disconnect Code */
ND_PRINT((ndo, "%04x, ", EXTRACT_16BITS(dat)));
dat += 2;
length -= 2;
/* Control Protocol Number */
ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(dat)));
dat += 2;
length -= 2;
/* Direction */
ND_PRINT((ndo, "%s", tok2str(l2tp_cc_direction2str,
"Direction-#%u", EXTRACT_8BITS(ptr))));
ptr++;
length--;
if (length != 0) {
ND_PRINT((ndo, " "));
print_string(ndo, (const u_char *)ptr, length);
}
}
| 167,897 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
const uint8_t *name, uint8_t *dst, int dst_size)
{
int namelen = strlen(name);
int len;
while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) {
len = ff_amf_tag_size(data, data_end);
if (len < 0)
len = data_end - data;
data += len;
}
if (data_end - data < 3)
return -1;
data++;
for (;;) {
int size = bytestream_get_be16(&data);
if (!size)
break;
if (size < 0 || size >= data_end - data)
return -1;
data += size;
if (size == namelen && !memcmp(data-size, name, namelen)) {
switch (*data++) {
case AMF_DATA_TYPE_NUMBER:
snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data)));
break;
case AMF_DATA_TYPE_BOOL:
snprintf(dst, dst_size, "%s", *data ? "true" : "false");
break;
case AMF_DATA_TYPE_STRING:
len = bytestream_get_be16(&data);
av_strlcpy(dst, data, FFMIN(len+1, dst_size));
break;
default:
return -1;
}
return 0;
}
len = ff_amf_tag_size(data, data_end);
if (len < 0 || len >= data_end - data)
return -1;
data += len;
}
return -1;
}
Commit Message: avformat/rtmppkt: Convert ff_amf_get_field_value() to bytestream2
Fixes: out of array accesses
Found-by: JunDong Xie of Ant-financial Light-Year Security Lab
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-20 | int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
static int amf_get_field_value2(GetByteContext *gb,
const uint8_t *name, uint8_t *dst, int dst_size)
{
int namelen = strlen(name);
int len;
while (bytestream2_peek_byte(gb) != AMF_DATA_TYPE_OBJECT && bytestream2_get_bytes_left(gb) > 0) {
int ret = amf_tag_skip(gb);
if (ret < 0)
return -1;
}
if (bytestream2_get_bytes_left(gb) < 3)
return -1;
bytestream2_get_byte(gb);
for (;;) {
int size = bytestream2_get_be16(gb);
if (!size)
break;
if (size < 0 || size >= bytestream2_get_bytes_left(gb))
return -1;
bytestream2_skip(gb, size);
if (size == namelen && !memcmp(gb->buffer-size, name, namelen)) {
switch (bytestream2_get_byte(gb)) {
case AMF_DATA_TYPE_NUMBER:
snprintf(dst, dst_size, "%g", av_int2double(bytestream2_get_be64(gb)));
break;
case AMF_DATA_TYPE_BOOL:
snprintf(dst, dst_size, "%s", bytestream2_get_byte(gb) ? "true" : "false");
break;
case AMF_DATA_TYPE_STRING:
len = bytestream2_get_be16(gb);
if (dst_size < 1)
return -1;
if (dst_size < len + 1)
len = dst_size - 1;
bytestream2_get_buffer(gb, dst, len);
dst[len] = 0;
break;
default:
return -1;
}
return 0;
}
len = amf_tag_skip(gb);
if (len < 0 || bytestream2_get_bytes_left(gb) <= 0)
return -1;
}
return -1;
}
| 168,001 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: int Track::Info::Copy(Info& dst) const
{
if (&dst == this)
return 0;
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0)
{
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | int Track::Info::Copy(Info& dst) const
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
// We now copy the string member variables from src to dst.
// This involves memory allocation so in principle the operation
// can fail (indeed, that's why we have Info::Copy), so we must
// report this to the caller. An error return from this function
// therefore implies that the copy was only partially successful.
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0) {
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
const BlockEntry* Track::GetEOS() const { return &m_eos; }
long Track::GetType() const { return m_info.type; }
long Track::GetNumber() const { return m_info.number; }
unsigned long long Track::GetUid() const { return m_info.uid; }
const char* Track::GetNameAsUTF8() const { return m_info.nameAsUTF8; }
const char* Track::GetLanguage() const { return m_info.language; }
const char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; }
const char* Track::GetCodecId() const { return m_info.codecId; }
const unsigned char* Track::GetCodecPrivate(size_t& size) const {
size = m_info.codecPrivateSize;
return m_info.codecPrivate;
}
bool Track::GetLacing() const { return m_info.lacing; }
unsigned long long Track::GetDefaultDuration() const {
return m_info.defaultDuration;
}
unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; }
unsigned long long Track::GetSeekPreRoll() const { return m_info.seekPreRoll; }
long Track::GetFirst(const BlockEntry*& pBlockEntry) const {
const Cluster* pCluster = m_pSegment->GetFirst();
for (int i = 0;;) {
if (pCluster == NULL) {
pBlockEntry = GetEOS();
return 1;
}
| 174,253 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 close_uinput (void)
{
BTIF_TRACE_DEBUG("%s", __FUNCTION__);
if (uinput_fd > 0) {
ioctl(uinput_fd, UI_DEV_DESTROY);
close(uinput_fd);
uinput_fd = -1;
}
}
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 | void close_uinput (void)
{
BTIF_TRACE_DEBUG("%s", __FUNCTION__);
if (uinput_fd > 0) {
TEMP_FAILURE_RETRY(ioctl(uinput_fd, UI_DEV_DESTROY));
close(uinput_fd);
uinput_fd = -1;
}
}
| 173,450 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppCache::AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry) {
std::pair<EntryMap::iterator, bool> ret =
entries_.insert(EntryMap::value_type(url, entry));
if (!ret.second)
ret.first->second.add_types(entry.types());
else
cache_size_ += entry.response_size(); // New entry. Add to cache size.
return ret.second;
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | bool AppCache::AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry) {
std::pair<EntryMap::iterator, bool> ret =
entries_.insert(EntryMap::value_type(url, entry));
if (!ret.second) {
ret.first->second.add_types(entry.types());
} else {
cache_size_ += entry.response_size(); // New entry. Add to cache size.
padding_size_ += entry.padding_size();
}
return ret.second;
}
| 172,968 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ScreenLayoutObserver::GetDisplayMessageForNotification(
const ScreenLayoutObserver::DisplayInfoMap& old_info,
base::string16* out_message,
base::string16* out_additional_message) {
if (old_display_mode_ != current_display_mode_) {
if (current_display_mode_ == DisplayMode::MIRRORING) {
*out_message = GetEnterMirrorModeMessage();
return true;
}
if (old_display_mode_ == DisplayMode::MIRRORING &&
GetExitMirrorModeMessage(out_message, out_additional_message)) {
return true;
}
if (current_display_mode_ == DisplayMode::UNIFIED) {
*out_message = GetEnterUnifiedModeMessage();
return true;
}
if (old_display_mode_ == DisplayMode::UNIFIED) {
*out_message = GetExitUnifiedModeMessage();
return true;
}
if (current_display_mode_ == DisplayMode::DOCKED ||
old_display_mode_ == DisplayMode::DOCKED) {
return false;
}
}
if (display_info_.size() < old_info.size()) {
for (const auto& iter : old_info) {
if (display_info_.count(iter.first))
continue;
*out_message =
GetDisplayRemovedMessage(iter.second, out_additional_message);
return true;
}
} else if (display_info_.size() > old_info.size()) {
for (const auto& iter : display_info_) {
if (old_info.count(iter.first))
continue;
*out_message = GetDisplayAddedMessage(iter.first, out_additional_message);
return true;
}
}
for (const auto& iter : display_info_) {
DisplayInfoMap::const_iterator old_iter = old_info.find(iter.first);
if (old_iter == old_info.end()) {
NOTREACHED() << "A display mode transition that should have been handled"
"earlier.";
return false;
}
if (iter.second.configured_ui_scale() !=
old_iter->second.configured_ui_scale()) {
*out_additional_message = l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_DISPLAY_RESOLUTION_CHANGED,
GetDisplayName(iter.first), GetDisplaySize(iter.first));
return true;
}
if (iter.second.GetActiveRotation() !=
old_iter->second.GetActiveRotation()) {
int rotation_text_id = 0;
switch (iter.second.GetActiveRotation()) {
case display::Display::ROTATE_0:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_STANDARD_ORIENTATION;
break;
case display::Display::ROTATE_90:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_90;
break;
case display::Display::ROTATE_180:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_180;
break;
case display::Display::ROTATE_270:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_270;
break;
}
*out_additional_message = l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_DISPLAY_ROTATED, GetDisplayName(iter.first),
l10n_util::GetStringUTF16(rotation_text_id));
return true;
}
}
return false;
}
Commit Message: Avoid Showing rotation change notification when source is accelerometer
BUG=717252
TEST=Manually rotate device with accelerometer and observe there's no notification
Review-Url: https://codereview.chromium.org/2853113005
Cr-Commit-Position: refs/heads/master@{#469058}
CWE ID: CWE-17 | bool ScreenLayoutObserver::GetDisplayMessageForNotification(
const ScreenLayoutObserver::DisplayInfoMap& old_info,
base::string16* out_message,
base::string16* out_additional_message) {
if (old_display_mode_ != current_display_mode_) {
if (current_display_mode_ == DisplayMode::MIRRORING) {
*out_message = GetEnterMirrorModeMessage();
return true;
}
if (old_display_mode_ == DisplayMode::MIRRORING &&
GetExitMirrorModeMessage(out_message, out_additional_message)) {
return true;
}
if (current_display_mode_ == DisplayMode::UNIFIED) {
*out_message = GetEnterUnifiedModeMessage();
return true;
}
if (old_display_mode_ == DisplayMode::UNIFIED) {
*out_message = GetExitUnifiedModeMessage();
return true;
}
if (current_display_mode_ == DisplayMode::DOCKED ||
old_display_mode_ == DisplayMode::DOCKED) {
return false;
}
}
if (display_info_.size() < old_info.size()) {
for (const auto& iter : old_info) {
if (display_info_.count(iter.first))
continue;
*out_message =
GetDisplayRemovedMessage(iter.second, out_additional_message);
return true;
}
} else if (display_info_.size() > old_info.size()) {
for (const auto& iter : display_info_) {
if (old_info.count(iter.first))
continue;
*out_message = GetDisplayAddedMessage(iter.first, out_additional_message);
return true;
}
}
for (const auto& iter : display_info_) {
DisplayInfoMap::const_iterator old_iter = old_info.find(iter.first);
if (old_iter == old_info.end()) {
NOTREACHED() << "A display mode transition that should have been handled"
"earlier.";
return false;
}
if (iter.second.configured_ui_scale() !=
old_iter->second.configured_ui_scale()) {
*out_additional_message = l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_DISPLAY_RESOLUTION_CHANGED,
GetDisplayName(iter.first), GetDisplaySize(iter.first));
return true;
}
// We don't show rotation change notification when the rotation source is
// the accelerometer.
if (iter.second.active_rotation_source() !=
display::Display::ROTATION_SOURCE_ACCELEROMETER &&
iter.second.GetActiveRotation() !=
old_iter->second.GetActiveRotation()) {
int rotation_text_id = 0;
switch (iter.second.GetActiveRotation()) {
case display::Display::ROTATE_0:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_STANDARD_ORIENTATION;
break;
case display::Display::ROTATE_90:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_90;
break;
case display::Display::ROTATE_180:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_180;
break;
case display::Display::ROTATE_270:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_270;
break;
}
*out_additional_message = l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_DISPLAY_ROTATED, GetDisplayName(iter.first),
l10n_util::GetStringUTF16(rotation_text_id));
return true;
}
}
return false;
}
| 172,043 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,367 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
FILE
*file;
Image
*image,
*next_image,
*pwp_image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
register Image
*p;
register ssize_t
i;
size_t
filesize,
length;
ssize_t
count;
unsigned char
magick[MaxTextExtent];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
pwp_image=AcquireImage(image_info);
image=pwp_image;
status=OpenBlob(image_info,pwp_image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
count=ReadBlob(pwp_image,5,magick);
if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
read_info=CloneImageInfo(image_info);
(void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
(void *) NULL);
SetImageInfoBlob(read_info,(void *) NULL,0);
unique_file=AcquireUniqueFileResource(read_info->filename);
for ( ; ; )
{
for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))
{
for (i=0; i < 17; i++)
magick[i]=magick[i+1];
magick[17]=(unsigned char) c;
if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0)
break;
}
if (c == EOF)
break;
if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0)
{
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Dump SFW image to a temporary file.
*/
file=(FILE *) NULL;
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowFileException(exception,FileOpenError,"UnableToWriteFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=fwrite("SFW94A",1,6,file);
(void) length;
filesize=65535UL*magick[2]+256L*magick[1]+magick[0];
for (i=0; i < (ssize_t) filesize; i++)
{
c=ReadBlobByte(pwp_image);
(void) fputc(c,file);
}
(void) fclose(file);
next_image=ReadImage(read_info,exception);
if (next_image == (Image *) NULL)
break;
(void) FormatLocaleString(next_image->filename,MaxTextExtent,
"slide_%02ld.sfw",(long) next_image->scene);
if (image == (Image *) NULL)
image=next_image;
else
{
/*
Link image into image list.
*/
for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;
next_image->previous=p;
next_image->scene=p->scene+1;
p->next=next_image;
}
if (image_info->number_scenes != 0)
if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),
GetBlobSize(pwp_image));
if (status == MagickFalse)
break;
}
if (unique_file != -1)
(void) close(unique_file);
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
(void) CloseBlob(pwp_image);
pwp_image=DestroyImage(pwp_image);
if (EOFBlob(image) != MagickFalse)
{
char
*message;
message=GetExceptionMessage(errno);
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"UnexpectedEndOfFile","`%s': %s",image->filename,message);
message=DestroyString(message);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: Prevent memory use after free
CWE ID: CWE-416 | static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
FILE
*file;
Image
*image,
*next_image,
*pwp_image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
register Image
*p;
register ssize_t
i;
size_t
filesize,
length;
ssize_t
count;
unsigned char
magick[MaxTextExtent];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
pwp_image=AcquireImage(image_info);
image=pwp_image;
status=OpenBlob(image_info,pwp_image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
count=ReadBlob(pwp_image,5,magick);
if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
read_info=CloneImageInfo(image_info);
(void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
(void *) NULL);
SetImageInfoBlob(read_info,(void *) NULL,0);
unique_file=AcquireUniqueFileResource(read_info->filename);
for ( ; ; )
{
for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))
{
for (i=0; i < 17; i++)
magick[i]=magick[i+1];
magick[17]=(unsigned char) c;
if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0)
break;
}
if (c == EOF)
break;
if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0)
{
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Dump SFW image to a temporary file.
*/
file=(FILE *) NULL;
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowFileException(exception,FileOpenError,"UnableToWriteFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=fwrite("SFW94A",1,6,file);
(void) length;
filesize=65535UL*magick[2]+256L*magick[1]+magick[0];
for (i=0; i < (ssize_t) filesize; i++)
{
c=ReadBlobByte(pwp_image);
(void) fputc(c,file);
}
(void) fclose(file);
next_image=ReadImage(read_info,exception);
if (next_image == (Image *) NULL)
break;
(void) FormatLocaleString(next_image->filename,MaxTextExtent,
"slide_%02ld.sfw",(long) next_image->scene);
if (image == (Image *) NULL)
image=next_image;
else
{
/*
Link image into image list.
*/
for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;
next_image->previous=p;
next_image->scene=p->scene+1;
p->next=next_image;
}
if (image_info->number_scenes != 0)
if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),
GetBlobSize(pwp_image));
if (status == MagickFalse)
break;
}
if (unique_file != -1)
(void) close(unique_file);
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
if (EOFBlob(image) != MagickFalse)
{
char
*message;
message=GetExceptionMessage(errno);
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"UnexpectedEndOfFile","`%s': %s",image->filename,message);
message=DestroyString(message);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,639 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cib_remote_signon(cib_t * cib, const char *name, enum cib_conn_type type)
{
int rc = pcmk_ok;
cib_remote_opaque_t *private = cib->variant_opaque;
if (private->passwd == NULL) {
struct termios settings;
int rc;
rc = tcgetattr(0, &settings);
settings.c_lflag &= ~ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
fprintf(stderr, "Password: ");
private->passwd = calloc(1, 1024);
rc = scanf("%s", private->passwd);
fprintf(stdout, "\n");
/* fprintf(stderr, "entered: '%s'\n", buffer); */
if (rc < 1) {
private->passwd = NULL;
}
settings.c_lflag |= ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
}
if (private->server == NULL || private->user == NULL) {
rc = -EINVAL;
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->command));
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->callback));
}
if (rc == pcmk_ok) {
xmlNode *hello =
cib_create_op(0, private->callback.token, CRM_OP_REGISTER, NULL, NULL, NULL, 0, NULL);
crm_xml_add(hello, F_CIB_CLIENTNAME, name);
crm_send_remote_msg(private->command.session, hello, private->command.encrypted);
free_xml(hello);
}
if (rc == pcmk_ok) {
fprintf(stderr, "%s: Opened connection to %s:%d\n", name, private->server, private->port);
cib->state = cib_connected_command;
cib->type = cib_command;
} else {
fprintf(stderr, "%s: Connection to %s:%d failed: %s\n",
name, private->server, private->port, pcmk_strerror(rc));
}
return rc;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_remote_signon(cib_t * cib, const char *name, enum cib_conn_type type)
{
int rc = pcmk_ok;
cib_remote_opaque_t *private = cib->variant_opaque;
if (private->passwd == NULL) {
struct termios settings;
int rc;
rc = tcgetattr(0, &settings);
settings.c_lflag &= ~ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
fprintf(stderr, "Password: ");
private->passwd = calloc(1, 1024);
rc = scanf("%s", private->passwd);
fprintf(stdout, "\n");
/* fprintf(stderr, "entered: '%s'\n", buffer); */
if (rc < 1) {
private->passwd = NULL;
}
settings.c_lflag |= ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
}
if (private->server == NULL || private->user == NULL) {
rc = -EINVAL;
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->command), FALSE);
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->callback), TRUE);
}
if (rc == pcmk_ok) {
xmlNode *hello =
cib_create_op(0, private->callback.token, CRM_OP_REGISTER, NULL, NULL, NULL, 0, NULL);
crm_xml_add(hello, F_CIB_CLIENTNAME, name);
crm_send_remote_msg(private->command.session, hello, private->command.encrypted);
free_xml(hello);
}
if (rc == pcmk_ok) {
fprintf(stderr, "%s: Opened connection to %s:%d\n", name, private->server, private->port);
cib->state = cib_connected_command;
cib->type = cib_command;
} else {
fprintf(stderr, "%s: Connection to %s:%d failed: %s\n",
name, private->server, private->port, pcmk_strerror(rc));
}
return rc;
}
| 166,153 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner)
: context_(base::MakeUnique<Context>(task_runner)) {}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311 | FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner)
| 173,262 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin,
const GURL& embedding_origin) {
DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin());
DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin());
if (!CanRequestObjectPermission(requesting_origin, embedding_origin))
return {};
std::vector<std::unique_ptr<Object>> results;
auto* info = new content_settings::SettingInfo();
std::unique_ptr<base::DictionaryValue> setting =
GetWebsiteSetting(requesting_origin, embedding_origin, info);
std::unique_ptr<base::Value> objects;
if (!setting->Remove(kObjectListKey, &objects))
return results;
std::unique_ptr<base::ListValue> object_list =
base::ListValue::From(std::move(objects));
if (!object_list)
return results;
for (auto& object : *object_list) {
base::DictionaryValue* object_dict;
if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) {
results.push_back(std::make_unique<Object>(
requesting_origin, embedding_origin, object_dict, info->source,
host_content_settings_map_->is_incognito()));
}
}
return results;
}
Commit Message: Fix memory leak in ChooserContextBase::GetGrantedObjects.
Bug: 854329
Change-Id: Ia163d503a4207859cd41c847c9d5f67e77580fbc
Reviewed-on: https://chromium-review.googlesource.com/c/1456080
Reviewed-by: Balazs Engedy <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Commit-Queue: Marek Haranczyk <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629919}
CWE ID: CWE-190 | ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin,
const GURL& embedding_origin) {
DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin());
DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin());
if (!CanRequestObjectPermission(requesting_origin, embedding_origin))
return {};
std::vector<std::unique_ptr<Object>> results;
content_settings::SettingInfo info;
std::unique_ptr<base::DictionaryValue> setting =
GetWebsiteSetting(requesting_origin, embedding_origin, &info);
std::unique_ptr<base::Value> objects;
if (!setting->Remove(kObjectListKey, &objects))
return results;
std::unique_ptr<base::ListValue> object_list =
base::ListValue::From(std::move(objects));
if (!object_list)
return results;
for (auto& object : *object_list) {
base::DictionaryValue* object_dict;
if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) {
results.push_back(std::make_unique<Object>(
requesting_origin, embedding_origin, object_dict, info.source,
host_content_settings_map_->is_incognito()));
}
}
return results;
}
| 172,055 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 wrmsr_interception(struct vcpu_svm *svm)
{
struct msr_data msr;
u32 ecx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
u64 data = (svm->vcpu.arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(svm->vcpu.arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
if (svm_set_msr(&svm->vcpu, &msr)) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(&svm->vcpu, 0);
} else {
trace_kvm_msr_write(ecx, data);
skip_emulated_instruction(&svm->vcpu);
}
return 1;
}
Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR
Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is
written to certain MSRs. The behavior is "almost" identical for AMD and Intel
(ignoring MSRs that are not implemented in either architecture since they would
anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
non-canonical address is written on Intel but not on AMD (which ignores the top
32-bits).
Accordingly, this patch injects a #GP on the MSRs which behave identically on
Intel and AMD. To eliminate the differences between the architecutres, the
value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to
canonical value before writing instead of injecting a #GP.
Some references from Intel and AMD manuals:
According to Intel SDM description of WRMSR instruction #GP is expected on
WRMSR "If the source register contains a non-canonical address and ECX
specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE,
IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP."
According to AMD manual instruction manual:
LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the
LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical
form, a general-protection exception (#GP) occurs."
IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the
base field must be in canonical form or a #GP fault will occur."
IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must
be in canonical form."
This patch fixes CVE-2014-3610.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int wrmsr_interception(struct vcpu_svm *svm)
{
struct msr_data msr;
u32 ecx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
u64 data = (svm->vcpu.arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(svm->vcpu.arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
if (kvm_set_msr(&svm->vcpu, &msr)) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(&svm->vcpu, 0);
} else {
trace_kvm_msr_write(ecx, data);
skip_emulated_instruction(&svm->vcpu);
}
return 1;
}
| 166,348 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SyncType GetSyncType(const Extension* extension) {
if (!IsSyncable(extension)) {
return SYNC_TYPE_NONE;
}
if (!ManifestURL::GetUpdateURL(extension).is_empty() &&
!ManifestURL::UpdatesFromGallery(extension)) {
return SYNC_TYPE_NONE;
}
if (PluginInfo::HasPlugins(extension))
return SYNC_TYPE_NONE;
switch (extension->GetType()) {
case Manifest::TYPE_EXTENSION:
return SYNC_TYPE_EXTENSION;
case Manifest::TYPE_USER_SCRIPT:
if (ManifestURL::UpdatesFromGallery(extension))
return SYNC_TYPE_EXTENSION;
return SYNC_TYPE_NONE;
case Manifest::TYPE_HOSTED_APP:
case Manifest::TYPE_LEGACY_PACKAGED_APP:
case Manifest::TYPE_PLATFORM_APP:
return SYNC_TYPE_APP;
case Manifest::TYPE_UNKNOWN:
case Manifest::TYPE_THEME:
case Manifest::TYPE_SHARED_MODULE:
return SYNC_TYPE_NONE;
}
NOTREACHED();
return SYNC_TYPE_NONE;
}
Commit Message: Fix syncing of NPAPI plugins.
This fix adds a check for |plugin| permission
while syncing NPAPI plugins.
BUG=252034
Review URL: https://chromiumcodereview.appspot.com/16816024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207830 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | SyncType GetSyncType(const Extension* extension) {
if (!IsSyncable(extension)) {
return SYNC_TYPE_NONE;
}
if (!ManifestURL::GetUpdateURL(extension).is_empty() &&
!ManifestURL::UpdatesFromGallery(extension)) {
return SYNC_TYPE_NONE;
}
if (PluginInfo::HasPlugins(extension) ||
extension->HasAPIPermission(APIPermission::kPlugin)) {
return SYNC_TYPE_NONE;
}
switch (extension->GetType()) {
case Manifest::TYPE_EXTENSION:
return SYNC_TYPE_EXTENSION;
case Manifest::TYPE_USER_SCRIPT:
if (ManifestURL::UpdatesFromGallery(extension))
return SYNC_TYPE_EXTENSION;
return SYNC_TYPE_NONE;
case Manifest::TYPE_HOSTED_APP:
case Manifest::TYPE_LEGACY_PACKAGED_APP:
case Manifest::TYPE_PLATFORM_APP:
return SYNC_TYPE_APP;
case Manifest::TYPE_UNKNOWN:
case Manifest::TYPE_THEME:
case Manifest::TYPE_SHARED_MODULE:
return SYNC_TYPE_NONE;
}
NOTREACHED();
return SYNC_TYPE_NONE;
}
| 171,248 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info,
size_t count, const uint64_t clsid[2])
{
size_t i;
cdf_timestamp_t tp;
struct timespec ts;
char buf[64];
const char *str = NULL;
const char *s;
int len;
if (!NOTMIME(ms))
str = cdf_clsid_to_mime(clsid, clsid2mime);
for (i = 0; i < count; i++) {
cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
switch (info[i].pi_type) {
case CDF_NULL:
break;
case CDF_SIGNED16:
if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf,
info[i].pi_s16) == -1)
return -1;
break;
case CDF_SIGNED32:
if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf,
info[i].pi_s32) == -1)
return -1;
break;
case CDF_UNSIGNED32:
if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf,
info[i].pi_u32) == -1)
return -1;
break;
case CDF_FLOAT:
if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf,
info[i].pi_f) == -1)
return -1;
break;
case CDF_DOUBLE:
if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf,
info[i].pi_d) == -1)
return -1;
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
len = info[i].pi_str.s_len;
if (len > 1) {
char vbuf[1024];
size_t j, k = 1;
if (info[i].pi_type == CDF_LENGTH32_WSTRING)
k++;
s = info[i].pi_str.s_buf;
for (j = 0; j < sizeof(vbuf) && len--;
j++, s += k) {
if (*s == '\0')
break;
if (isprint((unsigned char)*s))
vbuf[j] = *s;
}
if (j == sizeof(vbuf))
--j;
vbuf[j] = '\0';
if (NOTMIME(ms)) {
if (vbuf[0]) {
if (file_printf(ms, ", %s: %s",
buf, vbuf) == -1)
return -1;
}
} else if (str == NULL && info[i].pi_id ==
CDF_PROPERTY_NAME_OF_APPLICATION) {
str = cdf_app_to_mime(vbuf, app2mime);
}
}
break;
case CDF_FILETIME:
tp = info[i].pi_tp;
if (tp != 0) {
char tbuf[64];
if (tp < 1000000000000000LL) {
cdf_print_elapsed_time(tbuf,
sizeof(tbuf), tp);
if (NOTMIME(ms) && file_printf(ms,
", %s: %s", buf, tbuf) == -1)
return -1;
} else {
char *c, *ec;
cdf_timestamp_to_timespec(&ts, tp);
c = cdf_ctime(&ts.tv_sec, tbuf);
if (c != NULL &&
(ec = strchr(c, '\n')) != NULL)
*ec = '\0';
if (NOTMIME(ms) && file_printf(ms,
", %s: %s", buf, c) == -1)
return -1;
}
}
break;
case CDF_CLIPBOARD:
break;
default:
return -1;
}
}
if (!NOTMIME(ms)) {
if (str == NULL)
return 0;
if (file_printf(ms, "application/%s", str) == -1)
return -1;
}
return 1;
}
Commit Message: Apply patches from file-CVE-2012-1571.patch
From Francisco Alonso Espejo:
file < 5.18/git version can be made to crash when checking some
corrupt CDF files (Using an invalid cdf_read_short_sector size)
The problem I found here, is that in most situations (if
h_short_sec_size_p2 > 8) because the blocksize is 512 and normal
values are 06 which means reading 64 bytes.As long as the check
for the block size copy is not checked properly (there's an assert
that makes wrong/invalid assumptions)
CWE ID: CWE-119 | cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info,
size_t count, const cdf_directory_t *root_storage)
{
size_t i;
cdf_timestamp_t tp;
struct timespec ts;
char buf[64];
const char *str = NULL;
const char *s;
int len;
if (!NOTMIME(ms) && root_storage)
str = cdf_clsid_to_mime(root_storage->d_storage_uuid, clsid2mime);
for (i = 0; i < count; i++) {
cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
switch (info[i].pi_type) {
case CDF_NULL:
break;
case CDF_SIGNED16:
if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf,
info[i].pi_s16) == -1)
return -1;
break;
case CDF_SIGNED32:
if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf,
info[i].pi_s32) == -1)
return -1;
break;
case CDF_UNSIGNED32:
if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf,
info[i].pi_u32) == -1)
return -1;
break;
case CDF_FLOAT:
if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf,
info[i].pi_f) == -1)
return -1;
break;
case CDF_DOUBLE:
if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf,
info[i].pi_d) == -1)
return -1;
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
len = info[i].pi_str.s_len;
if (len > 1) {
char vbuf[1024];
size_t j, k = 1;
if (info[i].pi_type == CDF_LENGTH32_WSTRING)
k++;
s = info[i].pi_str.s_buf;
for (j = 0; j < sizeof(vbuf) && len--;
j++, s += k) {
if (*s == '\0')
break;
if (isprint((unsigned char)*s))
vbuf[j] = *s;
}
if (j == sizeof(vbuf))
--j;
vbuf[j] = '\0';
if (NOTMIME(ms)) {
if (vbuf[0]) {
if (file_printf(ms, ", %s: %s",
buf, vbuf) == -1)
return -1;
}
} else if (str == NULL && info[i].pi_id ==
CDF_PROPERTY_NAME_OF_APPLICATION) {
str = cdf_app_to_mime(vbuf, app2mime);
}
}
break;
case CDF_FILETIME:
tp = info[i].pi_tp;
if (tp != 0) {
char tbuf[64];
if (tp < 1000000000000000LL) {
cdf_print_elapsed_time(tbuf,
sizeof(tbuf), tp);
if (NOTMIME(ms) && file_printf(ms,
", %s: %s", buf, tbuf) == -1)
return -1;
} else {
char *c, *ec;
cdf_timestamp_to_timespec(&ts, tp);
c = cdf_ctime(&ts.tv_sec, tbuf);
if (c != NULL &&
(ec = strchr(c, '\n')) != NULL)
*ec = '\0';
if (NOTMIME(ms) && file_printf(ms,
", %s: %s", buf, c) == -1)
return -1;
}
}
break;
case CDF_CLIPBOARD:
break;
default:
return -1;
}
}
if (!NOTMIME(ms)) {
if (str == NULL)
return 0;
if (file_printf(ms, "application/%s", str) == -1)
return -1;
}
return 1;
}
| 166,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
Commit Message:
CWE ID: CWE-119 | int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
if (num_elements > PIPE_MAX_ATTRIBS)
return EINVAL;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
| 164,954 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 am_check_url(request_rec *r, const char *url)
{
const char *i;
for (i = url; *i; i++) {
if (*i >= 0 && *i < ' ') {
/* Deny all control-characters. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,
"Control character detected in URL.");
return HTTP_BAD_REQUEST;
}
}
return OK;
}
Commit Message: Fix redirect URL validation bypass
It turns out that browsers silently convert backslash characters into
forward slashes, while apr_uri_parse() does not.
This mismatch allows an attacker to bypass the redirect URL validation
by using an URL like:
https://sp.example.org/mellon/logout?ReturnTo=https:%5c%5cmalicious.example.org/
mod_auth_mellon will assume that it is a relative URL and allow the
request to pass through, while the browsers will use it as an absolute
url and redirect to https://malicious.example.org/ .
This patch fixes this issue by rejecting all redirect URLs with
backslashes.
CWE ID: CWE-601 | int am_check_url(request_rec *r, const char *url)
{
const char *i;
for (i = url; *i; i++) {
if (*i >= 0 && *i < ' ') {
/* Deny all control-characters. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,
"Control character detected in URL.");
return HTTP_BAD_REQUEST;
}
if (*i == '\\') {
/* Reject backslash character, as it can be used to bypass
* redirect URL validation. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,
"Backslash character detected in URL.");
return HTTP_BAD_REQUEST;
}
}
return OK;
}
| 169,749 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SetUpTestCase() {
input_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1;
output_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
}
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 void SetUpTestCase() {
input_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1;
output_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
output_ref_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
#if CONFIG_VP9_HIGHBITDEPTH
input16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment,
(kInputBufferSize + 1) * sizeof(uint16_t))) + 1;
output16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t)));
output16_ref_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t)));
#endif
}
| 174,506 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.